Control Structures
Control Structures
#include <iostream>
int main()
int i = 10;
if (i < 15) {
Explanation:
Program starts.
i is initialized to 10.
If-condition is checked. 10 < 15, yields true.
“10 is less than 15” gets printed.
if condition yields false. “I am Not in if” is printed.
2, if … else statement
Syntax
if (condition)
{
// Executes this block if
// condition is true
}
else
{
// Executes this block if
// condition is false
}
Flowchart for if … else statement
#include <iostream>
int main()
int i = 20;
// Check if i is 10
if (i == 10)
else
return 0;
Explanation:
Program starts.
i is initialized to 20.
if-condition is checked. i == 10, yields false.
flow enters the else block.
“i is 20” is printed
“Outside if-else block” is printed.
Example 2:
#include <iostream>
int main()
{
int i = 25;
if (i > 15)
else
return 0;
Syntax
if (condition)
statement 1;
else if (condition)
statement 2;
.
.
else
statement;
// C++ program to illustrate if-else-if ladder
#include <iostream>
using namespace std;
int main()
{
int i = 20;
// Check if i is 10
if (i == 10)
cout << "i is 10";
// Since i is not 10
// Check if i is 15
else if (i == 15)
cout << "i is 15";
// Since i is not 15
// Check if i is 20
else if (i == 20)
cout << "i is 20";
return 0;
}
Flowchart for if … else if … else statement
Examples of if else if the ladder
#include <iostream>
int main()
int i = 20;
// Check if i is 10
if (i == 10)
// Since i is not 10
// Check if i is 15
else if (i == 15)
// Since i is not 15
// Check if i is 20
else if (i == 20)
else
return 0;
}
Explanation:
Program starts.
i is initialized to 20.
condition 1 is checked. 20 == 10, yields false.
condition 2 is checked. 20 == 15, yields false.
condition 3 is checked. 20 == 20, yields true. “i is 20” gets printed.
“Outside if-else-if” gets printed.
Program ends.
Example 2:
Another example to illustrate the use of if else if ladder in C++.
#include <iostream>
int main()
int i = 25;
else