0% found this document useful (0 votes)
7 views17 pages

Chapter 3

Chapter 3 discusses program control statements, focusing on flow control, conditionals, and loops in programming. It explains how programmers can control the execution order of statements using conditionals like 'if', 'else', and 'switch', as well as repetition structures such as 'for', 'while', and 'do while' loops. The chapter provides syntax examples and practical exercises to illustrate these concepts in C++.

Uploaded by

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

Chapter 3

Chapter 3 discusses program control statements, focusing on flow control, conditionals, and loops in programming. It explains how programmers can control the execution order of statements using conditionals like 'if', 'else', and 'switch', as well as repetition structures such as 'for', 'while', and 'do while' loops. The chapter provides syntax examples and practical exercises to illustrate these concepts in C++.

Uploaded by

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

Chapter -3

Program Control Statements/structure

 Normally, a program executes statements from first to last. The first statement is
executed, then the second, then the third, and so on, until the program reaches its end or
terminates.
 A running program spends all of its time executing instructions or statements in that
program.
 The order in which statements in a program are executed is called flow of that program.
 Programmers can control which instruction to be executed in a program, which is called
flow control.
 This term reflects the fact that the currently executing statement has the control of the
CPU, which when completed will be handed over (flow) to another statement.
 Flow control in a program is typically sequential, from one statement to the next.
 But we call also have execution that might be divided to other paths by branching
statements. Or perform a block of statement repeatedly until a condition fails by
Repetition or looping.
 Flow control is an important concept in programming because it will give all the power to
the programmer to decide what to do to execute during a run and what is not, therefore,
affecting the overall outcome of the program
 Control structures are portions of program code that contain statements within them and,
depending on the circumstances, execute these statements in a certain way.
 There are typically two kinds:
 conditionals and
 Loops.
3.1 Conditionals/selection statement

 In order for a program to change its behaviour depending on the input, there
must a way to test that input. Conditionals allow the program to check the
values of variables and to execute (or not execute) certain statements.

1
 Selection statements are statements in a program where there are points at
which the program will decide at runtime whether some part of the code should
or should not be executed.
 C++ has two types of conditional statement
 if statement and
 Switch-case conditional structures/statement.
3.1.1 The if Statement

 It is sometimes desirable to make the execution of a statement dependent upon


a condition being satisfied.
 The different forms of the ‘If” statement will be used to decide whether to
execute part of the program based on a condition which will be tested either for
TRUE or FALSE result.
 The different forms of the “If” statement are:
 the simple if statement
 The if else statement
 The if else if statement (nested if else statement)
The simple if statement/condition:
The simple if statement will decide only one part of the program to be executed if the
condition is satisfied or ignored if the condition fails.
The General Syntax is:

 In any “if” statement, first the “expression” will be evaluated and if the outcome is
non zero (which means TRUE), then the “statements” is executed. Otherwise,
nothing happens (the statement will not be executed) and execution resumes to the
line immediately after the “if” block.
 To make multiple statements dependent on the same condition we can use a
compound statement, which will be implemented by embracing the group of
instructions within the left “{“and right “}” French bracket.
2
if (expression) statements;
 Most of the time “expression” will have relational expressions testing whether
something is equal, greater, less, or different from something else.
 It should be noted that the output of a relational expression is either True
(represented by anything different from zero) or False (represented by Zero).
 Thus any expression, whose final result is either zero or none zero can be used in
”expression” .
 Thus, expression and be:
 Relational expression,
 A variable,
 A literal constant, or
 Assignment operation, as the final result is whatever we have at the right
hand side and the one at the left hand side is a variable.

Example1: if(age>18)
cout<<”you are an adult”;
Example 2: if(x ==10)
cout<<”x is 100”<<endl;
Example 3: if (count! = 0)

Average = sum / count;

3
Example 4: if (balance > 0)

Interest = balance * creditRate;


