Hi, I just picked a book recently and try to teach myself C, so I am new to this.
The problem I am trying to solve is to write a program that reads integers until 0 is entered.
And then, terminates the program and count even(exclude 0) and odd numbers as well as their averages.
Below is my code. It's working, but what I don't understand is that if I use even_count instead of (even_count-1), I will have 1 more even number than I wanted. Can someone please let me know if my logic is wrong?
Code:
#include <stdio.h>
int main(void)
{
int num,a;
int even_count = 0;
int odd_count = 0;
int even_sum = 0;
int odd_sum = 0;
while (num !=0)
{
printf("Please enter a number (0 to stop):\n");
a = scanf("%d", &num);
if (a = 0)
goto terminate;
else
{
if ( (num%2)!=0)
{
odd_count++;
odd_sum = num +odd_sum;
}
else
{
even_count++;
even_sum += num;
}
}
}
terminate: printf("prgram terminated.\n\n");
printf("odd count: %d ; even count: %d\n", odd_count, even_count-1);
printf("odd sum: %d ; even sum: %d\n", odd_sum/odd_count, even_sum/(even_count-1));
system ("pause");
return 0;
}