Home » C++ programming language

A simple example of ladder if-else statement in C++

Ladder if-else statement example in C++: program to enter a character and validate whether it is an alphabet or digit, here we are using ladder if-else (multiple if-else) form of conditional statements in C++.

Ladder if-else statement

When we have multiple conditions to check, we use this form of if-else.

In this program: We will check whether a entered character is valid alphabet or not?

1) Condition to check alphabet

(ch>='a'&& ch<='z') || (ch>='A' && ch<='Z')

Character is greater than or equal to 'a' (lowercase) and less than or equal to 'z' (lowercase) or character is greater than or equal to 'A' (Uppercase) and less than or equal to 'Z' (Uppercase).

2) Condition to check digits

(ch>='0' && ch<='9')

Character is greater than or equal to '0' and less than or equal to '9'.

Consider the program:

#include<iostream>
using namespace std;

int main()

{	char ch;

	//input a character
	cout<<"Enter a character: ";
	cin>>ch;

	
	//condition to validate character is an alphabet
	if( (ch>='a'&& ch<='z') || (ch>='A' && ch<='Z'))
	{	
		cout<<"Entered character is an alphabet";
	}
	//condition to validate character is a digit
	else if(ch>='0' && ch<='9')
	{	
		cout<<"Entered character is a digit";
	}
	//other characters are not valid character
	else
	{	
		cout<<"Enter a valid character";
	}
	
	cout<<endl;
	
	return 0;
}

Output

First run:
Enter a character: W
Entered character is an alphabet

Second run:
Enter a character: i
Entered character is an alphabet

Third run:
Enter a character: 7
Entered character is a digit

Fourth run:
Enter a character: +
Enter a valid character 





Was this page helpful? YES NO

Are you a blogger? Join our Blogging forum.



Comments and Discussions


We are using Google to publish ads on our website; Google has its own privacy policies. They may save log, cookies on your system. Google may also collect information of your system like IP address, region, city, country. For more details please go through the Google’s privacy policy.