Lecture_5_Loops_ST[1]

Download Report

Transcript Lecture_5_Loops_ST[1]

Chapter 5
Iteration With while Loops and for Loops.
5.1
More About The while Loop:
Initializers, Accumulators,
and Exit Condition.
int num, sum = 0;
// initializing
while (sum < 100)
//exit condition based on loop body
{
cout <<"Enter a number less than 100 : " ;
cin >> num;
sum += num;
//sum = sum + num *accumulator*
}
cout << “the sum is ”<< sum << endl:
5.2
What is the last number printed by
the loop below:
HOMEWORK
int num = 0;
while (num < 100)
{
num += 2;
cout << num << endl;
}
What is output by the following
code segment?
int n = 4, p = 1;
while (n > 0)
{
p *= n;
n--;
cout << p << endl;
}
5.3
HOMEWORK
What is output by the following code
segment?
int x = 16;
while (x > 1)
{
cout << x << endl;
x /= 2;
}
5.4
Consider the following code segment:
int prod = 1;
int num = 5;
int k = 1;
while (k <= num)
{
prod *= k;
k ++;
}
cout << prod << endl;
What value is output as a result of executing the above code segment?
Trace k
num
prod
k at end of loop
1
2
3
4
5
6
1
1
2
3
-
5
5
5
5
-
1
1
2
6
-
2
3
4
5.5
Consider the following code segment:
int prod = 1;
int num = 5;
int k = 1;
while (k <= num){
prod = prod * k;
k ++;
}
cout << prod << endl;
What value is output as a result of executing the above code
segment?
Trace k
num
prod
k at end of loop
1
5
1
1
1
5
1
2
2
2
5
2
3
3
3
5
6
4
4
5
120
6
-
5.6
Consider the function SomeSum given below:
int SomeSum(int number) //function header
// precondition: number >= 0
// postcondition: ???
Trace n
{
1
int sum = 0;
s
n%10
s+=n%10
n/=10
while (number > 0)
{
sum += number % 10;
number /= 10;
}
return sum;
}
// end of function
What value is returned by the call SomeSum(0) ?
What value is returned by the call
What value is returned by the call
SomeSum(7) ?
SomeSum(512) ?
5.7
Consider the function SomeSum given below:
int SomeSum(int number) //function header
// precondition: number >= 0
// postcondition: ???
Trace n
{
1
0
int sum = 0;
s
n%10
s+=n%10
n/=10
while (number > 0)
{
sum += number % 10;
number /= 10;
}
return sum;
}
// end of function
What value is returned by the call SomeSum(0) ?
What value is returned by the call
What value is returned by the call
0
SomeSum(7) ?
SomeSum(512) ?
5.8
Consider the function SomeSum given below:
int SomeSum(int number) //function header
// precondition: number >= 0
// postcondition: ???
Trace n
{
1
7
int sum = 0;
s
0
n%10
7
s+=n%10
7
n/=10
0
while (number > 0)
{
sum += number % 10;
number /= 10;
}
return sum;
}
// end of function
What value is returned by the call SomeSum(0) ?
0
What value is returned by the call
7
What value is returned by the call
SomeSum(7) ?
SomeSum(512) ?
5.9
Consider the function SomeSum given below:
int SomeSum(int number) //function header
// precondition: number >= 0
// postcondition: ???
Trace n
{
1
512
int sum = 0;
2
51
3
5
while (number > 0)
{
sum += number % 10;
number /=10;
}
return sum;
}
// end of function
s
0
2
3
n%10
2
1
5
s+=n%10
2
3
8
What value is returned by the call SomeSum(0) ?
0
What value is returned by the call
7
What value is returned by the call
SomeSum(7) ?
SomeSum(512) ?
n/=10
51
5
0
8
5.10
Consider the function SomeSum given below:
int SomeSum(int number) //function header
// precondition: number >= 0
// postcondition: ???
Trace n
{
1
512
int sum = 0;
2
51
3
5
while (number > 0)
{
sum += number % 10;
number /=10;
}
return sum;
}
// end of function
s
0
2
3
n%10
2
1
5
s+=n%10
2
3
8
What value is returned by the call SomeSum(0) ?
0
What value is returned by the call
7
What value is returned by the call
SomeSum(7) ?
SomeSum(512) ?
n/=10
51
5
0
8
Note: This algorithm finds the sum of the individual digits.
Try it with any other 2 or 3 digit number and see.
5.11
** This is a problem in your next project.
Talk about counting how many digits in a number using similar code.
Priming a while Loop
• Problem: enter numbers, add them up, stop when 0 entered
• What should loop test be?
int sum = 0;
int num;
cout << “Enter a number. “;
cin >> num;
// prime the loop
while (num != 0)
{
sum += num;
cout << “Enter a number. “;
cin >> num;
// again at end of body of loop
}
cout << "total = " << sum << end;
• Code duplication problem: input (and prompt) code is repeated
before loop and in the loop at the end of body of the loop.
• Alternative to duplicated code on next slide?
5.12
Alternative Solution without priming
• An alternative to repeating code:
• break statement exits (inner-most) loop
int sum = 0;
// initialize accumulator
int num;
while (true)
{
cout>> “enter measure of sides (0 to quit)”;
cin >> num;
if (num == 0)
// get out of loop
{
break; // exit loop when exit condition is met.
}
sum += num; // accumulate sum
}
cout << "total = " << sum << end;
5.13
While Loop with an accumulator, a counter, and
sentinel for exit condition
• A sentinel is a specific value for user to enter that marks the end
of input.
double sentinel = -99; //test for exit condition
double num;
double sum = 0;
//initialize the accumulator
double count = 0;
//initialize the counter
cout <<“Enter test grades (-99 when finished)”;
cin >>num
//priming read
while (num != sentinel)
{
count++;
//increment the counter.
sum += num;
//add num to the accumulator.
cout <<“Enter test grades (-99 when finished)”;
cin >> num;
}
cout << “average = " << sum/count << end;
5.14
While Loop with an accumulator, a counter, and
sentinel for exit condition
• A sentinel is a specific value for user to enter that marks the end of input.
double sentinel = -99; //test for exit condition
double num;
double sum = 0;
//initialize the accumulator
double count = 0;
//initialize the counter
cout <<“Enter test grades (-99 when finished)”;
cin >>num
//priming read
What would happen
while (num != sentinel)
if the counter and
{
accumulator were
count++;
//increment the counter.
not initialized?
sum += num;
//add num to the accumulator.
cout <<“Enter test grades (-99 when finished)”;
cin >> num;
//-99 is sentinel
}
cout << “average = " << sum/count << end;
5.15
For Loops
Easier to use when the number of iterations are known.
SYNTAX:
for (initialization; test expression; update)
{
Statement(s);
Note
no ;
}
Initialization -
sets the starting value of a counter.
Test expression – contains maximum value a counter can
have & determines when loop is finish.
Update – alter the counter. Use the postincrement operator
k++, or decrement k--, or j += x.
5.16
For Loops, continued
• Numbers can be variables.
• Update takes place at the very end of the for statement.
Example of for loop.
Write the numbers and the squares of all the
numbers from 1 to 9.
for (int i=1; i<=9; i++)
{
cout << i <<“
“<< i*i << endl;
}
Note:
The for loop is better than the while loop for
running a program a specific number of times as
done in previous assignments.
5.17
For Loops, continued
• Numbers can be variables.
• Update takes place at the very end of the for statement.
Example of for loop.
Add up even integers between 16 & 26.
int sum = 0;
for (int i=16; i <= 26; i += 2)
{
sum += i;
}
cout<<“sum = “<<sum<< endl;
5.18
HOMEWORK
• Write the for loop equivalent to the following while loop. (num is a
variable with a value).
int k=1;
sum = 0;
While (k<= num)
{
sum += k;
k += 2;
}
5.19
Alternate forms of loops……
HOMEWORK
sum = 0;
for(int x = 1; x <= 10; x++)
{
sum += x;
}
• Rewrite as a while loop.
• Rewrite as a do while loop.
5.20
Alternate forms of loops……
HOMEWORK
x = 0;
do
{
x ++;
cout<<x<<“ “;
}
while (x <= 20);
• Rewrite as a while loop.
• Rewrite as a for loop.
5.21
Alternate forms of loops……
HOMEWORK
x = 2;
while (x <= 30)
{
cout<<x<<“ “;
x += 2;
}
• Rewrite as a do while loop.
• Rewrite as a for loop.
5.22
Finding the Minimum Number and Maximum Number
void MinMax()
{
// Initialize highest possible value for min
int num = 0, min = 100, max = 0; //and lowest possible value for max
for(int i=1; i < 10; i++)
{
do
{
cout << “Enter a number between 1 and 100. ”;
cin >> num;
}
while (num < 1 || num > 100);
//check for bad input
if (num < min)
min = num;
if (num > max)
max =num;
}
5.23
cout << “max = “ << max << “ min = ” << min << endl;
}
Assignment 5: Write a program
with the following 4 functions.
Write a function to return the number of digits in its
positive integer parameter.
State precondition and postcondition
Write a function to return the sum of the digits of its positive integer
parameter
State precondition and postcondition
Write a function that asks the user for 25 integers.
The output will be sentences indicating :
1. The smallest integer entered.
2. The largest integer entered
State precondition and postcondition
5.24
See next slide for fourth function.--
Add to the program the following
function.
Write a function with while loop that accepts positive integers 1-100 from a
keyboard until a sentinel (use 999) terminates the input.
1. Ignore any invalid numbers. If the number is not valid and not the sentinel, the
program should explain that to the user and prompt the user for another number.
This check for bad input could require a do while loop.
2. Output the number of integers keyed in, their sum, and their average. Use a
counter and an accumulator.
State precondition and postcondition
Continue this lecture with the following slides on nested loops
………………………………………………………………>
5.25
Part Two of Lecture 5:
Nested loops
Sometimes one loop occurs inside another. Why?
• Checking for bad input inside a loop.
• Generating tabular data
• The outside loop starts the rows .
• The inside loop has the values for the columns.
• Examples:
– Multiplication tables
– Displaying courses and grades for each
– Displaying bills and amount for each month
• Displaying bar graphs for data.
• Sorting and searching vectors (which is studied much later)
• There are numerous other reasons for nesting loops.
5.26
Nested loops
• Sometimes one loop occurs in another
• Generating tabular data
• The outside loop makes rows and the inside loop makes columns.
• Sorting vectors (which is studied much later)
for(int j=1; j <= 6; j++)
{
cout << j;
for(int k=1; k <= 6; k++)
{
cout << "\t" << j*k;
}
cout << endl;
}
• What’s printed? What’s the purpose of the inner loop?
5.27
Nested loops
• Sometimes one loop occurs in another
• Generating tabular data
• The outside loop makes rows and the inside loop makes columns.
• Sorting vectors (which is studied much later)
1 1 2 3
4
for(int j=1; j <= 6; j++)
2 2 4 6
8
{
cout << j;
3 3 6 9
12
for(int k=1; k <= 6; k++)
4 4 8 12 16
{
5 5 10 15 20
cout << "\t" << j*k;
6 6 12 18 24
}
cout << endl;
}
• What’s printed? What’s the purpose of the inner loop?
5
6
10
12
15
18
20
24
25
30
30
36
5.28
Nested loops
• Often code is simpler to reason about if inner loop is moved
to another function
int j,k;
for(j=1; j <= 6; j++)
{
cout << j;
for(k=1; k < j; k++)
{
cout << "\t" << j*k;
}
cout << endl;
}
• What’s printed? What’s the purpose of the inner loop?
5.29
Nested loops
• Often code is simpler to reason about if inner loop is moved
to another function
1
2
3
4
5
6
2
3
4
5
6
6
int j,k;
8
for(j=1; j <= 6; j++)
10
{
12
cout << j;
for(k=1; k < j; k++)
{
cout << "\t" << j*k;
}
cout << endl;
}
• What’s printed? What’s the purpose of the inner loop?
12
15
18
20
24
30
5.30
Give output:
HOMEWORK
for (x = -2; x <= 2; x++)
cout << x *x << endl;
for (x=1; x <= 5; x++)
{
cout << x <<endl;
for (y = 1; y <= x; y++)
{
cout << y ;
}
cout <<endl;
}
5.31
Give output:
HOMEWORK
• for (x = 1; x <= 2; x++)
•
for (y = 1; y <= 2; y++)
•
for (z = 1; z <= 2; z++)
cout << x << y << z << endl ;
x
y
//OUTPUT
z
5.32
Give output:
HOMEWORK
for(d=1; d<=4; d++)
{
cout<<endl;
for(a=1; a<=d; a++)
{
cout<<"*";
}
}
5.33
Write a segment of code that will print the each
output below (use nested loops!).
#1
*
**
***
****
#2
****
***
**
*
5.34
Write a segment of code that will print the each
output below (use nested loops!).
#3:
1
12
123
1234
#4
4444
333
22
1
5.35
Write a segment of code that will print the each
output below (use nested loops!).
#5:
1234
234
34
4
#6
1111
222
33
4
5.36
Write a segment of code that will print the each
output below (use nested loops!).
#7
*
**
***
****
5.37