Thursday, December 13

Program for accepting a number in a given range


Write a C program which asks the user for a number between 1 to 9 and shows the number. If the user inputs a number out of the specified range, the program should show an error and prompt the user for a valid input.

Program: Program for accepting a number in a given range.

#include<stdio.h>
int getnumber();
int main() 
{
int input = 0;
//call a function to input number from key board
input = getnumber();
//when input is not in the range of 1 to 9,print error message
while (!((input <= 9) && (input >= 1))) 
{
printf("[ERROR] The number you entered is out of range");
//input another number
input = getnumber();
}
//this function is repeated until a valid input is given by user.
printf("\nThe number you entered is %d", input);
return 0;
}
//this function returns the number given by user
int getnumber() 
{
int number;
//asks user for a input in given range
printf("\nEnter a number between 1 to 9 \n");
scanf("%d", &number);
return (number);
}

Output:
Enter a number between 1 to 9
45
[ERROR] The number you entered is out of range
Enter a number between 1 to 9
4
The number you entered is 4

Explanation:
getfunction() function accepts input from user. 'while' loop checks whether the number falls within range or not
and accordingly either prints the number(If the number falls in desired range) or shows error message(number is
out of range).