C Programming Examples Tutorial Index

C String Programs

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 for accepting a number in a given range.

Program:

#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("
    The 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(" Enter a number between 1 to 9 ");
    scanf("%d", &number);
    return (number);
}

Program 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 the desired range) or shows an error message(the number is out of range).



Found This Page Useful? Share It!
Get the Latest Tutorials and Updates
Join us on Telegram