How Can You Efficiently Count Age Groups in C Programming?

AI Thread Summary
To efficiently count age groups in C programming, the code initializes counters for each age category and uses a while loop to continuously accept age inputs until -1 is entered. The user should place the input prompt and scanf function inside the loop to allow for multiple entries. A common compilation error arises from missing a closing curly brace for the while loop, which needs to be corrected. Proper indentation is also emphasized for better readability and structure of the code. Following these adjustments will help the program compile successfully and function as intended.
clook
Messages
32
Reaction score
0
the assignment wants me to count the number of people in age groups and to report the number of people in each group.

i came up with this, used an int for each group and incremented with if/else if statements.

Code:
#include<stdio.h>
main()
{
      int x, infant, young, middleaged, old, older, reallyold;
      infant = 0;
      young = 0;
      middleaged = 0;
      old = 0;
      older = 0;
      reallyold = 0;
      printf("Please enter ages (Enter -1 to quit): ");
      scanf("%d", x);
	  while (x != -1)
    {
      if (x <= 16)
      infant++;
      else if (x <= 29)
      young++;
      else if (x <= 55)
      middleaged++;
      else if (x <= 75)
      old++;
      else if (x <= 99)
      older++;
      else if (x > 99)
      reallyold++;
      printf("Number of infants: %d \n", infant);
      printf("Number of young people: %d \n", young);
      printf("Number of middle aged people: %d \n", middleaged);
	  printf("Number of old people: %d \n", old);
	  printf("Number of older people: %d \n", older);
	  printf("Number of really old people: %d \n", reallyold);}

though I'm not sure if its exactly right.. and it won't let me compile.

i keep getting the "unexpected end of file" error. please help? :)i also want to make it so that you can enter as many ages as you want, but I'm not sure what kind of loop i should use for that.
 
Last edited:
Physics news on Phys.org
You should move the lines
printf("Please enter ages (Enter -1 to quit): ");
scanf("%d", x);
to just inside the while loop, not just outside it. Then you'll also have to initialize x to something other than -1. The reason it's not compiling is you forgot the closing curly brace } on the while loop.

Also you should use proper indentation. The while keyword itself should be the same indentation as the stuff before it, and the contents of the loop should be indented one more. Also if you have an "if" statement, the body of the statement should be indented one more than the "if" statement, like.
Code:
while X
{
    if A
        B
    else if C
        D
    else if G
        E
    other stuff here
}
 

Similar threads

Replies
12
Views
2K
Replies
3
Views
1K
Replies
12
Views
2K
Replies
1
Views
10K
Replies
5
Views
2K
Replies
9
Views
4K
Replies
3
Views
2K
Replies
1
Views
4K
Back
Top