×

C++ Tutorial

C++ Data types

C++ Operators & Keywords

C++ Conditional Statements

C++ Functions

C++ 'this' Pointer, References

C++ Class & Objects

C++ Constructors & Destructors

C++ Operator overloading

C++ 11 (Advance C++)

C++ Preparation

C++ Header Files & Functionsr

Data Structure with C++

C++ - Miscellaneous

C++ Programs

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++.

C++ - Ladder if-else statement

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

Example: Check whether a entered character is valid alphabet or not

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

Condition to check alphabet

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).

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

Condition to check digits

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

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

C++ Program to check whether a entered character is valid alphabet or not

#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 

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.