UEE1302 (1102) F10 Introduction to Computers and Programming ...
Transcript of UEE1302 (1102) F10 Introduction to Computers and Programming ...
Computational Intelligence on Automation Lab @ NCTU
UEE1302 (1102) F10 UEE1302 (1102) F10 UEE1302 (1102) F10 Introduction to Computers
and Programming
UEE1302 (1102) F10 Introduction to Computers
and Programming
Programming Lecture 03 Programming Lecture 03 Flow of Control Flow of Control (Part II):(Part II):
Repetition Repetition whilewhile,, forfor & & do..whiledo..while
Learning ObjectivesLearning Objectives
In this chapter you will:
� Learn about repetition (looping) control structures, i.e. while, for and do…while
� Explore how to construct and use (1) count-controlled, (2) sentinel-controlled, (3) flag-controlled, and (4) EOF-controlled repetition structures
PRO_03 PROF. HUNG-PIN(CHARLES) WEN 2
structures
� Examine break and continue statements
� Discover how to form and use nested control structures
Flow of ExecutionFlow of Execution
statement 1 false truestatement 1
statement 2
statement N
• • •
bool_expr
stmt_NO stmt_YES
false true
loop_cond
stmt_Loop
false
true
PRO_03 PROF. HUNG-PIN(CHARLES) WEN 3
statement N
(A) sequence (B) selection (C) repetition
Why Is Repetition Needed?Why Is Repetition Needed?
� Repetition (a.k.a. Loop) –allow you to efficiently use variables–can input, add, and average multiple –can input, add, and average multiple
numbers using a limited number of variables
� For example, to add five numbers:–declare a variable for each number, input
the numbers and add the variables together
PRO_03 PROF. HUNG-PIN(CHARLES) WEN 4
the numbers and add the variables together–create a loop that reads a number into a
variable and adds it to a variable that contains the sum of the numbers
A First Look of LoopsA First Look of Loops
� 3 types of loop structures in C++1. while
–most flexible–no restrictions
2. do-while
–least flexible–always execute loop body at least once
PRO_03 PROF. HUNG-PIN(CHARLES) WEN 5
–always execute loop body at least once3. for
–natural counting loop
whilewhile Loop ExampleLoop Example
� Example:…
count = 0; // Initializationcount = 0; // Initializationwhile (count < 3) // Loop Condition{
cout << "Hi "; // Loop Bodycount++; // Update expression
}
…
PRO_03 PROF. HUNG-PIN(CHARLES) WEN 6
…
–Loop body executes how many times?
dodo--whilewhile Loop ExampleLoop Example
� Example:…
count = 0; // Initializationcount = 0; // Initializationdo {
cout << "Hi "; // Loop Bodycount++; // Update expression
} while (count < 3); // Loop Condition
PRO_03 PROF. HUNG-PIN(CHARLES) WEN 7
while (count < 3); // Loop Condition…
–Loop body executes how many times?–do-while loops always execute body at least
once!
forfor Loop ExampleLoop Example
� Example:for (count=0; count<3; count++) {{
cout << "Hi "; // Loop Body}
� How many times does loop body execute?� Initialization, loop condition and update are all
PRO_03 PROF. HUNG-PIN(CHARLES) WEN 8
� Initialization, loop condition and update are allbuilt into the for-loop structure!
� A natural "counting" loop
The The whilewhile Loop (1/2)Loop (1/2)
� Syntax of the while statement is:while (entry_cond)while (entry_cond)
statement_while;
� Statement statement_while can be either simple or compound �
body of the loop � Expression entry_cond acts as a
decision maker and is usually a
entry_cond
stmt_while
false
true
PRO_03 PROF. HUNG-PIN(CHARLES) WEN 9
decision maker and is usually a Boolean expression
� The parentheses (…) are part of the syntax
The The whilewhile Loop Loop (2/2)(2/2)
� Expression entry_cond provides an entry condition
� Statement statement_while executes if the � Statement statement_while executes if the expression initially evaluates to true
� Loop condition entry_cond is then reevaluated � Statement continues to execute until the
expression entry_cond is no longer true
PRO_03 PROF. HUNG-PIN(CHARLES) WEN 10
� Infinite loop: continues to execute endlessly–can be avoided by including statements in
the loop body that assure exit condition will eventually be true
whilewhile Loop Example (Loop Example (1/2)1/2)
� Example:…idx = 0;idx = 0;while (idx < 10){
cout << 2*idx << “ ”;idx += 2; // idx= idx + 2
} cout << endl;
PRO_03 PROF. HUNG-PIN(CHARLES) WEN 11
cout << endl;…
Sample Run:> ./a.out0 4 8 12 16
whilewhile Loop Example (Loop Example (2/2)2/2)
…idx = 20;while (idx < 20) //never satisfy entry_cond{
cout << idx << “ ”;idx += 5;
} cout << endl;…
Sample Run:
PRO_03 PROF. HUNG-PIN(CHARLES) WEN 12
Sample Run:>./a.out
�
_
whilewhile (1): Counter(1): Counter--ControlledControlled
� If you know exactly how many pieces of data need to be read, the while loop becomes a counter-controlled loopcounter-controlled loop
� Example of counter-controlled loop:
counter = 0; // initialize loop control
while (counter < Limit) // test loop control{
statements;
PRO_03 PROF. HUNG-PIN(CHARLES) WEN 13
statements;…counter++; // update loop control
}
whilewhile (2): Sentinel(2): Sentinel--ControlledControlled
� Sentinel variable is tested in the condition and loop ends when sentinel is encountered
� Example of sentinel-controlled loop:cin >> target; // initialize loop control
while (target != sentinel) //test loop control{
statements;
PRO_03 PROF. HUNG-PIN(CHARLES) WEN 14
statements;…cin >> target; // update loop control
}
whilewhile (3): Flag(3): Flag--ControlledControlled
� A flag-controlled while loop uses a bool
variable to control the loop� Example of flag-controlled loop:
loop_stop = false; // initialize loop control
while (!loop_stop) // test loop control{
…if (expression) // update loop control
PRO_03 PROF. HUNG-PIN(CHARLES) WEN 15
if (expression) // update loop controlloop_stop = true;
…
}
whilewhile (4): EOF(4): EOF--ControlledControlled
� A EOF-controlled while loop uses a EOF (End-of-File) to control the loop
� The logical value returned by cin can � The logical value returned by cin can determine if the program has ended input
� Example of EOF-controlled loop:
cin >> var; // initialize loop control
while (cin) // test loop control{
� cin does not reach EOF
PRO_03 PROF. HUNG-PIN(CHARLES) WEN 16
{…cin >> var; // update loop control…
}
cin
Or use while (!cin.eof())
The The eofeof FunctionFunction
� When a program is reading from a disk file, eofcan determine the end of file status–When reading from input devices like –When reading from input devices like
keyboard, use ctrl+z or ctrl+d denotes eof� eof is a member of data type istream
– iostream includes header files of istream, ostream and others
� Syntax for the function eof is: istreamObj.eof()
PRO_03 PROF. HUNG-PIN(CHARLES) WEN 17
� Syntax for the function eof is: istreamObj.eof()– istreamObj is an input stream variable, such
as cin . EX: cin.eof()– cin.clear();to reset eof and restart reading
from input devices
whilewhile Pitfalls: Misplaced Pitfalls: Misplaced ;;
� Watch the misplaced ; (semicolon)–Example:while (response!= 0);while (response!= 0);
{
cout << "Enter val: ";
cin >> response;
}
–Notice the ";" after the while condition!
PRO_03 PROF. HUNG-PIN(CHARLES) WEN 18
� Result here: INFINITE LOOP!
whilewhile Pitfalls: Infinite LoopsPitfalls: Infinite Loops
� Loop condition must evaluate to false atsome iteration through loop–If not � infinite loop–If not � infinite loop
� Example:while (1){
cout << "Hello ";}
PRO_03 PROF. HUNG-PIN(CHARLES) WEN 19
–a perfectly legal C++ loop � always infinite!� Sometimes, infinite loops can be desirable
–e.g., "Embedded Systems"
TheThe forfor LoopLoop
Syntax of for statement: for (init_stmt;lp_cond;update_stmt)
− init_stmt: initialize ctrl variable − lp_cond: compare ctrl variable− update_stmt : update ctrl
variable
loop_cond
stmt_for
false
true
init_stmt statement_for;
PRO_03 PROF. HUNG-PIN(CHARLES) WEN 20
variable
� Action statement stmt_for can be a compound statement–much more typical
update_stmt
forfor versus versus whilewhile (1/2)(1/2)
� Rewrite for statement in while loop:init_stmt;while (lp_cond)while (lp_cond){
stmt_for;update_stmt;
}
� Rewrite while statement in for loop:for ( ; entry_cond; )
PRO_03 PROF. HUNG-PIN(CHARLES) WEN 21
for ( ; entry_cond; ) {
stmt_while;}
forfor versus versus whilewhile (2/2)(2/2)
� Components of for statement are optional but semicolons “;” must always be present–omissions � doing nothing in init_stmt and –omissions � doing nothing in init_stmt and update_stmt or being true in lp_cond
–EX: for ( ; ; ) { statements;} is valid � Differentiate for from while:
– initialization statements grouped as first set of items init_stmt within the for’s ()
PRO_03 PROF. HUNG-PIN(CHARLES) WEN 22
items init_stmt within the for’s ()– loop condition and loop statements are fixed: no
change in for–update statements as the last set of items update_stmt within the for’s ()
forfor Loop Example Loop Example 1 (1/3)1 (1/3)
Example 1: …for (count=2; count<=20; count+=2){{
cout << count << “ ”; } …
Modified Example 1a:…count = 2; for ( ; count<=20; count+=2){
PRO_03 PROF. HUNG-PIN(CHARLES) WEN 23
for ( ; count<=20; count+=2){
cout << count << “ ”; } … Sample Run:
>./a.out2 4 6 8 10 12 14 16 18 20
forfor Loop Example Loop Example 1 (2/3)1 (2/3)
Example 1: …for (count=2; count<=20; count+=2){{
cout << count << “ ”; } …
Modified Example 1b:…count = 2; for ( ; count<=20; ){
PRO_03 PROF. HUNG-PIN(CHARLES) WEN 24
{cout << count << “ ”; count +=2;
} …
forfor Loop Example Loop Example 1 (3/3)1 (3/3)
Example 1: …for (count=2; count<=20; count+=2){{
cout << count << “ ”; } …
Modified Example 1c:…count = 2;for (count=2; count<=20;
cout << count << “ ”, count+=2)
PRO_03 PROF. HUNG-PIN(CHARLES) WEN 25
cout << count << “ ”, count+=2){
; } …
forfor Loop Example Loop Example 2 (1/22 (1/2))
Example 2: for (idx=1; idx<=5; idx++){{
cout << “Hello!” << endl;cout << “*” << endl;
}
Example 2a:for (idx=1; idx<=5; idx++)
cout << “Hello!” << endl;
What will happen?
PRO_03 PROF. HUNG-PIN(CHARLES) WEN 26
cout << “Hello!” << endl;cout << “*” << endl;
What will happen?
forfor Loop Example Loop Example 2 (2/22 (2/2))
Example 2: …for (idx=1; idx<=5; idx++)for (idx=1; idx<=5; idx++){
cout << “Hello!” << endl;cout << “*”<< endl;
} …
Example 2b:…
PRO_03 PROF. HUNG-PIN(CHARLES) WEN 27
…for (idx=1; idx<=5; idx++) ;
cout << “Hello!” << endl;cout << “*” << endl;
… What will happen?
Comments on Comments on forfor looploop
� If loop condition lp_cond is initially false � do nothing –Ex: for (idx=0; idx > 0; idx++)–Ex: for (idx=0; idx > 0; idx++)
� Update statement update_stmt eventually sets the value of lp_cond to false � otherwise, this for loop will run forever. –Ex: for (idx=0; idx<100; idx--)
� If ctrl variable is float/double, then different
PRO_03 PROF. HUNG-PIN(CHARLES) WEN 28
� If ctrl variable is float/double, then different computers may yield different results on ctrl variable � should avoid using such variable.–Ex: for (double idx=0.1; idx<1.2; idx+=0.05)
The The do…whiledo…while Loop (1/2)Loop (1/2)
� Syntax of do…while statement:do
stmt_dowhile;
while (rep_cond);
� Statement stmt_dowhileexecutes first, and then rep_cond is evaluated
� If evaluates to ,
rep_cond
stmt_dowhile
falsetrue
PRO_03 PROF. HUNG-PIN(CHARLES) WEN 29
� If rep_cond evaluates to true, the statement stmt_dowhileruns again
false
The The do…whiledo…while Loop Loop (2/2)(2/2)
� As long as rep_cond in a do…while statement is true, the statement stmt_dowhile executes
� To avoid an infinite loop, the loop body stmt_dowhile must contain a update statement that makes rep_cond to be false
� The statement stmt_dowhile can be simple or compound
PRO_03 PROF. HUNG-PIN(CHARLES) WEN 30
compound
� If compound, it must be in braces { … }
� do…while loop typically has an exit condition and iterates at least once (unlike for and while)
do…whiledo…while Loop ExampleLoop Example
Example 1: …idx = 1;idx = 1;do{
cout << idx << “ ”;idx *= 2;
} while (idx <= 20);…
PRO_03 PROF. HUNG-PIN(CHARLES) WEN 31
…
Answer: 1 2 4 8 16 1 2 4 8 16 1 2 4 8 16 1 2 4 8 16
What will be displayed on screen?
do…whiledo…while Loop Loop vsvs whilewhile Loop Loop
Example 2a: …idx = 15;
Example 2b: …idx = 15;idx = 15;
do{
idx %= 8;} while (idx > 15);cout << idx << endl;
idx = 15;while (idx > 15){
idx %= 8;} cout << idx << “ ”;…
PRO_03 PROF. HUNG-PIN(CHARLES) WEN 32
cout << idx << endl; …
Answer: 7777 Answer: 15
What will be displayed on screen?
breakbreak & & continuecontinue in in RepetitionRepetition
� Flow of Control–Recall how loops provide "graceful" and
clear flow of control in and outclear flow of control in and out–In RARE instances, can alter natural flow
� break
–force the loop to exit immediately.� continue
–skip the rest of loop body
PRO_03 PROF. HUNG-PIN(CHARLES) WEN 33
–skip the rest of loop body
� These statements violate natural flow–only used when absolutely necessary!
breakbreak in Loopin Loop
� break: forces immediate exits from structures:–in switch statements:� the desired case is detected/processed� the desired case is detected/processed
–in while, for and do…while statements:� an unusual condition is detected
� Example:for (idx=10; idx<=50; idx+=2){
if (idx%9 == 0)
PRO_03 PROF. HUNG-PIN(CHARLES) WEN 34
if (idx%9 == 0)break;
cout << idx << “ ”; }
What will be displayed on screen?
10 12 14 16 �
continuecontinue in Loopin Loop
� continue: cause the next iteration of the loop to begin immediately–execution transferred to the top of the loop –execution transferred to the top of the loop –apply only to while, for and do…while
statements� Example: idx = 0;while (idx < 100) { What will be displayed
PRO_03 PROF. HUNG-PIN(CHARLES) WEN 35
{idx++; if (idx == 50)
continue;cout << idx << endl;
}
What will be displayed on screen?1 2…48 49 51 52…98 99
Nested Nested Loops (1/2)Loops (1/2)
� A loop contained within another loop� Example: Print 9x9 multiples� Example: Print 9x9 multiples
for (idx=1; idx<=9; idx++) //outer loop
{
cout << idx << “-multiples: ” << endl;
for (jdx=1; jdx<=9; jdx++) //inner loop
{
PRO_03 PROF. HUNG-PIN(CHARLES) WEN 36
{
cout << idx*jdx << “ ” ;
} // end of inner loop
} // end of outer loop
Nested Loops Nested Loops (2/2)(2/2)
� Outer (first) Loop:–controlled by value of idx
� Inner (second) Loop:–controlled by value of jdx
� Rules:–For each single trip through outer loop,
inner loop runs through its entire sequence
PRO_03 PROF. HUNG-PIN(CHARLES) WEN 37
inner loop runs through its entire sequence–Different variables to control each loop–Inner loop statements contained within
outer loop
Summary (1/3)Summary (1/3)
� C++ has three looping (repetition) structures: while, for and do…while
� while, for and do…while are reserved words
� while and for loops are called pre-test loops
� do…while loop is called a post-test loop
� while and for may not execute at all, but
PRO_03 PROF. HUNG-PIN(CHARLES) WEN 38
� while and for may not execute at all, but do…while always executes at least once
Summary (2/3)Summary (2/3)
� while: expression is the decision maker, and the statement is the body of the loop
� In a counter-controlled while loop, � In a counter-controlled while loop, –Initialize counter before loop–Body must contain a statement that
changes the value of the counter variable� A sentinel-controlled while loop uses a
sentinel to control the loop
PRO_03 PROF. HUNG-PIN(CHARLES) WEN 39
sentinel to control the while loop� An EOF-controlled while loop executes until
the program detects the end-of-file marker
Summary (3/3)Summary (3/3)
� for: simplifies the writing of a count-controlled while loop
� Executing a break statement in the body of a loop immediately terminates the loop
� Executing a continue statement in the body of a loop skips to the next iteration
� After a continue statement executes in a
PRO_03 PROF. HUNG-PIN(CHARLES) WEN 40
� After a continue statement executes in a for loop, the update statement is the next statement executed