Balance += interest;
}
The if else statement
 Another form of the “if” is the “if …else” statement.
 The “if else ” statement allows us to specify two alternative statements:
• One which will be executed if a condition is satisfied and
• Another which will be executed if the condition is not satisfied.
 The General Syntax is:

 First “expression” is evaluated and if the outcome is none zero (true), then
“statements1” will be executed. Otherwise, which means the “expression” is false
“statements2” will be executed.


4
Example 1: if (balance > 0)
{
interest = balance * creditRate;
balance += interest;
}
else
{
interest = balance * debitRate;
balance += interest;
}

Example 2: if (x > 0)

cout << "x is positive";

else

cout << "x is negative";

Exercise:
1. Write c++ program that accept a number from user and display weather number is odd or
even
2. Write c++ program that accept a number from user and display weather number is
positive or negative
3. Write a program that display message old if age is greater than 70 otherwise its adult
4. Write a program that display message pass and fail based on some constraint
The if else if statement

 The third form of the “if statement is “if else if” statement
 The “if else if” statement allows us to specify more than alternative statements each will
be executed based on testing one or more conditions.
 The General Syntax is:

5
 if (expression1) is evaluated and is the outcome is non zero (true), then “statements1”
will be executed.

Otherwise, which means the “expression1” then “expression2”


will be evaluated:
 if the output of expression2 is True then “statements2” will be executed otherwise the
next “expression” in the else if statement will be executed and so on.
 If all the expressions in the “if” and “else if” statements are False then “statements”
under else will be executed.
 The “if…else” and “if…else if” statements are selection as if one of the condition
(expression) is satisfied only instructions in its block will be executed and the rest will
be ignored.
Example 1 : if (ch >= '0' && ch <= '9')
kind = digit;
else if
{ (ch >= 'A' && ch <= 'Z')
kind = upperLetter;
else if
{
(ch >= 'a' && ch <= 'z')
kind = lowerLetter;
else
kind = special;
}
}
Example 2:
if(score >= 90)
cout<< “\n your grade is A”<<endl;
else if(score >= 80)
cout<< “\n your garde is B”<<endl;

6
else if(score >= 70)
cout<< “\n your garde is C”<<endl;
else if(score >= 60)
cout<< “\n your garde is D”<<endl;
else
cout<< “\n your garde is F”<<endl;

3.1.2 Switch statement

 Another C++ statement that implement the selection control flow is switch statement
(multiple-choice state)
 The switch statement provides a way of choosing between a set of alternatives based
on the value of an expression
 The general form of switch statement is:
 The switch statement has four components:
 Switch
 Case
 Default
 Break
 Where Default and Break are Optional
 The General Syntax might be:

 Expression is called the switch tag and the constants preceding each case are called the
case labels.
 The output of “expression” should always be a constant value

7
 First expression is evaluated and the outcome which is constant value will compare to
each of the numeric constants in the case labels in order they appear, until a match is
found.
 Note, however, that the evaluation of the switch tag with the case labels is only for
equality
 The statements following the matching case are then executed. Note the plural: each case
may fallow by zero more statement (not just one statement).
 After one case is satisfied, execution continues until either a break statement is
encountered which means until the execution reaches the right French bracket of the
switch statement.
 The final default case is optional and is exercised if none of the earlier cases provide a
match. This mean that if the value of the expression is not equal to any of the case labels,
then the statements under default will be executed. Now let us see the effect of including
a break statement in the switch statement.

#include <iostream>
using namespace std;
int main ()
{
// local variable declaration:
char grade = 'D';
switch(grade)
{

8
case 'A' :
cout << "Excellent!" << endl;
break;
case 'B' :
case 'C' :
cout << "Well done" << endl;
break;
case 'D' :
cout << "You passed" << endl;
break;
case 'F' :
cout << "Better try again" << endl;
break;
default :
cout << "Invalid grade" << endl;
cout << "Your grade is " << grade << endl;
}
return 0;
} output is as follows
You passed
Your grade is D

