c/c++ programming for engineers: loopsi109/notes/5- loops.pdf7/17/2018 3 5 while loop syntax while(...
TRANSCRIPT
7/17/2018
1
C/C++ Programming for Engineers:Loops
John T. Bell
Department of Computer ScienceUniversity of Illinois, Chicago
2
Review
What would be the best data type to use to record the concentration of a solution in a chemistry laboratory experiment?
A. boolB. charC. doubleD. intE. long int
7/17/2018
2
3
The Power of Loops
• Computers are dumb machines, that only do what they are told.
• Their power lies in that they follow instructions very quickly, and don’t mind repeating the same instruction millions of times per second. Hence the power of the loop.
• The programmers job is then to tell the computer how to loop, when to stop looping, and what to do each pass through the loop.
4
While Loops
• The simplest loops to understand are whileloops, which continue looping as long as some condition remains true.
• The condition is evaluated BEFORE each iteration of the loop, and the loop is executed only if the condition is true.
• ( If the condition is initially false, then the loop will execute zero times, i.e. not at all. )
7/17/2018
3
5
While Loop Syntax
while( condition ) {
// code in body of loop
}
• If braces are omitted, then a single statement comprises the body of the loop.
condition?
body
Followingcode
False
True
6
While Example
int guess = -1, answer = rand( ) % 10 + 1;
while( guess != answer ) {
cout << “Enter a guess from 1 to 10: “;
cin >> guess;
}
cout << “That’s right! Congratulations!\n”;
Must be initialized to ensure loop entry
7/17/2018
4
7
Looping With a Counter
• Although a while loop could be used with a counter to loop a specified number of times, that is not good practice.
• The best approach when a loop must execute a specified number of times is with a for loop, which initializes the counter, tests it on each iteration, and ( typically ) increments it on each iteration.
8
For Loop Syntax
for( init; condition; incr ) {
// code in body of loop
}
• If braces are omitted, then a single statement comprises the body of the loop.
• Note “incr” always happens after executing the body.
condition?
body
Followingcode
False
True
incr
init
7/17/2018
5
9
The for incrementation component most commonly uses auto-increment:
• “i++;”, as a stand-alone statement, is equivalent to “i += 1;” or “i = i + 1;”
• “i--;”, as a stand-alone statement, is equivalent to “i -= 1;” or “i = i - 1;”
• There is more to auto-increment ( and auto-decrement ), which we cover elsewhere.
10
For Loop Example
cout << “ i i^2 i^3” << endl;
int i;
for( i = 1; i <= 10; i++ ) {
cout << i << “ “ << i * i << “ “ << i * i * i;
cout << endl;
}
cout << “After the loop, i = “ << i << endl;
7/17/2018
6
11
What will be printed after the loop ends?
for( i = 1; i <= 10; i++ ) {// Assume loop body does not change i
}cout << “After the loop, i = “ << i << endl;A. 0B. 1C. 10D. 11E. Undefined. It may depend on the compiler.
12
Do-While Loops
• Do-while loops are nearly identical to whiles.
• The condition is evaluated AFTER each iteration of the loop, and the loop is repeated only if the condition is true.
• A do-while loop will always execute at least once. After that it functions identically to a while loop.
7/17/2018
7
13
Do-While Loop Syntax
do {
// code in body of loop
} while( condition );
• Note required semi-colon
• If braces are omitted, then a single statement comprises the body of the loop. ( Very rarely omitted. )
condition?
body
Followingcode
False
True
14
Do-While Example
int guess, answer = rand( ) % 10 + 1;
do {
cout << “Enter a guess from 1 to 10: “;
cin >> guess;
} while( guess != answer ) ;
cout << “That’s right! Congratulations!\n”;
No initialization needed
7/17/2018
8
15
Break and Continue
• “break” causes a loop to finish immediately, continuing execution with the code following the loop body. ( Also used in switches. )
• “continue” causes the current iteration of a loop to finish, starting the next iteration.– While or do-while loops will jump to the
evaluation of the loop condition.
– For loops will execute the “incrementation”, and then jump to the evaluation of the loop condition.
16
For Loop Flowchart Illustrating break and continue
for( init; condition; incr ) {
// code 1
if( test_C )
continue;
// code 2
if( test_B )
break;
// code 3
}
condition?
code 1
Following code
False
True
incr
init
code 2
code 3
test_C
test_B
True
7/17/2018
9
17
Input Checking With a While Loop
int age = -1; // Initialized to guarantee loop entry
while( age < 0 || age > 120 ) {
cout << “Please enter your age: “;
cin >> age;
if( age < 0 || age > 120 )
cout << age << “ is invalid. Try again.\n”;
} // Continue while input is bad
18
Input Checking With a Do-While Loop
int age; // No initialization needed
do { cout << “Please enter your age: “;
cin >> age;
if( age < 0 || age > 120 )
cout << age << “ is invalid. Try again.\n”;
} while( age < 0 || age > 120 ); //Continue while bad
7/17/2018
10
19
Input Checking With an Infinite Loop
int age; // No initialization needed
while( true ) {
cout << “Please enter your age: “;
cin >> age;
if( age > 0 && age <= 120 ) // Exit loop if good
break;
cout << age << “ is invalid. Try again.\n”;
} // Loops infinitely while input is bad
20
Review
In the following statement, which of the following is the correct order in which the operators will be evaluated?
A *= B + C / D – E++;
A. *=, +, /, -, ++
B. /, +, -, *=, ++
C. ++, /, +, -, *=
D. ++, +, /, -, *=
E. None of the above. The correct order of operations is not listed here.
7/17/2018
11
21
When to Use What Kind of Loop
• If you can count ( or calculate ) how many times the loop must execute, use a for loop, always with an INTEGER counter.
• Else if you need to ensure the loop executes at least once, ( and can’t rig a while to do so ), use a do-while loop. ( A comment at the top of the loop improves readability. )
• Else use a while loop.
22
Review
What type of loop is guaranteed to execute at least once, and then continue to repeat until a condition becomes false?
A. forB. untilC. do untilD. whileE. do while
7/17/2018
12
23
Nested Loops
• The body of a loop can contain any valid code, including other loops, termed nested loops.– The internal loop does not have to be the same type
as the enclosing outer loop.
– A nested “for” loop is a common way to iterate over two variables and/or produce a table:for( i = 0; i < iMax; i++ ) {
for( j = 0; j < jMax; j++ )
cout << i * j << “ “; // Prints numbers on a line
cout << endl; // New line when j loop exits.
}
24
Empty Loops
• Loops can also be empty.
– This is very rarely done intentionally.
– Comments and braces are needed if this is done on purpose.
– Error example: An infinite empty loop:int i = 0;
while( i < 5 )
i = i + 1;
Error here. The body of the loop is between the closing ) and the ;
“i = i + 1;” is after the loop, not inside it, and will never be executed.
;
7/17/2018
13
25
Always Use an INTEGER Loop Counter
int i, nLoops; // ( Assume all vars are given values. )
double x, xMin, xMax, delataX;
// WRONG:
for( x = xMin; x <= xMax; x += deltaX ) { . . .
// RIGHT:
for( i = 0; i < nLoops; i++ ) {
x = xMin + i * deltaX;
. . .
26
Review
What value will be stored by the following C++ code:
double answer = 3 + 5 / 2 * 4 / 5.0;
A. 0.2
B. 3.2
C. 4.0
D. 4.6
E. 5.0
7/17/2018
14
27
Review
Given the following code, what will be stored in k?int i = 5, j = 4, k = 3;k /= i++ % --j;
A. 0B. 1C. 1.5D. 3E. infinity ( divide by zero error. )
28
Infinite Loop Knock Knock Joke
Knock knock
Knock who?
Who’s there?
Knock