The "if-else" structure is another form of if statement that is specially used for making two way decision. In its structure, one test condition and two blocks of statements are used to make decision. When the given condition is true, the first block is Executed whereas other block is ignored. Similarly, second block is executed if the given condition becomes false.
Declaration
In C++, the general syntax of 'if-else' is as follows:if (test_condition)Where:
first_statement;
else
second_statement;
test_condition | It indicates the test conditions that can be logical expression or relational expression. |
first_statement | It will be executed if the given condition is true and second_statement will be ignored. |
second_statement | If the given condition is false, this statement will be executed and first_statement will be ignored. |
if (condition or set of conditions)In the above syntax, " group_of_statement_1 and group_of_statement_2 " indicates set of statement that will be executed or ignored according to the test condition.
{
group_of_statement_1
}
else
{
group_of_statement_2
}
Flowchart
The flowchart of C++ if else structure is as follows:Example Programs
Example 1: The following source code of the program inputs two values from the user and finds the large value from them.In the above program, num1, num2 and large are tree variables of integer data type. When the user enter two values, then if condition (num1 > num 2) is evaluate, suppose, we entered 5 and 3 respectively, then the condition looks like "5 > 4" which is absolutely true, in this case, "num1" value assigned to the variable "large" and its result will be display as large value.
#include
#include
main()
{
int num1, num2, large;
clrscr();
cout
cin>>num1;
cout
cin>>num2;
if
(num1 > num2)
large = num1;
else
large = num2;
cout
getch();
} // end main function
Example 2: The following program inputs a value and finds whether the entered value is even or odd by using if else.
#include
#include
main()
{
int num;
clrscr ();
cout
cin>>num;
if (num%2==0)
cout
else
cout
cout
getch();
}
Output of the Program:(suppose we entered 20)
Enter value: 20
20 is even number
Done
Example 3: The following program inputs a year and finds whether it is leap year or not.
Output of the Program:
#include
#include
main()
{
int year;
clrscr ();
cout
cin>>num;
if (year%4==0) //leap year divisible by 4
cout
else
cout
getch();
}
(suppose we entered 2020)
Enter a year: 2020
2020 is a leap yaer.