You are on page 1of 52

TOPIC 3

PROGRAM CONTROL
STRUCTURE (Part 3)

DFC2073 Programming Fundamentals


Astri
By end of this class :
 Understand Program Control Structure
 Solve problems using selection control structures
 Solve problems using loops control structures

DFC2073 Programming Fundamentals


Astri
Control Structure

ITERATIONAL

DFC2073 Programming Fundamentals


Astri
Presto !

DFC2073 Programming Fundamentals


Astri
Iterational structures
About:
 Allows us to execute a statement or group
of statements multiple times.

Used to repeat a
block of codeDFC2073 Programming Fundamentals
Astri
Iteration structures

Iteration structures

while statement

do-while statement

for statement

DFC2073 Programming Fundamentals


Astri
Repetition types & description

Repetition Description
Type
while loop Repeats a statement or group of statements while a
given condition is true.
It tests the condition before executing the loop body
do...while Like a while statement, except that it tests the
loop condition at the end of the loop body
for loop Execute a sequence of statements multiple times and
abbreviates the code that manages the loop variable

DFC2073 Programming Fundamentals


Astri
Repetition Structure (Cont…)
A Repetition Structure requires:
1 Loop control variable

•a variable whose value determines whether the loop


body will be executed or not.
•In can be initialize or ask as an input from user

2 Loop condition

•if the condition is true, the loop body is executed;


otherwise the loop exits.

3 Loop body

•a block of statements to be repeated.


DFC2073 Programming Fundamentals
Astri
Repetition Structure (Cont…)
Execution of the repetition is controlled
by 3 operations:

1 2 3
Initialization Evaluation Update

•of the loop •of loop •of the loop


control control control
variable. variable in variable by
the loop incrementing
condition or
decrementin
g (** if
needed)

DFC2073 Programming Fundamentals


Astri
while Statement

ITERATION STRUCTURES

DFC2073 Programming Fundamentals


Astri
‘while’ Statement
The general form of while statement :

while (expression) Boolean expression


{
statement;  any executable statement
}

Syntax

Key point of the while


loop is that the loop
might not ever run.

DFC2073 Programming Fundamentals

Flow Diagram Astri


‘while’ Statement : Example
Explanation :
 The variable count is initialized to 0.
count = 0;
 Next, count is checked whether its value is
while (count < 10)
{ less than or not.
 If the condition count is TRUE, then the
total = total + num;
count++; statement total = total + num is executed and
} the value of count is increased by 1.
 Next, loop condition is again tested whether
the count is still less than10 or not.
 If it is, the loop body is executed repeatedly
until the condition is no longer true.
 If the condition (count < 10) is FALSE, then
the loop body is ignored and program
execution immediately jumps to the next
statement that follows the while statement.
Output ?

DFC2073 Programming Fundamentals


Astri
‘while’ Statement : Example

Output ?

DFC2073 Programming Fundamentals


Astri
do…while Statement

ITERATION STRUCTURES

DFC2073 Programming Fundamentals


Astri
‘do - while’ Statement
The general form of do-while statement :
do
{

statement block;  any executable statement

  } while (expression);  Boolean expression

Syntax

Key point of the do


-while loop is always
iterate at least once,
regardless of the value
of its control condition.

DFC2073 Programming Fundamentals

Flow Diagram Astri


‘do -while’ Statement : Example

Output ?

DFC2073 Programming Fundamentals


Astri
for Statement

ITERATION STRUCTURES

DFC2073 Programming Fundamentals


Astri
‘for’ Statement
The general form of for statement :
for (initialization ; expression ; incrementation)
{
statement block;
}

Syntax

Key point of the for loop


is that the loop might
not ever run

DFC2073 Programming Fundamentals

Flow Diagram Astri


‘for’ Statement
 Here is the flow of control in a for loop:
1 Initialization

•allows you to declare and initialize any loop control variables.


•performed just once at the start of the loop.

2 Expression / Condition

•determines whether the loop execution should continue.


•if it is TRUE, the body of the loop is executed.
•if it is FALSE, the body of the loop does not execute and the loop will be
terminated.

Increment/decrement
3
•typically increments or decrements the loop index.
•this performed every time through the loop iteration.
•This part is used to increment any variable(s) that may need to be
incremented/decremented
DFC2073 Programming Fundamentals
Astri
‘for’ loops component & structure

initialization

Termination-
condition

Incrementation
‘for’ Statement : Example

Output ?

DFC2073 Programming Fundamentals


Astri
Do you know??
Optionally:
Using the comma operator (,) we can specify more
than one expression in any of the fields included in
a for loop

DFC2073 Programming Fundamentals