3.2 Repetition (loop) (iteration) statement


 There may be a situation, when you need to execute a block of code several numbers of
times.
 In general, statements are executed sequentially: The first statement in a function is
executed first, followed by the second, and so on.
 A loop statement allows us to execute a statement or group of statements multiple times
and following is the general from of a loop statement in most of the programming
languages:
 Repetition statements control a block of code to be executed repeatedly for a fixed
number of times or until a certain condition fails.
9
 There are three C++ repetition statements:
1) The For Statement or loop

2) The While statement or loop

3) The do…while statement or loop

The For Statement or loop


 The “for” statement (also called loop) is used to repeatedly execute a block of
instructions until a specific condition fails.
 A for loop is a repetition control structure that allows you to efficiently write a loop
that needs to execute a specific number of times.
 The syntax of a for loop in C++ is:

for ( initialization; condition; increment/decrement)


{
statement(s);
}

Here is the flow of control in a for loop:

1. The initialization step is executed first, and only once. This step allows you to declare and
initialize any loop control variables. You are not required to put a statement here, as long as a
semicolon appears.

2. Next, the condition is evaluated. If it is true, the body of the loop is executed. If it is false, the body
of the loop does not execute and flow of control jumps to the next statement just after for loop.

3. After the body of for loop executes the flow of control jumps back up to the increment/decrement
statement. This statement allows you to update any loop control variables. This statement can be left
blank, as long as a semicolon appears after the condition.

4. The condition is now evaluated again. If it is true, the loop executes and the process repeats itself
(body of loop, then increment step, and then again condition). After the condition becomes false, for
loop terminates.

Steps of execution of for loop:


1. Initialization is executed. (Will be executed only once)
2. Condition is checked, if it is true the loop continues, otherwise the loop
finishes and statement is skipped.
10
3. Statement is executed.
4. Finally, whatever is specified in the increase or decrease field is
executed and the loop gets back to step 2.
 Any of the three expressions in for loop may be empty.
 Generally there are two types of for loop
1. Infinite for loop
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;

1. Nested for loop


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";
Example 1: write aprogram using for statement that adds the numbers between 0 and n
int Sum=0;
for(int i=0; i<=n;i++)
Sum=Sum+i;
Example 2: write a program using for statement that adds the even numbers between 0 and n
int Sum=0;
for(int i=0; i<=n;)
{
Sum=Sum+i;
i+=2;
}
Example 3: write a program using for loop that display sum number from 1-10
sum = 0;

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

sum += i;
11
In the above example, the initialization is at the top before the looping starts, the condition is
put in if statement before the instructions are executed and the increment is found
immediately after the statements to be executed in the loop.
NB: even though there is the option of making all the three expressions null in a “for” loop, it is not
recommended to make the condition to take null statement.

The While statement or loop

 The while statement (also called while loop) provides a way of repeating a statement
or a block as long as a condition holds / is true.
 Repeats a statement or group of statements while a given condition is true. It tests the
condition before executing the loop body.
Syntax:

The syntax of a while loop in C++ is:

while(condition)

statement(s);

Here, statement(s) may be a single statement or a block of statements. The condition may be any
expression, and true is any non-zero value. The loop iterates while the condition is true.

When the condition becomes false, program control passes to the line immediately following the loop.

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;
while loop trace is follows
Iteration i N i <= n sum += i++

12
First 1 5 1 1

Second 2 5 1 3

Third 3 5 1 6

Fourth 4 5 1 10

Fifth 5 5 1 15

Sixth 6 5 0

do while loop
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

statement;

while (expression);

First statement is 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

13
following loop:

do {

cin >> n;

cout << n * n << '\n';

} while (n != 0);

Unlike the while loop, the do loop is never used in situations where it would have a null body.
Although a do loop with a null body would be equivalent to a similar while loop, the

latter is always preferred for its superior readability

