Online visitors

People learning around the world

Online

—

Visitors exploring W3Schools

Online visitors by country Circles show approximate country locations. The country list provides the visitor counts.

Circles represent countries, not exact visitor locations.

Country

Online

Loading country activity…

    C Program to Asks the User For a Number Between 1 to 9

    C Programming Examples


    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

    Notifications

    Updates are enabled for this browser.

    Receive new tutorials, articles and learning resources. You can turn updates off anytime.