My task is:
Write a program that reads integers until 0 is entered. After input terminates, the program should report the total number of even integers (excluding the 0) entered, the average value of the even integers, the total number of odd integers entered, and the average value of the odd integers.
But I had to use switch for this...
My code is:
#include <stdio.h>
int main(void)
{
int oddIndex = 0, evenIndex = 0, evenTotal = 0, evenSum, oddTotal = 0, oddSum;
int userInput;
int oddArray[oddIndex], evenArray[evenIndex];
printf("please enter some numbers: \n");
while (((scanf("%d", &userInput)) == 1) && (userInput != 0))
{
switch (userInput%2)
{
case 0:
evenArray[evenIndex] = userInput;
evenIndex++;
evenTotal++;
evenSum += userInput;
break;
default:
oddArray[oddIndex] = userInput;
oddIndex++;
oddTotal++;
oddSum += userInput;
break;
};
}
if (evenTotal > 0)
printf("even total: %d, even average: %d\n", evenTotal, evenSum/evenTotal);
else
printf("there is no even numbers!\n");
if (oddTotal > 0)
printf("odd total: %d, odd average: %d", oddTotal, oddSum/oddTotal);
else
printf("there is no odd numbers!");
}
Is this code ok?
switch
for a 2-case scenario; anif-else
would be more appropriate. – seand Jan 28 at 23:48