Reads integers until 0 is entered - C Statement

C examples for Statement:while

Introduction

Report on the following:

  • 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.

Demo Code

  
#include <stdio.h>  
int main(void)      
{  //w  w w  .j  av a 2 s.c o  m
     int n;  
     double sumeven = 0.0;  
     int ct_even = 0;  
     double sumodd = 0.0;  
     int ct_odd = 0;  
        
     while (scanf("%d", &n) == 1 && n != 0)  
     {  
         if (n % 2 == 0)  
         {  
             sumeven += n;  
             ++ct_even;  
         }  
         else  // n % 2 is either 1 or -1  
         {  
              sumodd += n;  
             ++ct_odd;  
        }  
     }  
     printf("Number of evens: %d", ct_even);  
     if (ct_even > 0)  
         printf("  average: %g", sumeven / ct_even);  
     putchar('\n');  
           
     printf("Number of odds: %d", ct_odd);  
     if (ct_odd > 0)  
         printf("  average: %g", sumodd / ct_odd);  
     putchar('\n');  
     printf("\ndone\n");  
       
    return 0;  
}

Result


Related Tutorials