Lecture 4: Control Flow – Loops
Computer Programming
Loop
2
! Looping is a syntax which allows repetition of some tasks subjected to the
conditions specified by the programmer
! Example of such condition could be based on a “count” (e.g. repeat 100
times) and could be any Boolean criteria (e.g. repeat until user answer ‘N’)
! Depending on the criteria, the loop can execute zero time, one time, up to
million times, or even forever!
! There are three types of loops in C/C++:
! While-Loop
! For-Loop
! Do-While Loop
! The three types of loops are very similar and sometimes even inter-
changeable (e.g. you can use only for-loop and never use while-loop in your life!)
! By using loops, the code size is now independent of the times of repetition.
(even if repeating 1000 times, the code size is still small but not 1000 times larger)
While loops – Syntax
! Let’s being with the simplest type: while-loops
! Syntax:
while ( Boolean_condition ) statement;
! Students may find it similar (only similar!) to if( ) in the sense that:
! There are parenthesis ( ), inside which we put Boolean conditions
! By default only ONE statement is run. If we need to execute two or more tasks,
we need compound statement with curly brackets { }
! No semi-colon between ( ) and the following statement
! However while () is different from if ():
! If () clause execute only ONCE when the condition is fulfilled, but while () keep
running REPEATEDLY as long as the condition is true.
! There is no else clause for while ()
While loops – Meaning
! Syntax:
while ( Boolean_condition ) statement;
! Meaning of while-loop is equivalent to as-long-as in English:
! When while() clause is executed, the Boolean condition is first checked
! If the condition is false, the while statement is skipped (execute 0 time!)
! If the condition is true, the statement is executed. After that, the condition is
checked again, if it is still true, the statement is executed again. The checking /
execution is repeated again and again until the statement finally become false.
Condition
is true?
statement
Yes!
No!
While loops – Example
! Suppose we’d like to print the numbers 1 to 100 on separate lines…
! We need a variable (let’s call it num) for the count, the value is initially 1
! We want to REPEAT printing the number AS LONG AS the num is
no greater than 100
! Besides “printing”, we also have another important task!
! This is… “to increase the num by 1”! (if not, it only prints 1 and loop forever!)
! As we have 2 statements (print & increase) to repeat, we use { … }
num=1;
while (num<=100) {
cout<
bool isPrime=true;
for (i=2; i
} while (num<=0); Deviation from normal flow with break or continue ! The 3 types of loops here keep on running until the condition become false. However sometimes we may wish to finish the loop earlier ! Consider the example for Prime checking again. The program keeps looping for a total of num-2 times (2..num-1), regardless of the number ! However, for even numbers like 1000, we could actually conclude that it is not a Prime at very early stage (when we check against 2) ! In other words, the trials from 3..999 are useless! It just waste CPU time ! For a case like this, we can use the break; command, which jumps immediately to the end of loop, canceling all remaining passes ! If you’d like to cancel just the current pass (but want to keep the remaining passes), you may use the continue; command instead ! However, in most cases, break; and continue; are avoidable. We could actually achieve the same effect using if() and/or extra variables Deviation from normal flow with break or continue Condition is true? Statement break; Yes! No! break jumps immediately to the end of loop, canceling all remaining passes Condition is true? Statement continue; Yes! No! continue cancel just the current pass, all remaining passes are unaffected ! Take while loop / for loop as an example: Faster Prime checking using break ! Let’s compare the speed with the prior version by typing 3333333 cout<<"Input an integer"; cin>>num;
bool isPrime=true;
for (i=2; i
bool isPrime=true;
for (i=2; i
Mix up of the comma operator and the semi-colon
wrong: for (sum=0; j=1; j<=10; j++)
Adding semi-colons to unneeded places…
wrong: for (j=1; j<=10; j++); sum += j;
Or omitting semi-colons when we really need them…
wrong: do { cin>>num; } while (num==0)
Incorrect use of relational operators:
wrong: while(x==y==z) while(x>y>z)
should be: while(x==y && y==z) while(x>y && y>z)
Further remarks
26
Avoid using floating point to control loops as there may be small
deviation (e.g. 0.14 is actually 0.1399999999999….)
Infinite loops are possible:
while(1){…} while(true){…} for( ; ; ){…}
Beware of off-by-one error:
for(i=1;i<10;i++) actually runs only 9 times! (not 10!)
for(i=0;i<=10;i++) actually runs 11 times! (not 10!)
Let’s check whether the values of variables are properly set…
int age; int age;
while( age <=0){ do {
cin>>age; cin>>age;
} } while (age<=0); Wrong! Value of age is unknown when it enters while loop! Should use do-while loop here: read at least once before check! Checklist After this lecture, students are expected to be able to: ! Write simple while-loop or for-loop to print numbers in ascending (1..100) or descending (100..1) order ! Explain the meanings of the 3 partitions inside ( ; ; ) of a for-loop ! Explain the difference between while-loop v.s. do-while-loop ! Explain the meanings (and differences) of break and continue ! Rewrite loops from one type to another (e.g change while to for) ! Write different types of nested loops (e.g. for enclose for ) ! Explain why nested for-loop uses different counter variables in the inner and outer loops Appendix: Programming Style - Indentation 28 void main(){ int i; for (i = 0; i < 100; i++) { if (i>3)
cout << i;
}
}
1st level (1 tab)
2nd level (2 tabs)
3rd level (3 tabs)
Programmers should indent by 1 level every time functions,
if clauses or for/while/do-while loops are encountered:
Appendix: Formatting programs in Visual Studio
29
! Let’s indent the code properly to reflect the program structure.
(Let’s indent WHILE you’re writing, not AFTER program completion)
! Improve readability and ease debugging
! In assignment, programming style marks will be allocated for:
! Indentation
! Proper comments
! Meaningful variable names
! To indent in visual studio, you may press the
! You may select multiple lines first and then press
them at the same time
! To move back one level to the left, press