Thread: Help: count even and odd numbers

  1. #1
    Registered User
    Join Date
    Mar 2011
    Posts
    2

    Help: count even and odd numbers

    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;
    }

  2. #2
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,909
    There are a few problems:
    You should avoid using goto. There are exceptions, but this isn't one of them.

    You need to use == for comparison, = for assignment. The result of if (a = 0) is whatever a is. You assign a to zero, so you always end up in the if block. Try
    Code:
    if (a == 0)
        break;
    else
        ...
    If somebody enters 0 for num, you still check for odd or even and increment the count. Since 0 % 2 is 0, you increment even_count. Try:
    Code:
    if (a == 0)
        break;
    else if (num != 0)
    {
        if ( (num%2)!=0)
        {
            odd_count++;
            odd_sum = num +odd_sum;
        }
        else
        {
            even_count++;
            even_sum += num;
        }
    }

Popular pages Recent additions subscribe to a feed