Astri
Difference between
‘while’ and ‘do while’
‘while’ ‘do while’
Repeats a statement or group Like a while statement but at
of statements while a given least once loop will be execute
condition is true. when its running

It tests the condition before It tests the condition at the


executing the loop body end of the loop body. If the
condition is false the program
will exit from the loop.

DFC2073 Programming Fundamentals


Astri
‘while’ versus ‘do while’

DFC2073 Programming Fundamentals


Astri
Things to ponder..
Base on the three example of control
structure in iteration just now (while, do-
while and for), for the same problem it
produces the same output solution.

So what is the difference that brought


the advantage of any of the structure
stated?

In For loops
More readable ; Coding just in one line;
More efficient; Easy to understand
DFC2073 Programming Fundamentals
Astri
Iteration Example
Let us view more example of iteration loop
application below

DFC2073 Programming Fundamentals


Astri
The WHILE Loop
Here is an example of countdown using a for loop:
int main ()
{
int n;
cout << "Enter the starting number > ";
cin >> n;
while (n>0)
{
cout << n << ", ";
--n;
}
cout << "FIRE!\n";
return 0;
}

DFC2073 Programming Fundamentals


Astri
The WHILE loop
 The process:
1. User assigns a value to n
2. The while condition is checked (n>0). At this point there are two
posibilities:
* condition is TRUE: statement is executed (to step 3)
* condition is FALSE: ignore statement and continue after it (to step 5)
3. Execute statement:
cout << n << ", ";
--n;
(prints the value of n on the screen and decreases n by 1)
4. End of block. Return automatically to step 2
5. Continue the program right after the block: print FIRE! and end
program.

DFC2073 Programming Fundamentals


Astri
DO-WHILE Loop
Here is an example of countdown using a for loop:
#include<iostream>
using namespace std;

int main ()
{
unsigned long n;
do
{
cout << "Enter number (0 to end): ";
cin >> n;
cout << "You entered: " << n << "\n";
}
while (n != 0);
cout<<"THE END"<<endl;
return 0;
}
DFC2073 Programming Fundamentals
Astri
The WHILE loop
 The process:
1. User assigns a value to n
2. The input receive is call upon and display
3. The while condition is checked (n!=0). At this point there
are two posibilities:
* condition is TRUE: statement is repeated (to step 1)
* condition is FALSE: ignore statement and continue the
program right after the block: print THE END and end
program.

• condition in the do-while loop is ONLY


evaluated after the execution of statement
• at least ONE EXECUTION of statement even if
DFC2073 Programming Fundamentals
condition is never fulfilled Astri
FOR Loop
Here is an example of countdown using a for loop:
#include <iostream>
using namespace std;
int main ()
{
for (int n=10; n>0; n--)
{
cout << n << ", ";
}
cout << "FIRE!\n";
return 0;
}

DFC2073 Programming Fundamentals


Astri
Loop :: Control Statement
 Loop control statements change execution from its normal
sequence.
 When execution leaves a scope, all automatic objects that were
created in that scope are destroyed.
 C++ supports the following control statements.

continue
break statement goto statement
statement
• Terminates the • Causes the loop • control flow
loop or switch to skip the statement that
statement and remainder of its causes the CPU
transfers body and to jump to
execution to immediately another spot in
the statement retest its the code.
immediately condition prior • It is identified
following the to reiterating. through use of
loop or switch. a statement
label. 
‘break’ Statement
 When the break statement is encountered inside a loop,
the loop is immediately terminated and program control
resumes at the next statement following the loop.

Syntax
break;

Do you know any


other control
structure uses the
break statement ?

Key point :
forcing
termination
Flow Diagram
‘break’ Statement : Example (i)

Output ?

We can leave a
loop even if the
condition for its to
end is not fulfilled
‘break’ Statement : Example (ii)
int main()
{
int sum = 0;
Program to type up to 10
// Allow the user to enter up to 10 numbers
for (int count=0; count < 10; ++count) numbers, and displays the sum
{ of all the numbers entered at
cout << "Enter a number to add, or 0 to exit: ";
int num;
the end
cin >> num;

// exit loop if user enters 0


if (num == 0)
break;
If the user enters
// otherwise add number to our sum
0, the break causes
sum += num;
}
the loop to
cout << "The sum of all the numbers you entered is "<<sum; terminate early.

return 0;
} before 10
numbers have
been entered!!
DFC2073 Programming Fundamentals
Astri
‘continue’ Statement
 Causes the loop to skip the remainder of its body and
immediately retest its condition prior to reiterating.
 as if the end of the statement block had been reached, causing it to jump to
the start of the following iteration

Syntax
continue;

