Date post: | 24-Nov-2014 |
Category: |
Documents |
Upload: | norazilah-roslan |
View: | 495 times |
Download: | 0 times |
LOGO
TOPIC 4: REPETITION CONTROL STRUCTURE
CSC 128: FUNDAMENTALS OF
COMPUTER PROBLEM SOLVING
Contents
Introduction 1
while loop2
for loop3
Introduction
It is used when a statement or a block of statements need to be executed several times.
Programmers use the repetition structures, referred to more simply as a loop, when they need the computer to repeatedly process one or more program instructions until some condition is met, at which time the repetition structures end.
Repetition is also known as iteration or loop.
Introduction – example
Let say, you want to display “ I love C++” 5 times.
void main(){cout << “ I love c++!\n”;cout << “ I love c++!\n”;cout << “ I love c++!\n”;cout << “ I love c++!\n”;cout << “ I love c++!\n”;
}
Repetition control structures
C++ provides a few types of loop structures: while loop for loop
LOGO
The while loop
while loop
Repeat or loop as long as the condition is true.
The general form of the while statement is:
while is a reserved word.The parentheses are part of the syntax
while (loop condition){
//loop bodystatement;
}
while loop
Loop condition acts as a decision maker and is usually a logical expression. A Boolean expression that controls the execution of the body
of the loop statement executes if the condition initially evaluates to true loop condition is then reevaluated statement continues to execute until the condition is no longer
true
while (loop condition){
//loop bodystatement;
}
while loop
The general form of while loop flowchart:
Loop condition
Statement (s)(loop body)
false
true
while loop
The following while loop prints I love C++ 5 times.
int count = 1;
while(count<= 5){
cout<< “ I love C++”;count ++;}
Loop control variable
while loop
Start
I love C++
End
count = 1
count <= 5
count++
T
F
Loop control variable
A LCV controls the number of times the statement or the block of statements is being executed.
int count = 0;
while(count < 10){
cout<< “ hello ”;count ++;
}
How many times this loop will execute??
while loop
Basic operation in loop: Initialization Evaluation Update
while loop
The following while loop prints I love C++ 5 times.
int count = 1; //initialization
while(count<= 5) //evaluation{
cout<< “ I love C++”;count ++; //update statement}
while loop
Update statement:
count ++; ORcount = count + 1;
counter
Requirement of a repetition structure
Flow Chart
I love C++
counter = 1
counter <= 5
counter ++
T
F
Initialize LCV
Evaluate LCV (loop condition)
Loop body
Update LCV
while loop
Example: to display the first five positive integers which increment by five.
while loop
Pseudocode:
BeginInitialize i to 0Repeat while i <= 20Display iadd 5 to i (update)End repeat while
End
while loop
Enter the while statement
i <= 20
Expression evaluates to zero
False condition
Expression evaluates to a nonzero number
True condition
Go back and reevaluate the
expression
LoopDisplay
i
i = i + 5
i = 0
Start
End
while loop
Example C++ program segment:
i = 0;while ( i <= 20){ cout << i << “ “; i = i + 5;}
1) Loop Control Variable (LCV)
2) A starting point / Initialization of the LCV
3) Testing the loop repetition condition
4) Updating the LCV
while loop
Various form of while loops: Counter controlled Sentinel controlled
while loop – counter control
If you know exactly how many pieces of data need to be read, the while loop becomes a counter-controlled loop.
General syntax:
while loop – counter control
Counter controlled while loop includes the following:◦ Counter
A numeric variable used for counting something
Is done by adding a constant, such as 1 or 2, to the value of a variable.
◦ Accumulator Numeric variable used to find totals
Is done by adding a variable to another variable
counter = counter + 1
sum = sum + variable
while loop – counter control
Counter controlled while loop includes the following:◦ Initializing
Assign a beginning value to the counter or accumulator; typically 0
◦ Updating Also called incrementing, means adding a number to the
values stored in the counter or accumulator.
while loop – counter control
#include <iostream>#include <conio>
int main(){ int count;
count = 1;
while (count <= 10) { cout << count << endl; count++; }
getch(); return 0;}
initializing
updating
while loop – counter control
Example: to find and display total of three numbers
Pseudocode:
BeginInitialize lcv to 0, total to 0Repeat while lcv is less than 3input numbertotal = total + numberUpdate lcvEnd repeat whiledisplay total
End
while loop – counter control
Program and outputvoid main(){
int lcv,total;
lcv = 0, total =0;
while (lcv < 3) { cout << “enter number" << endl;
cin>> number;
total = total + number;
lcv++; }
cout<<“the total is”<<total;
getch(); }
while loop – counter control
Exercise: Write a C++ statement associated to the following flowchart.
Begin
Initialize counter = 10
counter < 100Display counterMultiplied by 2
Add 10 to counter
T
F
End
while loop – counter control
Program and output
int main(){ int count;
count = 10;
while (count < 100) { cout << count * 2 << endl; count += 10; }
getch(); return 0;}
while loop – sentinel control
A sentinel-controlled while loop uses a special value called sentinel to control the loop. Sentinel value is a special value that indicates the end
of a set of data or of a process
Sentinel variable is tested in the condition and loop ends when sentinel is encountered
while loop – sentinel control
General syntax :
while loop – sentinel control
Example #include <iostream>#include <conio>
int main(){
char answer;
cout << "Do you want to quit (Y - yes, N - no) : "; cin >> answer;
while (answer != 'Y') { cout << "Welcome to the program." << endl; cout << "Do you want to quit (Y - Yes, N - No) : "; cin >> answer; } cout << "Bye."; getch(); return 0;}
Sentinel value
while loop – sentinel control
Output screen
while loop – sentinel control
Exercise 1: to create a program to calculate and print total of a few numbers and the program will stop and display the result when a value 333 is read.
while loop – sentinel controlvoid main(){
int number, total;total= 0;
cout << "Enter a number : "; cin >> number;
while (number != 333) { total = total + number;
cout << "Enter a number : "; cin >> number;
}
cout <<"You have entered 333 to terminate” <<“the program.“<<endl;
cout <<“the total is “<<total;
getch(); }
while loop – sentinel control
Exercise 2: to create a flowchart and C++ program that process the loop as long as user enter an even number
while loop – sentinel control
Solution Flowchart
Begin
End
number % 2 == 0Get another
number
F
Prompt for a number
Get a number
T
while loop – sentinel control
Program
int main(){
int number;
cout << "Enter a number : "; cin >> number;
while (number % 2 == 0) { cout << "Enter the next number : "; cin >> number; }
cout <<"You have entered an odd number to terminate” <<“the program.";
getch(); return 0;}
while loop – sentinel control
Output
while loop
Infinite loop continues to execute endlessly can be avoided by including statements in the loop
body that assure exit condition will eventually be false
{ while (answer != 'Y') { cout << "Welcome to the program." << endl;
cout << "Do you want to quit (Y - Yes, N - No) : "; cin >> answer; } cout << "Bye.";}
LOGO
The for loop
for loop
Also called as a counted or indexed for loop
The general form of the for statement is:
The initial statement, loop condition, and update statement are called for loop control statements
Items in square brackets ([ ]) are optional.
for ([initial statement]; loop condition; [update statement])
statement;
for loop
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. In C++, for is a reserved word.
for ([initial statement]; loop condition; [update statement])
statement;
for loop – Example 1
Example : Displaying star symbol three times.
for (int count = 1; count <= 3; count = count + 1) cout << “*” << endl;
initializationinitialization conditioncondition updateupdate
Result:
***
for loop – Example 1
Using for loop to display ‘Welcome to C++’ three times.
Pseudocode:
Start for( set i to 1; i less than or equal to 3; add 1 to i)display “welcome to C++”End for
End
for loop – Example 1
Flowchart Start
i = 1
i <= 3
Display “welcome to C+
+”
i ++
End
T
F
for loop – Example 1
C++ program
for (int count = 1; count <= 3; count = count + 1) cout << “welcome to C++” << endl;
initializationinitialization conditioncondition updateupdate
for loop – Exercise 1
To create a program to display the first 10 non negative number.
for loop – Exercise 2
To create a program to display backward the first 10 non negative number.
for loop – Exercise 3
Exercise 3: create a program that display the first 10 positive odd integers.
for loop – Exercise 3
Exercise 3 - answer
for loop – Exercises
How many time the following loop processed?
Answer:
for (int count = 6; count < 6; count = count + 1)cout << count << endl;
for loop – Exercises
How many time the following loop processed?
Answer:
for (int count = 4; count <= 10; count = count + 2)cout << count << endl;
for loop – Example 3
Example: to calculate and display total of 3 numbers
for loop – Example 3
Pseudocode:
StartInitialize total = 0For(set counter to 1; counter less than or equal to 3; add 1 to counter)
input numbertotal = total + number
EndforDisplay total
End
for loop – Example 3
Flowchart Start
counter=1, total = 0,
for counter <= 3
Input number
total = total + numbercounter = counter + 1
Output total
End
F
T
for loop – Example 3
C++ program segment
total = 0;
for (int count = 1; count <= 3; count = count + 1){
cin>>number;total = total + number;
}cout << “total:” <<total<<endl;
for loop – Exercises
Suppose j, sum, and num are int variables, and the input values are 26, 34, 61, 4, and -1. What is the output of the code below?
cout << "Enter a number : ";cin >> num;
for (j = 1; j <= 4; j++){
sum = sum + num; cout << "Enter a number : ";
cin >> num; }
cout << sum << endl;
for loop – Exercises
Exercise 4: answer
for loop
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.
In a for statement, you can omit all three statements—initial statement, loop condition, and update statement. The following is a legal for loop:
for loop
This is an infinite loop, continuously printing the word Hello
for (;;)cout << "Hello" << endl;
LOGO
Nested Control StructuresNested Control Structures
Nested loop
In many situations, it is very convenient to have a loop contained within another loop.
Such loops are called nested loops.For each single trip, through the
outer loop, the inner loop runs through its entire sequence. Each time counter i increases by 1, the inner loop
executes completely.
Nested loop
Example of C++ program segment
for (i = 0; i <= 1; i++){ cout << "\n i is now " << i << endl;
for (j = 1; j <= 4; j++) cout << " j = " << j ; }
Nested loop
How it works…
i is now 0j = 1 j = 2 j = 3 j = 4
i is now 1j = 1 j = 2 j = 3 j = 4
Outer loopInner loop
Nested loop
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.
***************
Nested loop
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.
Nested loop
The syntax
for (i = 1; i <= 5 ; i++){ for (j = 1; j <= i; j++) cout << "*"; cout << endl;}
Nested loop
What pattern does the code produce if we replace the first for statement with the following?
for (i = 5; i >= 1; i--)
Answer:
***************
Summary
Two types of loop: Pretest loop
• Evaluation occurs before the instructions within the loop are processed
• Instruction may never be processed• while statement, for statement
Posttest loop• Evaluation occurs after the instructions within the loop
are processed• Instructions will be processed at least once• do..while statement
LOGO
www.themegallery.com