Skip to main content

Write a C Program That Requests an Integer Value from the User. (Code and Explanation)

Write a C program that requests an integer value from the user. If the value is between 1 and 100, print “OK;” otherwise, print “Out of range”.


(explanation for code at the bottom of the post)



If you run it in Visual Studio, you will get this screen:



If you enter any number between 1 and 100 (1 and 100 included), you will get something like this:


( I entered 24)


However, if you enter a letter or any number outside the defined ranger (1-100), you will get this screen accompanied by sound alert:




Ok! let's break the code down line by line:


int userInput;

We defined an integer variable named userInput, this is where the value entered by user will be stored. int stands for integer.

--------------------------------------------------------------------------

printf("Enter an integer value between 1 and 100: ");
scanf_s("%d" , &userInput);



We wrote a printf line to display a prompt to the user asking him to enter an integer value between 1 and 100.

We wrote the scanf_s line to obtain the number from the user to store it in userInput.

--------------------------------------------------------------------------


if (userInput <= 100 && userInput >= 1)
{
printf("Ok!\n");
}
else if (userInput > 100 || userInput <1)
{
printf("Error! Out of Range...");
}



We wrote the if - else if syntax to compare the value entered by user with the acceptable range. If the user input anything from 1 to 100, the program will display the following message: "Ok!"

However, if the user enters any number outside of the acceptable range (1-100) or any letter, the program will display the following message: "Error! Out of Range..."