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

Chapter 3-Flow Control Statements

Uploaded by

ShaggY
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

Chapter 3-Flow Control Statements

Uploaded by

ShaggY
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 11

Programming I

2023
Chapter Three Control Flow Statements
3.1. Introduction
In real world, several activities are initiated (sequenced) or repeated based on decisions. Such
activities can be programmed by specifying the order in which computations are carried out.
Control flow refers to the order in which the individual statements, instructions or function calls
of a program are executed or evaluated. A control flow statement is an instruction that can cause
a change in the subsequent control flow to differ from the natural sequential order in which the
instructions are listed. The kinds of control flow statements available in C++, roughly
categorized by their effect, are:
 Conditional /selection statements -for executing a set of statements only if some
condition is met
 Looping statements- for executing a set of statements zero or more times, until some
condition is met
 Jumping statements- for continuation at a different statement
3.2. Conditional Statements
It is sometimes desirable to make the execution of a statement dependent upon a condition being
satisfied. The C++ if and switch statements provide the way of expressing this.
3.2.1. The if Statement
The if statement causes other statements to execute only under certain conditions. The general
syntax of the if statement is:
if (expression)
statement;
First expression is evaluated. If the outcome is nonzero then statement is executed. Otherwise,
nothing happens. For example, when dividing two values, we may want to check that the
denominator is nonzero:
if (count != 0)
average = sum / count;
To make multiple statements dependent on the same condition, we can use a compound
statement:
if (balance > 0) {
interest = balance * creditRate;

Page | 1
Programming I
2023
Chapter Three Control Flow Statements
balance += interest;
}
A variant of if statement that allows us to specify two alternative statements: one which is
executed if a condition is satisfied and one which is executed if the condition is not satisfied is
called the if-else statement and has the general form:
if (expression)
{
statement1;
}
else
{
statement2;
}
First expression is evaluated. If the outcome is nonzero then statement1 is executed. Otherwise,

statement2 is executed.

For example:
if (num > 0)
{
cout<< “Positive number:”;
}
else
{
cout<< “Negative number:”;
}
3.2.2. Nested if Statement
A nested if statement is an if statement in the conditionally executed code of another if
statement. Anytime an if statement appears inside another if statement, it is considered as nested.
if(a>b)
{
if(b>c)
cout<< “a is the greatest”;
}
Actuality the if-else if structure is a nested if statement
Example
#include<iostream.h>

Page | 2
Programming I
2023
Chapter Three Control Flow Statements
int main()
{
//Declaring the necessary variables……..
float mark;
//Asking the user for the mark of the student……….
cout <<”\n\tTHIS PROGRAM WILL HELP YOU TO DETERMINE LETTER GRADE”
<<“ OF STUDENTS”;
cout<< “\n\n”<< “Please enter the mark of the student: ”;
cin>> mark;
//Computing the letter grade………………….
if (mark>=85 && mark<=100)
cout<< “\nThe letter grade of this student is A”;
else if (mark>=70 && mark<85)
cout<< “\nThe letter grade of this student is B”;
else if (mark>=50 && mark<70)
cout<< “\nThe letter grade of this student is C”;
else if (mark>=35 && mark<50)
cout<< “\nThe letter grade of this student is D”;
else if (mark>=0 && mark<35)
cout<< “\nThe letter grade of this student is F”;
else
cout<< “\nSorry, this is an invalid mark value.”;
return 0;
}
3.2.3. The switch Statement
The switch statement provides a way of choosing between a set of alternatives, based on the value
of an expression. The switch statement is mainly used to replace multiple if-else sequence which
is hard to read and hard to maintain. The general form of the switch statement is:
switch (expression)
{
case constant1:
statements;

Page | 3
Programming I
2023
Chapter Three Control Flow Statements
break;
...
case constant n:
statements;
break;
default:
statements;
}
The expression (called the switch tag) following the switch keyword is an integer valued
expression. The value of this expression decides the sequence of statements to be executed. Each
sequence of statements begins with the keyword case followed by a constant integer (called case
labels). (Note that constant characters may also be specified). The keyword break is used to
delimit the scope of the statements under a particular case. The final default case is optional and is
exercised if none of the earlier cases provide a match.
For example, suppose we have parsed a binary arithmetic operation into its three components
and stored these in variables operators, operand1, and operand2. The following switch statement
performs the operation and stores the result in result.
switch (operators) {
case '+': result = operand1 + operand2;
break;
case '-': result = operand1 - operand2;
break;
case '*': result = operand1 * operand2;
break;
case '/': result = operand1 / operand2;
break;
default: cout << "unknown operator: " << ch << '\n';
break;
}
As illustrated by this example, it is usually necessary to include a break statement at the end of
each case. The break terminates the switch statement by jumping to the very end of it. There
are, however, situations in which it makes sense to have a case without a break. For example, if
we extend the above statement to also allow x to be used as a multiplication operator, we will
have:

