Skip to main content

Section 9.6 if - else-if - else Statements

What if there are more than two cases, amongst which we’d like to distinguish?
Take a look at the following example:

Compile and run the code below in your own C environment.

#include <stdio.h>

int main(void) {
    
    int age = 5;
    
    if (age<1)
        printf("Infant\n");
    else if (age<3)
        printf("Toddler\n");
    else if (age<13)
        printf("Child\n");
    else if (age<18)
        printf("Teen\n");
    else
        printf("Adult\n");
    
    return(0);
}
Figure 9.1.

Check Your Understanding Check Your Understanding

1.

Complete the following C program: After the user has entered a number, assign a score (use the variable "score" which has already been defined for this purpose) to the user input as follows: If the user enters a number less than 10 the score should be -1, if the user enters a number greater than 20 the score should be 1, and if the user enters a number between 10 and 20 the score should be 0. Then print the user’s score to the screen.

Compile and run the code below in your own C environment.

#include <stdio.h>

int main(void) {
   float number;
   int score;
   number = 1;

   printf("Please enter a number: ");
   scanf("%f", &number);

   /* Your code here. */


    printf("Your score is %d.", score);
    return(0);
}
When your program performs correctly you’ll be given a keyword to enter in Canvas.