Control Structures 204
Control Structures 204
Syntax
if(condition)
{
// Statements to execute if
// condition is true
}
#include <iostream>
using namespace std;
int main()
{
int i = 10;
if (i < 15) {
cout << "10 is less than 15 \n";
}
Syntax
if (condition)
{
// Executes this block if
// condition is true
}
else
{
// Executes this block if
// condition is false
}
#include <iostream>
using namespace std;
int main()
{
int i = 20;
// Check if i is 10
if (i == 10)
cout << "i is 10";
// Since is not 10
// Then execute the else statement
else
cout << "i is 20\n";
return 0;
}
3. Multiple Alternatives
The if-else-if ladder helps the user decide from among multiple options. The C+
+ if statements are executed from the top down. As soon as one of the conditions
controlling the if is true, the statement associated with that if is executed, and the
rest of the C++ else-if ladder is bypassed. If none of the conditions is true, then
the final statement will be executed.
This structure has the form:
If (condition A), then:
[Module A]
Else if (condition B), then:
[Module B]
..
..
Else if (condition N), then:
[Module N]
[End If structure]
// 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;
}
Repeat-For Structure
In C++, for loop is an entry-controlled loop that is used to execute a block of
code repeatedly for the specified range of values. Basically, for loop allows you
to repeat a set of instructions for a specific number of iterations.
for loop is generally preferred over while and do-while loops in case the number
of iterations is known beforehand.
This structure has the form:
Repeat for i = A to N by I:
[Module]
[End of loop]
Here, A is the initial value, N is the end value and I is the increment. The loop
ends when A>B. K increases or decreases according to the positive and negative
value of I respectively.
#include <iostream>
using namespace std;
int main()
{
// initializing n (value upto which you want to print
// numbers
int n = 5;
int i; // initialization of loop variable
for (i = 1; i <= n; i++) {
cout << i << " ";
}
return 0;
}
Repeat-While Structure
It also uses a condition to control the loop. This structure has the form:
Repeat while condition:
[Module]
[End of Loop]