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.#includeIn 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.
using namespace std;
main()
{
int num1, num2, large;
cout cin>>num1;
cout cin>>num2;
if
(num1 > num2)
large = num1;
else
large = num2;
coutreturn 0;
} // 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.
#includeOutput of the Program:
using namespace std;
main()
{
int num;
clrscr ();
cout cin>>num;
if (num%2==0)
cout else
cout cout return 0;
}
(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.
#includeOutput of the Program:
using namespace std;
main()
{
int year;
clrscr ();
cout cin>>num;
if (year%4==0) //leap year divisible by 4
cout else
cout return 0;
}
(suppose we entered 2020)
Enter a year: 2020
2020 is a leap yaer.