0% found this document useful (0 votes)
62 views

Lecture 5-C++ Flow Control Statements

Uploaded by

OPOKA ALBERT
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
62 views

Lecture 5-C++ Flow Control Statements

Uploaded by

OPOKA ALBERT
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 28

Lecture 5.

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 { }.

Types of statements in C++


C++ contains the following types of statements:
 Declaration statements

 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

Declaration statements. Declarations introduce a name into a program. E.g. int x;

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

1. C++ If Else Statement


In C++, if else statements are used to perform conditional execution of statement(s). Based on
the result of a condition, the decision to execute a block is taken.
In this lecture, we shall learn the different forms of if else statement, their syntax with detailed
explanation and examples for each of them.
In C++, If Else statement can occur in three forms. They are:
a) If statement

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.

b) C++ If …Else Statement


Following is the syntax of C++ If …Else statement.

if (condition) {

// Executes this block if

// condition is true

else

// Executes this block if

// 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:

// C++ program to illustrate if-else-if ladder


#include <iostream>
using namespace std;

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
}

Working of Switch Statement

1. Start of switch statement. The expression is evaluated to a value.


2. This value is then compared to each case value.
3. If it finds a match, corresponding block is executed.
4. break statement at the end of case block is optional. After executing a block, execution comes
out of the loop because of break. If no break statement is given, all the case blocks and default
block, next to this block, are executed.
5. default block is optional. If expression value does not match any of the case values, default
block is executed.

Check the following flow diagrams for detailed working of break statements at the end of case blocks,
and default block.

C++ Switch Flowchart or Flow-Diagram

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.

Switch Case Program Example 1


#include<iostream>
using namespace std;
int main()
{
int x = 20;
switch (x)
{
case 10:
cout<<"X is 10"; break;

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

// Program to build a simple calculator using switch Statement


#include <iostream>
using namespace std;

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

Enter an operator (+, -, *, /): -


Enter two numbers:
2.3
4.5
2.3 - 4.5 = -2.2

Output 3

Enter an operator (+, -, *, /): *


Enter two numbers:
2.3
4.5
2.3 * 4.5 = 10.35

Output 4

Enter an operator (+, -, *, /): /


Enter two numbers:
2.3
4.5
2.3 / 4.5 = 0.511111

Output 5

Enter an operator (+, -, *, /): ?


Enter two numbers:
2.3
4.5
Error! The operator is not correct.

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.

Question: How does the switch statement work?


The switch statement allows us to execute a block of code among many alternatives.
The expression is evaluated once and compared with the values of each case label.
 If there is a match, the corresponding code after the matching label is executed. For
example, if the value of the variable is equal to constant2, the code after case constant2: is
executed until the break statement is encountered.
 If there is no match, the code after default: is 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:

The conditional operator is of the form


variable = Expression1 ? Expression2 : Expression3

Or the syntax will also be in this form


variable = (condition) ? Expression2 : Expression3
Or syntax will also be in this form
(condition) ? (variable = Expression2) : (variable = Expression3)
It can be visualized into if-else statement as:
if(Expression1)
{
variable = Expression2;
}
else
{
variable = Expression3;
}

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

condition ? expression1 : expression2;

Here, condition is evaluated and


 if condition is true, expression1 is executed.
 And, if condition is false, expression2 is executed.
Working:
Here, Expression1 is the condition to be evaluated. If the condition (Expression1) is True
then Expression2 will be executed and the result will be returned. Otherwise, if the condition
(Expression1) is false then Expression3 will be executed and the result will be returned.

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;

// Using ternary operator


result = (number > 0) ? "Positive Number!" : "Negative Number!";

cout << result << endl;

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.

Example 2: C++ Ternary Operator


#include <iostream>
#include <string>
using namespace std;

int main() {
double marks;

// take input from users


cout << "Enter your marks: ";
cin >> marks;

// ternary operator checks if


// marks is greater than 40
string result = (marks >= 40) ? "passed" : "failed";

cout << "You " << result << " the exam.";

return 0;
}
Run Code

Output 1

Enter your marks: 80


You passed the exam.

Suppose the user enters 80. Then, the condition marks >= 40 evaluates to true. Hence, the first
expression "passed" is assigned to result.
Output 2

Enter your marks: 39.5


You failed the exam.

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.

// C++ program to find largest among two


// numbers using ternary operator

#include <iostream>
using namespace std;

int main()
{
// variable declaration
int n1 = 5, n2 = 10, max;

// Largest among n1 and n2


max = (n1 > n2) ? n1 : n2;

// Print the largest number


cout << "Largest number between " << n1
<< " and " << n2
<< " is " << 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.

// C++ program to check whether a year is leap year or not


// using ternary operator

#include <iostream>
using namespace std;
int main()
{
int yr = 1900;

(yr%4==0) ? (yr%100!=0? cout<<"The year "<<yr<<" is a leap year"


: (yr%400==0 ? cout<<"The year "<<yr<<" is a leap year"
: cout<<"The year "<<yr<<" is not a leap year"))
: cout<<"The year "<<yr<<" is not a leap year";
return 0;
}

//This code is contributed by Susobhan AKhuli

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;

// nested ternary operator to find whether


// number is positive, negative, or zero
result = (number == 0) ? "Zero" : ((number > 0) ? "Positive" : "Negative");

cout << "Number is " << result;

return 0;
}
Run Code

Output

Number is Zero

In the above example, notice the use of ternary operators,

(number == 0) ? "Zero" : ((number > 0) ? "Positive" : "Negative");

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

// This program calculates the average of numbers entered by the user.


// If the user enters a negative number, it ignores the number and
// calculates the average number entered before it.

# include <iostream>
using namespace std;

int main()
{
float num, average, sum = 0.0;
int i, n;

cout << "Maximum number of inputs: ";


cin >> n;

for(i = 1; i <= n; ++i)


{
cout << "Enter n" << i << ": ";
cin >> num;

if(num < 0.0)


{
// Control of the program move to jump:
goto jump;
}
sum += num;
}

jump:
average = sum / (i - 1);
cout << "\nAverage = " << average;
return 0;
}

Output

Maximum number of inputs: 10


Enter n1: 2.3
Enter n2: 5.6
Enter n3: -5.6

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;

// non-void return type


// function to calculate sum
int SUM(int a, int b)
{
int s1 = a + b;
return s1;
}

// 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

You might also like