3.3 Other Statements

The ‘continue’ Statement


The continue statement terminates the current iteration of a loop and instead jumps to the
next iteration. It applies to the loop immediately enclosing the continue statement. It is an
error to use the continue statement outside a loop.
In while and do loops, the next iteration commences from the loop condition. In a for loop,
the next iteration commences from the loop’s third expression. For example, a loop which
repeatedly reads in a number, processes it but ignores negative numbers, and terminates
when the number is zero, may be expressed as:
do {
cin >> num;
if (num < 0) continue;
// process num here...
} while (num != 0);
This is equivalent to:
do {
cin >> num;
if (num >= 0) {
// process num here...
}
} while (num != 0);

14
A variant of this loop which reads in a number exactly n times (rather than until the number
is zero) may be expressed as:

for (i = 0; i < n; ++i) {


cin >> num;
if (num < 0) continue; // causes a jump to: ++i
// process num here...
}
When the continue statement appears inside nested loops, it applies to the loop immediately
enclosing it, and not to the outer loops. For example, in the following set of nested loops,
the continue applies to the for loop, and not the while loop:

while (more) {
for (i = 0; i < n; ++i) {
cin >> num;
if (num < 0) continue; // causes a jump to: ++i
// process num here...
}
//etc...
}

The ‘break’ Statement


A break statement may appear inside a loop (while, do, or for) or a switch statement. It
causes a jump out of these constructs, and hence terminates them. Like the continue
statement, a break statement only applies to the loop or switch immediately enclosing it. It
is an error to use the break statement outside a loop or a switch.
For example, suppose we wish to read in a user password, but would like to allow the user a
limited number of attempts:

for (i = 0; i < attempts; ++i) {


cout << "Please enter your password: ";
cin >> password;
if (Verify(password)) // check password for correctness

15
break; // drop out of the loop
cout << "Incorrect!\n";
}
Here we have assumed that there is a function called Verify which checks a password and
returns true if it is correct, and false otherwise.
Rewriting the loop without a break statement is always possible by using an additional
logical variable (verified) and adding it to the loop condition:

verified = 0;
for (i = 0; i < attempts && !verified; ++i) {
cout << "Please enter your password: ";
cin >> password;
verified = Verify(password));
if (!verified)
cout << "Incorrect!\n";
}
The break version is arguably simpler and therefore preferred.

The ‘goto’ Statement


The goto statement provides the lowest-level of jumping. It has the general form:
goto label;
where label is an identifier which marks the jump destination of goto. The label should be
followed by a colon and appear before a statement within the same function as the goto
statement itself. For example, the role of the break statement in the for loop in the previous
section can be emulated by a goto:
for (i = 0; i < attempts; ++i) {
cout << "Please enter your password: ";
cin >> password;
if (Verify(password)) // check password for correctness
goto out; // drop out of the loop
cout << "Incorrect!\n";
}
out:

16
//etc...
Because goto provides a free and unstructured form of jumping (unlike break and
continue), it can be easily misused. Most programmers these days avoid using it altogether
in favor of clear programming. Nevertheless, goto does have some legitimate (though rare)
uses.

The ‘return’ Statement


The return statement enables a function to return a value to its caller. It has the general form:
return expression;
where expression denotes the value returned by the function. The type of this value should
match the return type of the function. For a function whose return type is void, expression
should be empty:
return;
The only function we have discussed so far is main, whose return type is always int. The
return value of main is what the program returns to the operating system when it completes
its execution. Under UNIX, for example, it its conventional to return 0 from main when the
program executes without errors. Otherwise, a non-zero error code is returned. For example:
int main (void)
{
cout << "Hello World\n";
return 0;
}
When a function has a non-void return value (as in the above example), failing to return a
value will result in a compiler warning. The actual return value will be undefined in this
case (i.e., it will be whatever value which happens to be in its corresponding memory
location at the time).

17

You might also like