hey guys..I'm trying to teach myself to writee code using C. The program I am working on now is to write a program that prompts a user for his/her age and then prints a message
based upon the age range that the user’s age falls into

here is the age rages...
Age Range Output
0 < age ≤ 20 You are a child.
20 < age ≤ 40 You are a young adult.
40 < age ≤ 60 You are a middle-aged adult.
60 < age You are old.

#include <stdio.h>

int main( void )
{
    int age;
    printf("what is your age?  ");
    scanf("%d", &age);

}

this is what I have so far

What you have looks good, except for a couple of nits:

>printf("what is your age? ");
>scanf("%d", &age);
There's no guarantee that the prompt will be shown before scanf starts blocking for input. Which means that on some systems, all the user will see is a blinking cursor and they won't know what to do. You can fix that by flushing stdout:

printf ( "What is your age? " );
fflush ( stdout );
scanf ( "%d", &age );

Alternatively, whenever a newline is printed the stream is flushed automatically, so you could do this (though it's not as pretty):

printf ( "What is your age?\n" );
scanf ( "%d", &age );

>}
main returns an int, which you already know because you've specified int as the return type. So you also need to return a value. 0 is standard and portable for a successful return:

#include <stdio.h>

int main ( void )
{
  int age;

  printf ( "What is your age? " );
  fflush ( stdout );
  scanf ( "%d", &age );

  return 0;
}

If you include <stdlib.h> you also have access to the macros EXIT_SUCCESS and EXIT_FAILURE, which are also portable and self-explanatory.

Presumably the actual problem you're having is figuring out how to print the messages depending on the value of age. What you need to look for in your book (you do have a book on C, right?) is if, else if, and else. Also, the logical AND (&& operator) will help your code look like your requirements. The if statements can be chained together to give you something like this:

if ( 0 < age && age <= 20 ) {
  puts ( "You are a child." );
}
else if ( 20 < age && age <= 40 ) {
  puts ( "You are a young adult." );
}
else if ( 40 < age && age <= 60 ) {
  puts ( "You are a middle-aged adult." );
}
else {
  puts ( "You are old." );
}

before today I had never heard of the fflush command. I knew of the if and else statements...it was the && that was really confusing me the most...

thank you for all your help!!!!!!

if I have anymore questions I will come back for help...

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