Page | 4
Programming I
2023
Chapter Three Control Flow Statements
switch (operator)
{
case '+': result = operand1 + operand2;
break;
case '-': result = operand1 - operand2;
break;
case 'x':
case '*': result = operand1 * operand2;
break;
case '/': result = operand1 / operand2;
break;
default: cout << "unknown operator: " << ch << '\n';
break;
}
Because case 'x' has no break statement, when this case is satisfied, execution proceeds to the
statements of the next case and the multiplication is performed.
It should be obvious that any switch statement can also be written as multiple if-else
statements. The above statement, for example, may be written as:
if (operator == '+')
result = operand1 + operand2;
else if (operator == '-')
result = operand1 - operand2;
else if (operator == 'x' || operator == '*')
result = operand1 * operand2;
else if (operator == '/')
result = operand1 / operand2;
else
cout << "unknown operator: " << ch << '\n';
However, the switch version is arguably neater in this case. In general, preference should be
given to the switch version when possible. The if-else approach should be reserved for situation
where a switch cannot do the job (e.g., when the conditions involved are not simple equality
expressions, or when the case labels are not numeric constants).

Page | 5
Programming I
2023
Chapter Three Control Flow Statements
3.3. Looping Statements
A loop is a control structure that causes a statement or group of statements to repeat. C++ has
three looping control structures: the while loop, the do…while loop and the for loop. The
difference between each of these is how they control repetition.

3.3.1. The ‘while’ Statement


The while statement (also called while loop) provides a way of repeating a statement while a
condition holds. It is one of the three flavours of iteration in C++. The general form of the while
statement is:
while (expression)
{
Statement1;
Statement2;
statementN;
}
The while loop has two important parts: An expression that is tested for a true or false value and
a statement or a block that is repeated as long as the expression is true. First expression (called
the loop condition) is evaluated. If the outcome is nonzero then statement (called the loop body)
is executed and the whole process is repeated. Otherwise, the loop is terminated.
For example, suppose we wish to calculate the sum of all numbers from 1 to some integer
denoted by n. This can be expressed as:
i = 1;
sum = 0;
while (i <= n)
sum += i++;
For n set to 5, the table below provides a trace of the loop by listing the values of the variables
involved and the loop condition.
Iteration i n i <= n sum += i++
First 1 5 1 1
Second 2 5 1 3

Page | 6
Programming I
2023
Chapter Three Control Flow Statements
Third 3 5 1 6
Fourth 4 5 1 10
Fifth 5 5 1 15
Sixth 6 5 0

3.3.2. The ‘do…while’ Statement


The do statement (also called do loop) is similar to the while statement, except that its body is
executed first and then the loop condition is examined. The general form of the do statement is:
do
{
statements;
}while (expression);
First statement statements are executed and then expression is evaluated. If the outcome of the
latter is nonzero then the whole process is repeated. Otherwise, the loop is terminated.
The do loop is less frequently used than the while loop. It is useful for situations where we
need the loop body to be executed at least once, regardless of the loop condition. For example,
suppose we wish to repeatedly read a value and print its square, and stop when the value is
zero. This can be expressed as the following loop:
do {
cin >> n;
cout << n * n << '\n';
} while (n != 0);
3.3.3. The ‘for’ Statement
The third type of loop in C++ is the for loop. The for statement (also called for loop) is similar
to the while statement, but has two additional components: an expression which is evaluated
only once before everything else, and an expression which is evaluated once at the end of each
iteration. The general form of the for statement is:
for(initialization; test_condition; update)
{

Page | 7
Programming I
2023
Chapter Three Control Flow Statements
statement/s;
}
 The initialization is an assignment statement that is used to set the loop control variable.
 The test_condition is a relational expression that determines when the loop exit.
 The update defines how the loop control variable changes each time the loop is repeated.
