Checking for Digit using if else – Computer Sir Ki Class

Code Learning #CPP#1865

## Checking for Digit using if else

Collecting a char input and checking the input as a digit or a non-digit.

## Learning Objectives

• Learning the range check for a digit.
• Learning to find an alternate path when given selection condition is not true using the else keyword.

## Program Approach

• A digit would be essentially in the range of 0 to 9 so the condition check will be formed as character greater or equal to ‘0’ and lesser or equal to ‘9’.

## Source Code

 #include using namespace std; int main( ) { char d; cout<<"Enter a character : "; cin>>d; if(d >= '0' && d<='9') cout<<"You entered a digit"<

## Run Output

``````Enter a character : 5
You entered a digit

-OR-
Enter a character : a
Character you entered was not a digit
``````

## Code Understanding

char d; cout<<“Enter a character : “; cin>>d;
Here we collect the input as a single character from the user.

if(d >= ‘0’ && d<=’9′)
Here we check if the character entered is between the range 0 to 9 as all the digit characters are supposed to be in that range only.

cout<<“You entered a digit”<<endl;
Here we print the message announcing that the number entered by the user was a digit.

else
This one is to give an alternate selection path when given condition of checking for digit is not true.

cout<<“Character you entered was not a digit”<<endl;
When the given condition is not true this message is printed.

## Notes

• For digit check one can also check using the ascii  value 48 to 57. The same condition may also be written like if( d>= 48 && d<=57).

Suggested Filename(s): checkdigit.cpp

sunmitra| Created: 22-Dec-2017 | Updated: 15-Sep-2018|

×