In this tutorial, you will learn how to write a C program to check whether a given input is a digit or not by using if-else. Along with the program, we will also learn various examples, algorithms, and fully explained program.
Problem Statement
The program should take the input from the user. It should prompt the user to enter a character and determine whether the entered character is a digit or not.
For Example
Enter a character: 7
Output: The input is a digit.
Algorithm
- Declare a variable
input
of type char to store the user input. - Display a prompt asking the user to enter a character.
- Read the character entered by the user and store it in the
input
variable. - Use an if-else statement to check if
input
is between ‘0’ and ‘9’. - If the condition is true, print “The input is a digit.”
- If the condition is false, print “The input is not a digit.”
- Return 0 to indicate successful execution of the program.
Program to check a given input is digit or not
#include <stdio.h>
int main() {
char input;
printf("Enter a character: ");
scanf("%c", &input);
if (input >= '0' && input <= '9') {
printf("The input is a digit.\n");
} else {
printf("The input is not a digit.\n");
}
return 0;
}
Output 1
Enter a character: aa
The input is not a digit
Output 2
Enter a character: 2
The input is a digit
Program Explanation
The program starts by declaring a variable input
of type char to hold the user input. It then prompts the user to enter a character and reads the input using the scanf
function. After taking the value from the user it will be stored in the input
variable.
Next, the program uses an if-else statement of C to check if the input character is a digit. The condition input >= '0' && input <= '9'
checks if the ASCII value of input
falls within the range of ‘0’ to ‘9’. If the condition is true, it prints “The input is a digit.” Otherwise, it prints “The input is not a digit.”
Conclusion
This C program allows users to enter a character and check whether it is a digit or not using if-else statements. It provides a simple and straightforward way to determine the digit status of the input character.