Key point :
Forces next iteration
of loop take place &
skip any code in
between
Flow Diagram
‘continue’ Statement : Example (i)
int count(0);
while (count < 10) Be careful:
 These loops typically
{ increment the loop
if (count == 5) variables in the body of
continue; // jump to end of loop body the loop, using continue
can cause the loop to
cout << count << " "; become infinite! 
++count;

// The continue statement jumps to here


}

• This program is intended to print every number between 0 and 9 except 5.


• But it actually prints below output then goes into an infinite loop
0 1 2 3 4
• When count is 5, the if statement evaluates to true, and the loop jumps to the bottom.
• The count variable is never incremented.
• On the next pass >count is still 5 > if statement is still true, therefore program
continues to loop forever.
‘continue’ Statement : Example (ii)
int count(0);
do
{
if (count == 5)
continue; // jump to end of loop body
cout << count << " ";

// The continue statement jumps to here


} while (++count < 10); // this still executes
// since it's outside the loop body

An example with a
do-while loop using
• This prints: continue correctly
0 1 2 3 4 6 7 8 9
‘continue’ Statement : Example (iii)
#include <iostream>
using namespace std;
int main () {
// Local variable declaration:
int a = 10;
// do loop execution
do {
if( a == 15) {
// skip the iteration.
a = a + 1; continue;
}
cout << "value of a: " << a << endl;
a = a + 1;
}while( a < 20 );
return 0;
}
‘continue’ Statement : Example (iv)
#include <iostream>
using namespace std;

int main () {
// Local variable declaration:
int a(10);

// do loop execution
do {
if( a <= 15) {
// skip the iteration.
a = a + 1;
continue;
}
cout << "value of a: " << a << endl;
a = a + 2;
}while( a < 25 );
return 0;
}
‘goto’ statement
 You should use this feature with caution since its
execution causes an unconditional jump ignoring any
type of nesting limitations
 goto allows to make an absolute jump to another
point in the program.
 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 (:)
 The goto statement and its corresponding
statement label must appear in the same function.
DFC2073 Programming Fundamentals
Astri
‘goto’ Statement : Example (i)
#include <iostream> If the input entered is :
#include <cmath> // for sqrt() function
using namespace std;
First Input x -> - 8
int main()
{
Second Input x -> - 5
double x; Last Input x -> 9
tryAgain: // this is a statement label
cout << "Enter a non-negative number:";
cin >> x;

if (x < 0.0)
{ If the input entered is :
cout<<"Invalid input"<<endl;
goto tryAgain; // this is the goto statement First Input x -> - 9
} Last Input x -> 22.5
cout << "The sqrt of "<< x << " is " << sqrt(x);

return 0;
}
‘goto’ Statement : Example (ii)
int main ()
{
int n=10;

next:
cout << n <<",";
n--;
if (n>0)
{
goto next;
}
cout << "FIRE!\n";
What is the output if
return 0; the statement are
change into the
} program code shown
‘goto’ Statement : Example (iii)
int main ()
{
int n=10;

next: The difference


cout << n ;<<",";
n--;
if (n>0)
{ cout<<",";
goto next;
cout << "FIRE!\n";
return 0;
What is the output if
} the statement are
change into the
program code shown
COMPARISON
break continue goto
• The loop is • The loop • The loop
immediately will skip the will skip the
terminated remainder remainder
and of its body of the body
program immediately and
control retest its resumes on
resumes at condition the
the next prior to program
statement reiterating. code that
following stated as
the loop. the
statement
label.
Infinite Loop Statement
 A loop becomes infinite loop if a condition never
becomes false.
 The for loop is traditionally used for this purpose.
 Since none of the three expressions that form the
for loop are required, you can make an endless
loop by leaving the conditional expression empty.
 When the conditional expression is absent, it is
assumed to be true.
 You may have an initialization and increment
expression, but C++ programmers more commonly use
the for(;;) construct to signify an infinite loop.
You can terminate
an infinite loop by
pressing Ctrl + C
keys.
Infinite Loop Statement : Example

Why don’t
you give it a
try ?
Class Activity
In group of TWO :
1. Write a program
to solve the
given problem
using
appropriate
iteration control
structure.

Activity 1
Activity 1
Iteration structure
Write a program using appropriate iteration
control structure:
1. To countdown from the value 10.
2. To display the number of countdown each
time.
3. Terminate the program as the value
reach 3 with an output statement display
as “countdown aborted!”.
Example output:
Exercise

Base on your workbook of DFC2073


workbook

<Complete Lab Activity 3B>

DFC2073 Programming Fundamentals


Astri
Closing

Reference :
• http://www.tutorialspoint.com
• http://
www.learncpp.com/cpp-tutorial
Next Class
TOPIC 4 :
Array, Structures and
Pointer (Part 1)

Do you have any question??

DFC2073 Programming Fundamentals


Astri

You might also like