Conditinoal Constructs Review
Conditinoal Constructs Review
1
Iterative Constructs
3
The while Statement
syntax
while (expression)
body
semantics expression
if expression is true then execute body
4
while (n != 0 ) { cin >> n; if (n > max) max = n; }
5
The for Statement initStatement
syntax
for(initStatement;
expression; postStatement)
body
false
expression
semantics
execute initStatement
evaluate expression, if true: iterate true
iteration:
body
– execute body
– execute postStatement
– repeat expression evaluation
postStatement
example
for (int i = 0; i < 20; ++i)
cout << "i is " << i << endl;
loop variable - declared inside for
its scope is body of the loop
modifying loop variable inside body is poor style, use while instead
6
Iterate and Keep Track Idiom
what is idiom again?
often need to iterate while keep track of some value across iterations – maximum
value found, sum, if all positive, etc.
idiom
before loop, declare tracking variable to keep track, initialize it
7
Break and Continue with
Iterative Constructs
break - exits innermost loop
int sum=0;
while(sum < 100) {
int i; cin >> i;
if (i< 0) {
cout << ”found negative number\n”;
break;
}
sum +=i;
}
avoid break with loops as they make code less readable (makes regular loop exit
unnecessary): first try to code loop without it
continue - skip the remaining statements and start a new iteration (evaluate
expression)
int sum=0;
for (int i = 0; i < 20; ++i) {
int intVar; cin >> intVar;
if(intVar < 0) continue;
sum +=i;
} 8
Nesting of Iterative Constructs
iterative constructs can be nested: one iterative construct may be inside
the body of another
example:
for (int i = 0; i < 10; ++i) // outer loop
for (int j = 0; j < 10; ++j) // inner loop
cout << i << j << endl;
what would this code output?
note, no need for curly brackets