C - Check value range of user input

Introduction

In the following program, the user enters a number between 1 and 10 and the output tells the user how that number relates to 5 or 6:

Demo

#include <stdio.h>

int main(void)
{
      int number = 0;
      printf("\nEnter an integer between 1 and 10: ");
      scanf("%d",&number);

      if(number > 5)
        printf("You entered %d which is greater than 5\n", number);

      if(number < 6)
        printf("You entered %d which is less than 6\n", number);
      return 0;//w w  w.j  a va  2s . com
}

Result

how It Works

With the first three statements in main(), you read an integer from the keyboard after prompting the user for the data:

int number = 0;
printf("\nEnter an integer between 1 and 10: ");
scanf("%d",&number);

An integer variable called number is initialized to 0.

Then you prompt the user to enter a number between 1 and 10. This value is then read using the scanf() function and stored in number.

The next statement is an if that tests the value that was entered:

if(number > 5)
  printf("You entered %d which is greater than 5\n", number);

You compare the value in number with the value 5. if number is greater than 5, you execute the next statement, which displays a message.

Then you go to the next part of the program.

if number isn't greater than 5, the printf() is skipped.

You've used the %d conversion specifier for integer values to output the number the user typed in.

Related Topic