The for loop continues to execute as long as the condition is true. Once the condition becomes
false, program execution resumes on the statement following the for. In the following program, a
for loop is used to print the numbers 1 through 100 on the screen:
#include <iostream.h>
int main() {
int x;
for(x=1; x <= 100; x++)
cout<< x<<”\t”;
return 0;
}
In the loop, x is initially set to 1 and then compared with 100. Since x is less than 100, cout is
called and the loop iterates. This causes x to be increased by 1 and again tested to see if it is still
less than or equal to 100. If it is, x is displayed. This process repeats until x is greater than 100, at
which point the loop terminates. In this example, x is the loop control variable, which is changed
and checked each time the loop repeats. The following example is a for loop that iterates
multiple statements:
for(x=100; x != 65; x -= 5)
{
z = x*x;
cout<< "The square of "<< x<< “ = ”<< z;
}
Both the squaring of x and the displaying operations are executed until x equals 65. Note that the
loop is negative running: x is initialized to 100 and 5 is subtracted from it each time the loop
repeats.
C++ allows the first expression in a for loop to be a variable definition. In the following example
which calculates the sum of all integers from 1 to n , i is defined inside the loop itself:

Page | 8
Programming I
2023
Chapter Three Control Flow Statements
sum = 0;
for (int i = 1; i <= n; ++i)
sum += i;
Any of the three expressions in a for loop may be empty. For example, removing the first and
the third expression gives us something identical to a while loop:
for (; i != 0;) // is equivalent to: while (i != 0)
something; // something;
Removing all the expressions gives us an infinite loop. This loop's condition is assumed to be
always true:
for (;;) // infinite loop
something;
For loops with multiple loop variables are not unusual. In such cases, the comma operator is
used to separate their expressions:
for (i = 0, j = 0; i + j < n; ++i, ++j)
something;
Because loops are statements, they can appear inside other loops. In other words, loops can be
nested. For example,
for (int i = 1; i <= 3; ++i)
for (int j = 1; j <= 3; ++j)
cout << '(' << i << ',' << j << ")\n";
produces the product of the set {1,2,3} with itself, giving the output:
(1,1)
(1,2)
(1,3)
(2,1)
(2,2)
(2,3)
(3,1)
(3,2)
(3,3)
3.4. Jumping Statements
3.4.1. The break statement

Page | 9
Programming I
2023
Chapter Three Control Flow Statements
#include <iostream.h>
int main () 10, 9, 8, 7, 6, 5, 4, 3, countdown aborted!
{
int n;
for (n=10; n>0; n--)
{
cout << n << ", ";
if (n==3)
{
cout << "countdown
aborted!";
break;
}
}
return 0;
}
Using break we
can leave a loop even if the condition for its end is not fulfilled. It can be used to end an infinite
loop, or to force it to end before its natural end. For example, we are going to stop the count
down before its natural end (maybe because of an engine check failure?):

3.4.2. The continue statement


The continue statement causes the program to skip the rest of the loop in the current iteration as
if the end of the statement block had been reached, causing it to jump to the start of the following
iteration. For example, we are going to skip the number 5 in our countdown:

#include <iostream.h>
int main () 10, 9, 8, 7, 6, 4, 3, 2, 1, FIRE!
{
for (int n=10; n>0; n--)
{
if (n==5) continue;
cout << n << ", ";
}
cout << "FIRE!\n";
return 0;
}

3.4.3. The goto statement


goto allows to make an absolute jump to another point in the program. You should use this
feature with caution since its execution causes an unconditional jump ignoring any type of

Page | 10
Programming I
2023
Chapter Three Control Flow Statements
nesting limitations. The destination point is identified by a label, which is then used as an
argument for the goto statement. A label is made of a valid identifier followed by a colon (:).
Generally speaking, this instruction has no concrete use in structured or object oriented
programming aside from those that low-level programming fans may find for it. For example,
here is our countdown loop using goto:

#include <iostream.h>
int main () 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, FIRE!
{
int n=10;
loop:
cout << n << ", ";
n--;
if (n>0) goto loop;
cout << "FIRE!\n";
return 0;
}

Page | 11

You might also like