introduction to loops iteration repetition counting loops also known as
TRANSCRIPT
Introduction to Loops
IterationRepetitionCounting
Loops Also known as
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 countingFor accumulatingFor searchingFor SortingFor displaying tablesFor data entryFor menu processingFor list processingFor simulations.
Types of loops
for (start condition; stop condition; change expression)while (stop condition)do..while(stop condition)
C/C++ Loop Structures
Pre-testfor loops (most common)
When you know how many times (fixed condition)
while loopsWhen you don’t know how many times
Event controlled (variable condition)
Post-testdo … 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 eventKeep 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
for (init controller; Ctrl expression; Alter controller){
statements;}
Example:for (count=1; count < 7; count++) {
cout << “count = ” << count << endl;}next statement;
start condition change expressionstop condition
The for StatementUsed as a counting loopUsed when we can work out in advance the number of iterations.Semicolons separate the itemsYou may declare variable and initialize it
example:
for (int count = 1; count < 7; count++){statement(s);
}
int num;cout << "NUMBER\tSQUARE\tCUBE\n“; cout << "------\t------\t----\n";
for (num = 1; num < 11; num++) {cout << num << “\t“;cout << num * num << “\t“;cout << num * num * num<<“\n";
}
A Simple ExampleCreate a table with a for loop
NUMBER SQUARE CUBE---------- ---------- ------ 1 1 1 2 4 8 . . . . . . 10 100 1000
for and if Statements working together.
Simple search for divisorsGiven an integer number find all the numbers that divide exactly into it (except 1 and itself).
e.g. if number = 12, divisors are 2,3,4,6
Thinks I canuse %
operator to find divisors
Solution Design
Get the number for userBy 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 numberif 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;
}
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 ?????
Common errors in constructing for Statements
Infinite loops
for (j=0; j>=0; j++) {cout << i << endl;
}
DEMO1 ChrisBe careful with terminating
conditions!
Programming convention
Use of integers called i,j,kYou will see them all the time.Most commonly used as loop controller variablesConventionally 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 ) ExpressionsExample 1:
j = 1;sum = 0;for ( ; j <= 10; j = j + 1){
sum = sum + j;
}
Empty/Null expression
Start condition outside for control area
We could do this
Example 2:
j = 1;sum = 0;for ( ; j <= 10; ){
sum = sum + j;
j = j + 1;
}
Empty/Null expressionEmpty/Null expression
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 LoopsRecall when a control structure is contained within another control structure, the inner one is said to be nested.
for ...if ...
for ...for...
You may have repetition within decision and vice versa.
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 - Ex.1for within for
Output0 1 2 3 **
1 1 2 3 **
2 1 2 3 **
3 1 2 3 **
4 1 2 3 **
Nested Loops – Example 1
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++) {
2 cout << "\n" <<row;
3 for (col = 1; col <= 3; col++){
4 cout <<"\t" << col;
5 }
6 cout << "\t**";
7 }
Line row col
1 0 ?
2 0 ?
3 0 1
4 0 1
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
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;
} avg = total/(trial-1); cout << "Avg for experiment "<<exper<< " is “<<
avg<< endl; }
Nested Loops - Ex. 2One off problem
Why trial – 1 ?
Recall Hand trace of nested loop
Inner loop terminated with value 4 one unit greater than terminating condition col <=3Same situation here, inner loop terminates when value of trial becomes 7A value one more than items entered!Need to correct by subtracting one
The while Statement
Syntaxstart 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. Forwhile is less rigid than forwhile 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 structuredFor 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 = 1cnt = 1; cnt < 7; cnt++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 processingFinding the Largest Value
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
Design: Needs a counter and a variable to hold maxvalue and a variable to hold number entered by user
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++; //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 oneif (max < x) max = x;
}cout << “Maximum value: “ << max << “\n”;}
could read from a file here
Output
The maximum value will be computed.How many numbers do you wish to enter? 4Enter a real number: 1.01 Enter a real number: -3 Enter a real number: 2.2Enter a real number: 7.07000 Maximum value: 7.07
CountersCounters
cout << “Enter “ << n cout << “Enter “ << n << … << … cin >> x;cin >> x;max = x;max = x;
count = count = 11
while (count < nwhile (count < n {{
cout << “LOOP cout << “LOOP number: “number: “
cin >> x;cin >> x; if (max < x)if (max < x) max = x;max = x;
count++;count++;
}}
count n loop executed
1 5 yes
2 yes
3 yes
4 yes
5 no
Running Totalstotal = 0;
count =0while (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 preferenceUse for for fixed length loopsUse while for variable length loops
Common Errors
using = rather than == in test expressions can cause infinite loops.using == with floating point numbersplacing a semi colon at end of for statement.
for (i=0;i<=10;i++);statement; //only executed once.
using comas as separators in a forfor (i=0, i<=10, i++)
one off problems
SummaryA 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 LoopsFunctions of one variable use debugger TablesCounting and accumulatingInteractive whileInteractive forMenu systemsList processingdata validation