Program for accepting a number in a given range.

28 Dec 2022 Balmiki Kumar 0 C Programming

C Program for Accepting a Number in a Given Range

Accepting a number in a given range" means writing a program in C that prompts the user to enter a number and ensures that the number falls within a specified range.

 

c 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).

BY: Balmiki Kumar

Related Blogs

Post Comments.

Login to Post a Comment

No comments yet, Be the first to comment.