Repetition1 - UCL Computer Science

Download Report

Transcript Repetition1 - UCL Computer Science

Introduction to Loops
Loops Also known as
Iteration
Repetition
Counting
Purpose
To apply the same steps again and
again to a block of statements.
Recall a block of statement is one or
more statement, block usually defined
by braces { and }
Most Common Uses of Loops
For
For
For
For
For
For
For
For
For
counting
accumulating
searching
Sorting
displaying tables
data entry
menu processing
list processing
simulations.
Types of loops
for (start condition; stop condition; change expression)
while (stop condition)
do..while(stop condition)
C/C++ Loop Structures
Pre-test
for loops (most common)
When you know how many times (fixed condition)
while loops
When you don’t know how many times
Event controlled (variable condition)
Post-test
do … while loops
When you don’t know how many times, but you know
you need at least one pass.
What you need to think about to construct a loop
What you are going to control the loop with?
A counter
Keep repeating a number of times
An event
Keep repeating until controller takes a particular value.
More generally:Keep repeating until something happens (You define
the event).
Usually a controller variable is needed.
What you are going to initialise your controller with?
How does your controller change?
What is the condition of controller that stops loop?
The for Statement Syntax
start condition
stop condition
change expression
for (init controller; Ctrl expression; Alter
controller){
statements;
}
Example:
for (count=1; count < 7; count++) {
cout << “count = ” << count << endl;
}
next statement;
The for Statement
Used as a counting loop
Used when we can work out in advance the
number of iterations.
Semicolons separate the items
You may declare variable and initialize it
example:
for (int count = 1; count < 7; count++){
statement(s);
}
A Simple Example
Create a table with a for loop
int num;
cout << "NUMBER\tSQUARE\tCUBE\n“;
cout << "------\t------\t----\n";
for (num
cout
cout
cout
}
= 1; num < 11; num++) {
<< num << “\t“;
<< num * num << “\t“;
<< num * num * num<<“\n";
NUMBER
---------1
2
.
.
10
SQUARE
---------1
4
.
.
100
CUBE
-----1
8
.
.
1000
for and if Statements working
together.
Simple search for divisors
Given an integer number find all the
numbers that divide exactly into it
(except 1 and itself).
Thinks I can
use % operator
to find divisors
e.g. if number = 12, divisors are 2,3,4,6
Solution Design
Get the number for user
By starting with check number= 2 and
finish with check number 1 less than
number (is this efficient?)
find the remainder of dividing number with
current check number
if remainder is 0 display current check number
as a divisor.
otherwise don’t display anything
Program segment for finding divisors of an
integer
cout << “Enter an integer :”;
cin >> number;
for (j = 2; j < number; j = j + 1){
if (number % j == 0){
cout << j << “ is a divisor of
cout << number << ‘\n’;
}
sum = sum + j;
}
“;
Common errors in constructing
for Statements
for (j = 0, j < n, j = j + 3)
// commas used when semicolons needed
for (j = 0; j < n)
// three parts needed
for (j = 0; j >= 0; j++)
?????what is wrong here ?????
Infinite loops
for (j=0; j>=0; j++) {
cout << i << endl;
}
DEMO1 Chris
Be careful with terminating conditions!
Programming convention
Use of integers called i,j,k
You will see them all the time.
Most commonly used as loop controller
variables
Conventionally used for counters
We will see later that counters often have a
dual use as array indices.
When you see i,j,k declared expect to see a
loop!
for -- Null (Empty ) Expressions
Example 1:
Start condition outside
for control area
j = 1;
sum = 0;
for (
; j <= 10; j = j + 1){
sum = sum + j;
}
Empty/Null
expression
We could do this
Empty/Null
expression
Example 2:
j = 1;
sum = 0;
for (
; j <= 10;
){
sum = sum + j;
j = j + 1;
}
change expression outside
for control area
Still legal!- Nothing but two
semi-colons!
Example 3:
j = 1;
sum = 0;
for (
;
;
){
sum = sum + j;
}
j++;
if (j > 10) break;
stop condition outside for
control area
Nested Loops
Recall when a control structure is contained
within another control structure, the inner one
is said to be nested.
if ...
for...
for ...
for ...
You may have repetition within decision and
vice versa.
Nested Loops - Ex.1
for within for
Example
int row,col;
for (row = 0; row < 5; row++) {
cout << "\n" <<row;
for (col = 1; col <= 3; col++){
cout <<"\t" << col;
}
cout << "\t**";
}
Nested Loops – Example 1
Output
0 1
1 1
2 1
3 1
4 1
2
2
2
2
2
3
3
3
3
3
**
**
**
**
**
variable row changes from
0 to 4
variable col changes from
1 to 3 for every time row
changes
Tracing Execution through Loops
1
for (row = 0; row < 5; row++)
{
Line
row
col
1
0
?
2
0
?
3
0
1
2
cout << "\n" <<row;
4
0
1
3
for (col = 1; col <= 3; col++){
5
0
1
3
0
2
4
0
2
5
0
2
3
0
3
4
0
3
5
0
3
6
0
4
7
0
4
1
1
4
2
1
4
3
1
0
4
1
0
5
1
0
4
cout <<"\t" << col;
5
}
6
cout << "\t**";
7
}
Nested Loops - Ex. 2
One off problem
for (exper =1; exper<=4; exper=exper +1) {
cout << "\tScores for experiment "<< exper <<":\n";
total = 0.0;
for (trial = 1; trial <=6; trial = trial +1) {
cout << "Enter result of trial " << trial <<" : ";
cin >> score;
total = total + score;
}
Why trial – 1 ?
avg = total/(trial-1);
cout << "Avg for experiment "<<exper<< " is “<< avg<< endl;
}
Recall Hand trace of nested loop
Inner loop terminated with value 4
one unit greater than terminating
condition col <=3
Same situation here, inner loop
terminates when value of trial
becomes 7
A value one more than items entered!
Need to correct by subtracting one
The while Statement
Syntax
start condition;
while (stop condition{
statements;
change statement;
}
Example of while
count = 1;
while (count <= 10) {
cout << “count = ” << count << endl;
count = count + 1;
}
next statement;
While vs. For
while is less rigid than for
while more suitable for event control
(clearer syntax) i.e . Keep processing until
something happens. E.g. the control variable
is assigned a specific value.
For is more structured
For is more suitable for fixed length loops
(clearer)
For is more common when used to process
arrays (see in later lecture on arrays)
Can choose either. Many do and just use one
or other all the time!
for = while?
for (cnt = 1; cnt < 7; cnt++){
cout << …
}
cnt = 1;
while (cnt < 7){
cout << …
cnt++;
}
The while and for Statement
 The loop control expression is tested before
any of the statements are executed


Possible never to execute any statement;
while needs a separate control variable
initialization before while begins.
 The body may contain any number of
statements, including branches and other
loops
 The control variable is changed any time
during loop execution for the while (usual to
be last statement though.
 The control variable is changed after the last
statement in the for structure.
 The statement immediately after the while or
for is executed upon exiting
Example List processing
Finding the Largest Value
Design: Needs a counter and a variable to hold maxvalue and a
variable to hold number entered by user
 Get the number of items in the list.
 Checks to see if that number is positive.

If not positive ask for the number to be entered again
 Get the first number and use it to initialise the variable that hold
the max value
 Increment a counter
 while we have more number to enter
get user to input a number.
 increment counter
 compare number with max - Assigns the largest to max.

 end loop
 display max
int count = 0, n = 0;
double max = 0, x = 0;
cout << "The maximum value will be computed.\n";
cout << "How many numbers do you wish to enter? ";
cin >> n;
while (n <= 0) {
cout << "\nERROR: Positive integer required.\n\n”;
cout << "How many numbers to enter? ";
cin >> n;
}
cout << “Enter a real number: “;
cin >> x;
max = x;
// first value to max
count++;
could read from
a file here
//entered a number so increase count by one
while (count < n) {
cout << “Enter a real number: “;
cin >> x;
count++;
//entered a number so increase count by one
if (max < x)
max = x;
}
cout << “Maximum value: “ << max << “\n”;
}
Output
The maximum value will be computed.
How many numbers do you wish to enter? 4
Enter a real number: 1.01
Enter a real number: -3
Enter a real number: 2.2
Enter a real number: 7.07000
Maximum value: 7.07
Counters
cout << “Enter “ << n << …
cin >> x;
max = x;
count = 1
while (count < n {
cout << “LOOP number: “
cin >> x;
if (max < x)
max = x;
count++;
}
count
n
loop executed
1
5
yes
2
yes
3
yes
4
yes
5
no
Running Totals
total = 0;
count =0
while (count <4) {
cout << “Enter a number: “;
cin >> num;
count++;
total = total + num;
cout << “The total is “ << total;
}
cout << “Grand total is “ << total << endl;
Choice for or while
Personal preference
Use for for fixed length loops
Use while for variable length loops
Common Errors
using = rather than == in test expressions can
cause infinite loops.
using == with floating point numbers
placing a semi colon at end of for statement.
for (i=0;i<=10;i++);
statement; //only executed once.
using comas as separators in a for
for (i=0, i<=10, i++)
one off problems
Summary
A loop is a section of repeating code
loop normally controlled by control variable, a
condition, an alter statement.
Three types of loop, 2 pre-test 1 post
test.
Conditions may be fixed count or variable
count.
Always use indentation and braces with
loops.
Loops are frequently nested.
Demos
Infinite Loops
Functions of one variable use debugger
Tables
Counting and accumulating
Interactive while
Interactive for
Menu systems
List processing
data validation