Lecture 5-C++ Flow Control Statements
Lecture 5-C++ Flow Control Statements
C++ Statements
A computer program is a list of instructions to be executed by a computer. In a programming
language, these programming instructions are called statements. C++ statements are the elements
of programs that controls how and in what order programs are executed. The statements can either
be a single line of code with a semicolon ; at the end or a block of code inside curly braces { }.
Expression statements
Compound statements
Flow Control Statements
o Selection statements
o Iteration statements
o Jump statements
Labeled statements
Exception Handling Statements e.g. Try-Catch blocks
Expression statements. These statements evaluate an expression for its side effects or for its
return value.
Null statements. These statements can be provided where a statement is required by the C++
syntax but where no action is to be taken.
Compound statements. These statements are groups of statements enclosed in curly braces ({ }).
They can be used wherever a single statement may be used.
Selection statements. These statements perform a test; they then execute one section of code if
the test evaluates to true (nonzero). They may execute another section of code if the test evaluates
to false.
Iteration statements. These statements provide for repeated execution of a block of code until a
specified termination criterion is met.
Jump statements. These statements either transfer control immediately to another location in the
function or return control from the function.
Labeled statements are used to direct the program's control to the given statement from a specific
position. E.g. Target label for goto statement, Case and Default label in a switch statement.
1|Page
@myco…TCBE 2202 Computing for Civil Engineering
C++ Flow Control Statements
There come situations in real life when we need to make some decisions and based on these
decisions, we decide what we should do next. Similar situations arise in programming also where
we need to make some decisions and based on these decisions we will execute the next block of
code. This is implemented using decision making or flow control statements.
Earlier, we described statements as commands, pieces of code that are executed in some order.
Expressions ending with a semicolon are statements. C++ language comes with two built-in styles
of flow control statements. For example;
a) Branching/Selection Statements
Selection statements allow us to check or use conditions, and based on that condition, we execute
the appropriate statements. It is also called branching because the program chooses to follow one
branch or another. Examples of such statements include; if, if...else, Nested if...else and Switch.
b) Looping/Iteration Statements
If we need some code to execute multiple times, we use the iteration statements. Iteration
statements are statements that execute some code in a loop. The code in the loop executes 0, 1, or
multiple times, depending on the statement and the condition. E.g. for…, while and do statement.
Thus: Branching is deciding what actions to take and looping is deciding how many times to take
a certain action.
Note: With the introduction of decision making /control structures we are going to have to
introduce a new concept: the compound-statement or block. A block is a group of statements
which are separated by semicolons (;) like all C++ statements, but grouped together in a block
enclosed in braces: { }: e.g.
{ statement1; statement2; statement3; }
Most of the control structures that we will see in this section require a generic statement as part of
its syntax. A statement can be either a simple statement (a simple instruction ending with a
semicolon) or a compound statement (several instructions grouped in a block), like the one just
described. In the case that we want the statement to be a simple statement, we do not need to
enclose it in braces ({}). But in the case that we want the statement to be a compound statement it
must be enclosed between braces ({}), forming a block.
2|Page
@myco…TCBE 2202 Computing for Civil Engineering
C++ decision making statements
The Decision Making (flow control) Statements are used to evaluate the one or more conditions
and make the decision whether to execute set of statement or not. Decision-making statements
in programming languages decide the direction of the flow of program execution. Decision-
making statements available in C++ are:
1. if statement 6. Jump Statements:
2. if-else statements break
3. nested if statements continue
4. if-else-if ladder goto
5. switch statements return
b) If-Else statement
c) If-Else-If statement
3|Page
@myco…TCBE 2202 Computing for Civil Engineering
a) C++ If Statement
Following is the syntax of simple C++ If statement.
if (condition) {
// Statements to execute if
// condition is true
}
If the condition is true, the statement(s) inside if block are executed. If the condition is false, the
statement(s) inside if block are not executed. In either of the cases, the execution continues with
the subsequent statements after the completion of if statement.
Flow Diagram
Following is the flow diagram of if statement in C++.
Example
Following is an example C++ program, where we use if statement to print a message only if the
number is positive.
4|Page
@myco…TCBE 2202 Computing for Civil Engineering
C++ Program
#include <iostream>
using namespace std;
int main() {
int a = 10;
if (a>0) {
cout << a << " is positive.";
}
}
Output
10 is positive.
if (condition) {
// condition is true
else
// condition is false
}
If the condition is true, the statement(s) inside if block are executed. If the condition is false, the
statement(s) inside else block are executed. After the execution of either if block or else block,
program execution continues with next statements after if-else statement.
Else block is optional. So, if you do not provide else block to an if block, it becomes a
simple if statement. So, if-else could be considered as an extension to simple if statement.
5|Page
@myco…TCBE 2202 Computing for Civil Engineering
Flow Diagram
Following is the flow diagram of if-else statement in C++.
Example: In the following example C++ program, we use if-else statement to check if a number
is positive or not.
C++ Program
#include <iostream>
using namespace std;
int main() {
int a = -10;
if (a>0) {
cout << a << " is positive.";
}
else {
cout << a << " is not positive.";
}
}
Output
-10 is not positive.
6|Page
@myco…TCBE 2202 Computing for Civil Engineering
c) C++ If Else If Statement (nested-if)
Following is the syntax of C++ if-else-if statement.
if (condition1) {
// statement(s)
} else if (condition2) {
// statement(s)
} else if (condition3) {
// statement(s)
} else {
// statement(s)
}
A nested if in C++ is an ‘if’ statement that is the target of another if statement. Nested if statements
mean an ‘if’ statement inside another if statement. Yes, both C and C++ allow us to nested if
statements within if statements, i.e., we can place an ‘if’ statement inside another if statement.
If condition1 is true, executes the statement(s) inside if block are executed. Else, the next condition
in the else-if ladder is evaluated. The next condition is condition2. If the condition2 is true, the
statement(s) inside corresponding else if block are executed. If condition2 is also false, condition3
is executed, and so on, until a condition is true. If no condition evaluates to true, then the last else
block is executed.
Even in if-else-if statement, the last else block is optional.
Flow Diagram: Following is the flow diagram of if-else-if statement in C++.
7|Page
@myco…TCBE 2202 Computing for Civil Engineering
or
Example: In the following example C++ program, we use if-else-if statement to check if a number
is positive, negative or zero.
C++ Program
#include <iostream>
using namespace std;
int main() {
int a = -7;
if (a>0) {
cout << a << " is positive.";
} else if(a<0) {
cout << a << " is negative.";
} else {
cout << a << " is zero.";
}
}
Output
-7 is negaitive.
8|Page
@myco…TCBE 2202 Computing for Civil Engineering
d) if-else-if ladder in C++
Here, a user can decide 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 else statement will be executed. if-else-if ladder is similar to
switch statement.
Syntax:
if (condition)
statement;
else if (condition)
statement;
.
.
.
else
statement;
Example:
int main()
{
int i = 20;
if (i == 10)
cout << "i is 10";
else if (i == 15)
cout << "i is 15";
else if (i == 20)
cout << "i is 20";
else
cout << "i is not present";
}
Output:
i is 20
9|Page
@myco…TCBE 2202 Computing for Civil Engineering
Flow Diagram: Following is the flow diagram to illustrate if-else-if ladder in C++.
10 | P a g e
@myco…TCBE 2202 Computing for Civil Engineering
2. Switch statements
In C++, Switch statement executes one of the many code blocks based on the value of an
expression.
Syntax of Switch Statement
Following is the syntax of switch statement in C++.
switch (expression) {
case value1:
// code block
break;
case value2:
// code block
break;.
.
.
default:
// code block
}
Check the following flow diagrams for detailed working of break statements at the end of case blocks,
and default block.
Following is the execution flow diagram of switch statement with break statement for each of the case
blocks.
11 | P a g e
@myco…TCBE 2202 Computing for Civil Engineering
12 | P a g e
@myco…TCBE 2202 Computing for Civil Engineering
Following is the execution flow diagram of switch statement without break statement for case blocks.
case 20:
cout << "X is 20"; break;
case 30:
cout << "X is 30"; break;
default:
cout<<"X is not 10, 20 or 30";
break;
}
return 0;
}
Output:
X is 20
13 | P a g e
@myco…TCBE 2202 Computing for Civil Engineering
Example 1: C++ Switch
Following is an example of Switch statement in C++. In this example, we shall print the name of
weekday based on the numeric value.
C++ Program
#include <iostream>
using namespace std;
int main() {
int day = 25;
switch (day%7) {
case 1: {
cout << "Monday" << endl;
break;
}
case 2: {
cout << "Tuesday" << endl;
break;
}
case 3: {
cout << "Wednesday" << endl;
break;
}
case 4: {
cout << "Thursday" << endl;
break;
}
case 5: {
cout << "Friday" << endl;
break;
}
default: {
cout << "Off day" << endl;
}
}
}
Output
Thursday
14 | P a g e
@myco…TCBE 2202 Computing for Civil Engineering
Example 2: C++ Switch without Break
Following is an example of Switch statement in C++. We have not used break statement after end
of case blocks. In this example, we shall print the name of weekday based on the numeric value.
C++ Program
#include <iostream>
using namespace std;
int main() {
int day = 24;
switch (day%7) {
case 1: {
cout << "Monday" << endl;
}
case 2: {
cout << "Tuesday" << endl;
}
case 3: {
cout << "Wednesday" << endl;
}
case 4: {
cout << "Thursday" << endl;
}
case 5: {
cout << "Friday" << endl;
}
default: {
cout << "Off day" << endl;
}
}
}
Output
Wednesday
Thursday
Friday
Off day
15 | P a g e
@myco…TCBE 2202 Computing for Civil Engineering
The break Keyword: When C++ reaches a break keyword, it breaks out of the switch block. Thus,
a break can save a lot of execution time because it "ignores" the execution of all the rest of the
code in the switch block. When a match is found, and the job is done, it's time for a break. There
is no need for more testing.
Example 3: Create a Calculator using the switch Statement
int main() {
char oper;
float num1, num2;
cout << "Enter an operator (+, -, *, /): ";
cin >> oper;
cout << "Enter two numbers: " << endl;
cin >> num1 >> num2;
switch (oper) {
case '+':
cout << num1 << " + " << num2 << " = " << num1 + num2;
break;
case '-':
cout << num1 << " - " << num2 << " = " << num1 - num2;
break;
case '*':
cout << num1 << " * " << num2 << " = " << num1 * num2;
break;
case '/':
cout << num1 << " / " << num2 << " = " << num1 / num2;
break;
default:
// operator is doesn't match any case constant (+, -, *, /)
cout << "Error! The operator is not correct";
break;
}
return 0;
}
Run Code
Output 1
16 | P a g e
@myco…TCBE 2202 Computing for Civil Engineering
Enter an operator (+, -, *, /): +
Enter two numbers:
2.3
4.5
2.3 + 4.5 = 6.8
Output 2
Output 3
Output 4
Output 5
In the above program, we are using the switch...case statement to perform addition, subtraction,
multiplication, and division.
17 | P a g e
@myco…TCBE 2202 Computing for Civil Engineering
How This Program Works
1. We first prompt the user to enter the desired operator. This input is then stored in
the char variable named oper.
2. We then prompt the user to enter two numbers, which are stored in the float
variables num1 and num2.
3. The switch statement is then used to check the operator entered by the user:
If the user enters +, addition is performed on the numbers.
If the user enters -, subtraction is performed on the numbers.
If the user enters *, multiplication is performed on the numbers.
If the user enters /, division is performed on the numbers.
If the user enters any other character, the default code is printed.
Notice that the break statement is used inside each case block. This terminates
the switch statement.
If the break statement is not used, all cases after the correct case are executed.
Note: We can do the same thing with the if...else..if ladder. However, the syntax of
the switch statement is cleaner and much easier to read and write.
18 | P a g e
@myco…TCBE 2202 Computing for Civil Engineering
3. Conditional or Ternary Operator (?:) in C++
The conditional operator is kind of similar to the if-else statement as it does follow the same
algorithm as of if-else statement but the conditional operator takes less space and helps to write
the if-else statements in the shortest way possible.
Syntaxes:
19 | P a g e
@myco…TCBE 2202 Computing for Civil Engineering
The Conditional Operator ‘?:’ takes three operands ( condition , expression1 and expression2 ) to
work, hence they are also called ternary operators.
A ternary operator evaluates the test condition and executes a block of code based on the result
of the condition.
Its syntax is
In C++, the ternary operator (also known as the conditional operator) can be used to
replace if...else in certain scenarios.
20 | P a g e
@myco…TCBE 2202 Computing for Civil Engineering
Example 1: When to use a Ternary Operator?
In C++, the ternary operator can be used to replace certain types of if...else statements.
For example, we can replace this code
#include <iostream>
using namespace std;
int main() {
// Create a variable
int number = -4;
if (number > 0)
cout << "Positive Number";
else
cout << "Negative Number!";
return 0;
}
Run Code
with
#include <iostream>
#include <string>
using namespace std;
int main() {
int number = -4;
string result;
return 0;
}
Run Code
Output
Negative Number!
21 | P a g e
@myco…TCBE 2202 Computing for Civil Engineering
Here, both programs give the same output. However, the use of the ternary operator makes our
code more readable and clean.
Note: We should only use the ternary operator if the resulting statement is short.
int main() {
double marks;
cout << "You " << result << " the exam.";
return 0;
}
Run Code
Output 1
Suppose the user enters 80. Then, the condition marks >= 40 evaluates to true. Hence, the first
expression "passed" is assigned to result.
Output 2
Now, suppose the user enters 39.5. Then, the condition marks >= 40 evaluates to false. Hence,
the second expression "failed" is assigned to result.
22 | P a g e
@myco…TCBE 2202 Computing for Civil Engineering
Example 3: Program to Store the greatest of the two Number.
#include <iostream>
using namespace std;
int main()
{
// variable declaration
int n1 = 5, n2 = 10, max;
return 0;
}
Output
Largest number between 5 and 10 is 10
Example 4: Program to check whether a year is leap year or not.
#include <iostream>
using namespace std;
int main()
{
int yr = 1900;
Output
The year 1900 is not a leap year
23 | P a g e
@myco…TCBE 2202 Computing for Civil Engineering
Example 5: Nested Ternary Operators
It is also possible to use one ternary operator inside another ternary operator. It is called the nested
ternary operator in C++.
Here's a program to find whether a number is positive, negative, or zero using the nested ternary
operator.
#include <iostream>
#include <string>
using namespace std;
int main() {
int number = 0;
string result;
return 0;
}
Run Code
Output
Number is Zero
Here,
(number = = 0) is the first test condition that checks if number is 0 or not. If it is, then it
assigns the string value "Zero" to result.
Else, the second test condition (number > 0) is evaluated if the first condition is false.
Note: It is not recommended to use nested ternary operators. This is because it makes our code
more complex.
24 | P a g e
@myco…TCBE 2202 Computing for Civil Engineering
4. Jump Statements (Loop Control Statements) in C++
These statements are used in C++ for the unconditional flow of control throughout the functions
in a program. C++ support four types of jump statements:
A) break
This loop control statement is used to terminate the loop. As soon as the break statement is
encountered from within a loop, the loop iterations stop there, and control returns from the loop
immediately to the first statement after the loop.
Syntax:
break; You can apply break
statement to while loop,
do-while loop, for loop
and a switch statement.
Basically, break statements are used in situations when we are not sure about the actual number
of iterations for the loop or we want to terminate the loop based on some condition.
B) continue
This loop control statement is just like the break statement. The continue statement is opposite
to that of the break statement, instead of terminating the loop, it forces to execute the next
iteration of the loop.
As the name suggests the continue statement forces the loop to continue or execute the next
iteration. When the continue statement is executed in the loop, the code inside the loop following
the continue statement will be skipped and the next iteration of the loop will begin.
Syntax:
continue;
We can use continue
statement in while Loop,
do-while Loop and a for
Loop
25 | P a g e
@myco…TCBE 2202 Computing for Civil Engineering
C) goto
The goto statement in C/C++ also referred to as the unconditional jump statement can be used
to jump from one point to another within a function. In C++ programming, the goto statement
is used for altering the normal sequence of program execution by transferring control to some
other part of the program.
Syntax:
Syntax1 | Syntax2
----------------------------
goto label; | label:
. | .
. | .
. | .
label: | goto label;
In the above syntax, the first line tells the compiler to go to or jump to the statement marked as
a label. Here, a label is a user-defined identifier that indicates the target statement. The statement
immediately followed after ‘label:’ is the destination statement. The ‘label:’ can also appear
before the ‘goto label;’ statement in the above syntax.
In the syntax above, label is an identifier. When goto label; is encountered, the control of program
jumps to label: and executes the code below it.
The goto statement gives the power to jump to any part of a program but, makes the logic of the
program complex and tangled. The goto statement can be replaced in most of C++ program with
the use of break and continue statements. It is actually generally considered a good idea not to use
goto statement.
26 | P a g e
@myco…TCBE 2202 Computing for Civil Engineering
Example: goto Statement
# include <iostream>
using namespace std;
int main()
{
float num, average, sum = 0.0;
int i, n;
jump:
average = sum / (i - 1);
cout << "\nAverage = " << average;
return 0;
}
Output
Average = 3.95
27 | P a g e
@myco…TCBE 2202 Computing for Civil Engineering
D) return
The return in C or C++ returns the flow of the execution to the function from where it is called.
This statement does not mandatorily need any conditional statements. As soon as the statement
is executed, the flow of the program stops immediately and returns the control from where it was
called. The return statement may or may not return anything for a void function, but for a non-
void function, a return value must be returned.
Syntax:
return[expression];
Example:
// C++ code to illustrate return
// statement
#include <iostream>
using namespace std;
// returns void
// function to print
void Print(int s2)
{
cout << "The sum is " << s2;
return;
}
int main()
{
int num1 = 10;
int num2 = 10;
int sum_of = SUM(num1, num2);
Print(sum_of);
return 0;
}
Output:
The sum is 20
Note: We shall discuss more about Loop Control Statements in the next lecture about C++ loops
28 | P a g e
@myco…TCBE 2202 Computing for Civil Engineering