Control Structures
Control Structures are just a way to specify flow of control in programs.
There are three basic types of flow of control, known as:
Sequence logic, or sequential flow
Selection logic, or conditional flow
Iteration logic, or repetitive flow
Sequence Logic
Sequential logic as the name suggests follows a serial or sequential flow in which the flow depends on the series of instructions given to the computer.
Selection Logic (Branching)
Selection Logic simply involves a number of conditions which decides one out of several written statements.
Iteration Logic (Looping)
It helps to repeat a statement a certain number of times until the condition is satisfied.
Selection Logic (Branching)
Selection Logic simply involves a number of conditions which decides one out of several written statements.
If statement
If…else statement
If… else if statement
switch statement
if statement
« Use the if statement to specify a block of C++ code to be executed if
a condition is true.
Syntax
if (condition)
{
// block of code to be executed if the condition is true
) |
Example
#include <iostream.h>
void main()
{
if (20 > 18) {
cout << "20 is greater than 18";
)
)
If...else statement
- Use the if statement to specify a block of C++ code to be executed
if a condition is true.
Syntax
if
(condition)
{ // block of code to be executed if the condition is true)
}
else{
//block of code to be executed}
Example – if…else
int a = 20;
if (a < 18)
{
cout << "Good day.";
}
else
{
cout << "Good evening.";
}
Output:
Good evening
If... else if statement
« Use the if statement to specify a block of C++ code to be executed if a condition
is true.
« Use the else statement to specify a block of code to be executed if the condition
is false.
Syntax
if (condition)
{
// block of code to be executed if the condition is true
}
else if(Condition)
{
// block of code to be executed if the condition is false
}
else{
//block of code;
}
Example
int a = 22;
if (a < 10)
{
cout << "Good morning.";
}
else if (a < 20)
{
cout << "Good day.";
}
else
{
cout << "Good evening.";
}
Output
Good Evening
Switch Statement
Use the switch statement to select one of many code blocks to be executed.
Syntax:
switch(expression)
{
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}
This is how it works:
The switch expression is evaluated once
The value of the expression is compared with the values of each case
If there is a match, the associated block of code is executed
Example:
int day = 4;
switch (day) {
case 1:
cout << "Monday";
break;
case 2:
cout << "Tuesday";
break;
case 3:
cout << "Wednesday";
break;
case 4:
cout << "Thursday":
break;
case 5:
cout << "Friday";
break;
case 6:
cout << "Saturday";
break;
case 7:
cout << "Sunday";
)
Output: Thursday
0 Comments