The if-else-if structure is also known as nested if else structure or multiple if else structure. It is used to execute one block of statements from multiple blocks of statements.
In C++ if else if structure, multiple conditions and multiple blocks of statements are given. When any of the given condition is true, the statements associated with that condition are executed. In this case, all other blocks are ignored.
The general syntax of "if-else-if" structure is as follows:
if (condition-1)
{ Block-1 }
else if (condition-2)
{ Block-2 }
else if (condition-3)
{ Block-3 }
----------------
----------------
else if (condition-m)
{ Block-m }
else
{ Block-n}
Flowchart of if-else-if Structure
Following is the flowchart of C++ if else if structure:Read: Nested if statement in C++
Working of if else if Structure
In C++, the if else if structure is executed by following these rules:- The conditions are evaluated in the given sequence until a true condition is found.
- The statements associated with true condition are executed.
- The block of statements of following the last else is executed if all conditions are false.
If Else If Statement Example Programs
Example 1: The following program finds out whether a number is positive, negative or zero by using C++ if-else-if statement.
#include
#include
main()
{
int num;
clrscr();
cout
cin>>num;
if (num >0 )
cout
else if (num
cout
else
cout
getch();
}
In the above source code, "if-else-if" statement is used. Suppose the user enters a positive number, the number is tested with if statement. The answer is true because number is positive. The message is displayed on the screen and rest of the conditions will be ignored.Example 2: The following source code of the program inputs any character through keyboard and determines whether it is a capital letter, small letter, a digit or a special character symbol using logical operators and "if-else-if" statement.
Example 3: The following source code inputs three numbers and finds out the smallest number using logical operators and "if-else-if" statement.
#include
#include
main()
{
char ch;
clrscr();
cout
cin>>ch;
if (ch>='A' && ch
cout
else if (ch>= 'a' && ch
cout
else if (ch>= '0' && ch
cout
else
cout
getch();
}
Example 4: The following source code of program performs simple arithmetic calculations using "if-else-if" statement.
#include
#include
main()
{
int num1, num2, num3, mini;
clrscr();
cout
cin>>num1;
cout
cin>>num2;
cout
cin>>num3;
if (num1
mini = num1;
else if (num2
mini = num2;
else
mini = num3
cout
getch();
}
Output of the program:
#include
#include
main()
{
float n, m; char opt;
clrscr();
cout
cin>>n>>opt>>m;
if (opt == '-')
cout
else if (opt == '*')
cout
else if (opt == '/')
cout
else
cout
getch();
}
Enter first value, operator and second value:
4+6
10