You are on page 1of 41

REPETITION AS A CONTROL

STRUCTURE
 Instructions need to be repeated more than one
time to process lots of data
 Could do it by just literally repeating the code,
by copy and paste
 But that isn't flexible, nor is it easy to keep
consistent
 Need a "loop"
TWO PARTS TO REPETITION
A Body
 what needs to be repeated
 must be marked off in some fashion like {}

A Control expression
 some way to make the repetition stop when
desired

Infinite loops not required!


while
for
do..while
WHILE LOOP
 The body can be either one statement (doesn't
need {} then) or more than one statement (a
block that has {} around it)
 Any kind of statement can be in the body of a
loop, including other while statements
THE SYNTAX OF A WHILE
LOOP
 while (condition) // note no semicolon

{
statement;
statement;
statement;
}
 Indentation useful for humans, not compiler
THE SEMANTICS OF A WHILE
 The condition at the top of the loop is evaluated
to see if it is true or false
 it MUST be - will be forced to bool !

 If the condition is true, the body will be entered


at the top and executed all the way through
 Then the condition will be evaluated again, and
the process is repeated
THE SEMANTICS OF A WHILE
(CONT'D)
 If the condition at the top turns out to be false,
the body of the loop is completely skipped
 Execution continues with statements following
loop body
 PRE-test loop - it is possible the body may not
be executed at all!
When the expression
is tested and found
to be false, the loop FALSE
is exited and control Expression
passes to the
statement that TRUE
follows the loop
body body
statement
HOW TO CONTROL IT?

TWO kinds of loops


counter-controlled (x < 5)
 when you know how many times you
want it to repeat
sentinel-controlled (x != -1)
 when you let EVENTS control how many
times it repeats
COUNTER-CONTROLLED
LOOPS
 Three parts
 counter variable - declare and initialize
outside the loop
int ctr = 0;
 test the counter at the top of the loop
while (ctr < 5)
 COUNT inside the loop body
ctr = ctr + 1;
AN EXAMPLE
int linectr = 0;
while (linectr <= 3)
{
cout << linectr << endl;
linectr = linectr + 1;
}
How many lines of output??
SENTINEL-CONTROLLED
LOOP
 Three parts
 Initial read / input before the loop
cin >> num;
 Test at top of loop for sentinel value or event
while (num != -1)
 Change something inside the loop
cin >> num;
AN EXAMPLE
int num;
cin >> num;
while (num > 0)
{
cout << num;
cin >> num;
}
How many repetitions of the body??
CAUSES OF INFINITE LOOPS
 Testing the wrong variable
 Forgetting to change the counter or the
situation inside the loop
 using the wrong test (< instead of >)
 using = instead of ==
The general form of the for statement is:
 for (initial statement; loop condition; update statement)

The initial statement, loop condition, and update
statement are called for loop control statements
 The for loop executes as follows:
 1. The initial statement executes.
 2. The loop condition is evaluated. If the loop condition evaluates
to true
 i. Execute the for loop statement.
 ii. Execute the update statement (the third expression in the parentheses).
3. Repeat Step 2 until the loop condition evaluates to false.

 The initial statement usually initializes a variable (called the


for loop control, or for indexed, variable).
 In C++, for is a reserved word.
Why????
Why????
The following are some comments on for loops:
If the loop condition is initially false, the loop body
does not execute.
The update expression, when executed, changes the
value of the loop control variable (initialized by the
initial expression), which eventually sets the value of
the loop condition to false
The for loop body executes indefinitely if the loop
condition is always true.
A semicolon at the end of the for statement (just
before the body of the loop) is a semantic error. In
this case, the action of the for loop is empty.
In the for statement, if the loop condition is
omitted, it is assumed to be true.
What is the output ????
The general form of a do...while statement is:
do
statement
while (expression);
The statement executes first, and then the expression is
evaluated
If the expression evaluates to true, the statement executes
again
As long as the expression in a do...while statement is
true, the statement executes
To avoid an infinite loop, the loop body must
contain a statement that makes the expression
false
The statement can be simple or compound
If compound, it must be in braces
do...while loop has an exit condition and always
iterates at least once (unlike for and while)
 Suppose we want to create the following pattern
*
**
***
****
*****
 In the first line, we want to print one star, in the second line
two stars and so on
Since five lines are to be printed, we start with the
following for statement
 for (i = 1; i <= 5 ; i++)
The value of i in the first iteration is 1, in the
second iteration it is 2, and so on
Can use the value of i as limit condition in another
for loop nested within this loop to control the
number of starts in a line
 The syntax is:
for (i = 1; i <= 5 ; i++)
{
for (j = 1; j <= i; j++)
cout << "*";
cout << endl;
}
What pattern does the code produce if we replace the first for statement
with the following?
for (i = 5; i >= 1; i--)
 Answer:
*****
****
***
**
*
C++ has three looping (repetition) structures:
while, for, and do…while
while, for, and do are reserved words
while and for loops are called pre-test loops
do...while loop is called a post-test loop
while and for may not execute at all, but do...while
always executes at least once
 Write a C++ programs to display your name Five Times (use For
loop)
 Write a C++ programs that adds two integer numbers and then
display the answer
 Write a C++ program that accept a number from the user and test
if the number is even or odd, if is even number then display it and
also if its an odd number display it
 Write a program that accept grade from the user and then test if
the grade is A, B+, B, C, D, F (print a message “Excellent”,
”Very good”, ”Good”,”Satisfactory”,”Poor”,”Fail”) Repectivelly
----use Switch
What will be the value of z?
 int i = 5;
 while (i > 0) {
 --i;
 cout << i << endl;
}

What will be the output?
 #include <iostream.h>
 int main() {
 int n = 3;
 while (n >= 0) {
 cout << n * n << endl;
 --n;
 }
 cout << n << endl;
}
What will be the output?

You might also like