The if-else
statement is a conditional statement with an optional else. The if statement executes a block of statements is the condition is true, but does not do anything when condition is false. The if-else block contains code for both true and false conditions.
Each of the block in if-else
construct will be enclosed using braces( { } ). The general form of if-else is given below.
if(expression)
{
statement1;
statement2;
}
else
{
statement3;
statement4;
}
Clearly, the a program executes if
block when expression = true and executes else
block when expression = false.
Example Program: if-else
// example program to demostrate if-else
#include <cstdlib>
#include <iostream>
using namespace std;
int main()
{
//Variable Declaration
int x,y,total;
//Variable Initialization
x = 100;
y = 200;
total = 0;
//the if-else block
if(x < 100)
{
total = x + y;
}
else
{
total = y - x;
}
//Printing the output
cout << "Total =" << total << endl;
system("PAUSE");
return EXIT_SUCCESS;
}
Output:
Total =100
In the above example, the condition x < 100
is false. As a result, the else
block is executed giving an output 100.
Types of if-else Constructs
There are several ways to construct if-else structure. Here is a list of possible constructs.
#1
if(expression)
{
statement1;
statement2;
}
else
{
statement3;
}
#2
if(expression)
{
if(expression)
{
statement1;
statement2;
} else {
statement3;
}
}
else
{
statement4;
}
#3
if(expression)
{
if(expression)
{
statement1;
}
else
{
statement2;
}
}
else
{
if(expression)
{
statement3;
}
else
{
statement4;
}
}
#4
if(expression)
{
}
else if(expression)
{
}
else if(expression)
{
}
else if(expression)
{
}
You can create different kinds of if-else
constructs which one of the above construct as building blocks.