:) Hi, Ive written a program that is supposed to count the number of people of different ages and calculate the average of valid ages. We exclude ages entered as 0, over 130 or negative.
The program does run but I sometimes don't have the right number in the different categories. I suppose this is because of my IF statements. Also the average doesn't calculate.

I don't see the problem, please help?
Here's what I have

#include <stdio.h>

int main()
{
    // variable declaration
    int i,nb, sum, total;
    int min=0, adu=0, ret=0, cent=0, invalid=0;  
    float avg; 
    
    
    printf("Enter 7 ages followed by ENTER after each: \n");
    scanf("%d", &nb);
    
    //execution
    for (i=1; i<7;++i){
        scanf("%d", &nb);
        
        if(nb>0 && nb<18){            //minors
        total += nb;
          min++;
}
        if (nb>=18 && nb<55){        // adults
        total+=nb;
        adu++;
}
        if (nb>=55 && nb<120){        // retirees
        total +=nb;
        ret++;
}
        if (nb>=100 && nb<120){         // 100 & over
        cent++;
}
        else if(nb<=0 || nb>=120){     // invalid
        invalid++;
}
}      
       // calculations
       sum=(min+ret+adu);
       avg=(total/sum;

       // output
       
     printf("\n Number of minors            : %d",min);
     printf("\n Number of retirees          : %d",ret);
     printf("\n Number of people 100 or over: %d",cent);
     printf("\n Invalid ages                : %d",invalid);
     printf("\n Average age                 : %f", avg);
     getch();
}

Thank you for any help!

Comments
used code tags correctly :)

line 39 is missing close parentheses -- ) Also you need to typecast total and sum to float to prevent loss of precision.

line 6: you are using uninitialized variables

Your program would run a bit better (faster and efficiently) if you used else if.

line 39 is missing close parentheses -- ) Also you need to typecast total and sum to float to prevent loss of precision.

line 6: you are using uninitialized variables

Your program would run a bit better (faster and efficiently) if you used else if.

Thanks for the reply. Sorry about the missing tags in my first post.
I figured it out on my own about the sum and total needed to be floats. I also removed the first scanf(line 12) which wasn't needed.
Sent in my finished program at University this morning so can't change my if to else if .
My teacher never told us about this. We have no textbook, only a small booklet of notes which aren't even his.
Do you know a good textbook on C programming? I have my first mid term next week.
Thanks again :)

This article has been dead for over six months. Start a new discussion instead.