PIC 10A Flow control Ernest Ryu UCLA Mathematics
If statement An if statement conditionally executes a block of code. # include < iostream > using namespace std ; int main () { double d1; cin >> d1; if (d1 <0) { cout << " Error. Negative input!" << endl ; 2
If-else statement An if-else statement conditionally executes one of the alternatives. # include < iostream > using namespace std ; int main () { int n; cin >> n; if (n>0) { cout << " n is positive." << endl ; else { cout << " n is not positive." << endl ; 3
If-else statement An if-else statement can have more than one alternatives. int main () { int n; cin >> n; if (n>0) { cout << " n is positive." << endl ; else if (n<0) { cout << " n is negative." << endl ; else { cout << " n is 0." << endl ; 4
Flow control The programs we had encountered had a linear sequence of instructions. However, real programs may bifurcate, repeat code, and take decisions. Control structures allow programs to follow a more complicated flow. 5
The type bool A Boolean (named after Prof. Boole) is a data type with two possible values: true or false. The type bool represents a Boolean value. bool is a fundamental type. (#include not needed.) A literal of type bool is written as true false No capitals. bool b = true ; cout << b << endl ; The output is 1. 6
Comparison operators The comparison/relational operators are >, >=, <, <=, ==, and!=. When used with integer types or floating-point types, they return a bool. They represent >,, <,, =, and. bool b = ( 454 < 324 ); cout << b << endl ; cout << ( 6.4!= 3.2 ) << endl ; The output is 0 and 1. 7
Comparison operators The comparison operator == is closer to = than the assignment operator =. Never use == (or!=) with floating-point numbers! double d1 = 3./15. ; double d2 =.3 / 1.5 ; cout << ( d1 == d2) << endl ; The output is 0. (Results may vary. Each CPU handles round-off errors slightly differently.) An operator does different things based on what type it is used with. On strings, comparison operators look at the lexicographical order. string s1 = " Alice "; string s2 = " Bob "; cout << ( s1 < s2) << endl ; The output is 1. 8
Comparison operators: warning Do not mix up = and ==. 9
Logical operators The Logical operators are &&,, and!. && = and = conjunction = = or = disjunction =! = not = negation = bool b1 = true ; bool b2 = false ; cout << ( b1 && b2) << endl ; cout << ( b1 b2) << endl ; cout <<! b1 << endl ; The output is 0, 1, and 0. 10
Logical operators: warning Use && and. & and are something else! You can t do int x = 5; cout << ( 4 <= x <= 10) << endl ; (Why?) Instead do int x = 5; cout << ( 4 <= x && x <= 10) << endl ; 11
while loop The while loop while (condition) { code to run loops through the code as long as the condition is true. (Running while the condition is true.) The code runs 0, 1, 2,..., or even infinitely many times. 12
while loop This code prints integers 0, 1,..., n-1. # include < iostream > using namespace std ; int main () { int n, i = 0; cin >> n; while (i < n) { cout << i << endl ; i += 1; The code in the loop executes n times. 13
while loop: example I put $100 in my bank, which gives 4% annual interest. How many years until it becomes $300? int main () { double annual_ interest, current_ money, goal ; int years = 0; cin >> annual_ interest ; cin >> current_ money ; cin >> goal ; while ( current_ money < goal ) { current_ money *= ( 1. + annual_ interest ); years += 1; cout << " You ll reach your goal after "; cout << years << " years " << endl ; 14
Infinite loop An infinite loop is a loop that never ends while ( true ) { cout << " This will never end." << endl ; Infinite loops (mostly) happen by accident. In the interest example, the loop never terminates if the interest is 0.0. 15
Increment/decrement operator The increment/decrement operators are ++ and --. Actually, there are 4 such operators. When x is of type int, ++x pre-increment x++ post-increment --x pre-decrement x-- post-decrement ++x and x++ are similar to x += 1. (Increment the value of x by 1.) --x and x-- are similar to x -= 1. (Decrement the value of x by 1.) ++x and x++ (--x and x--) are slightly different. More on this later. 16
Increment/decrement operator int a = 10; while (a>0) { cout << a << endl ; a - -; Output is 10, 9,..., 1. 17
for loop The for loop for (intialization; condition; update) { code to run executes the initialization, loops through the code as long as the condition is true, and perform the update after each loop. It is similar to initialization while (condition) { code to run update 18
for loop for loops can be slightly cleaner than while loops # include < iostream > using namespace std ; int main () { int n; cin >> n; for ( int i=0; i<n; i ++) { cout << i << endl ; Output is 0, 1,..., n-1. 19
for loop You are running the loop for i equals 0 through n-1. for ( int i=0; i<n; i ++) {... 20
for loop: warning When you get the iteration index of a loop off by one, you commit an off-by-one error. If you wish to print 1, 2,..., n, the program # include < iostream > using namespace std ; int main () { int n; cin >> n; for ( int i=0; i<n; i ++) { cout << i << endl ; has an off-by-one error. The for loop should be for ( int i=1; i <=n; i ++) 21
do-while loop Similar to the while loop, but will run the loop at least once. # include < iostream > # include < string > using namespace std ; int main () { string s; do { cout << " Enter text : "; cin >> s; cout << " You entered : " << s << "\n"; while (s!= " goodbye "); 22
break The break statement exits a loop. string s; while ( true ) { cout << " Enter text : "; cin >> s; if (s == " goodbye ") { break ; cout << " You entered : " << s << "\n"; 23
continue The continue statement skips the remaining part of the loop and continues to the next iteration. for ( int i = 1; i <= 10; ++i) { if ( i==6 i==9 ) { continue ; cout << i << endl ; Sometimes, using continue and break makes the code cleaner. 24
Useful digression: Boolean algebra In Elementary algebra (the algebra you know) you learned things like a + b = b + a a (b + c) = a b + a c. Elementary algebra studies arithmetic on real numbers. Boolean algebra is the study of things like a or b = b or a a and (b or c) = (a and b) or (a and c). Boolean algebra studies logical operations on Booleans. https://en.wikipedia.org/wiki/boolean_algebra 25
Useful digression: Boolean algebra The notation seems intimidating. However, it s not that hard if you think by example. a or b = b or a You must be smart or hardworking. = You must be hardworking or smart. a and (b or c) = (a and b) or (a and c) Your shirt must have long sleeves, and it must be red or green. = Your shirt must be a red long-sleeve or a green long-sleeve. 26
Useful digression: Boolean algebra Useful identities of Boolean algebra. Distributivity of and over or a and (b or c) = (a and b) or (a and c) Distributivity of or over and a or (b and c) = (a or b) and (a or c) 27
Useful digression: Boolean algebra De Morgan s law 1 not (a or b) = (not a) and (not b) This is a club for those who are smart or hard-working. He s not allowed because he s not smart and he lazy. De Morgan s law 2 not (a and b) = (not a) or (not b) To enter this establishment, you must have shoes and a shirt. If you barefoot or shirtless, you re not allowed. Again, this isn t that hard if you think by example. 28
Useful digression: Boolean algebra The truth table of the 3 logical operators is a b a && b a b!a false false false false true false true false true true true false false true false true true true true false 29
Useful digression: Boolean algebra The Venn diagram for a && (b c) b a c The shaded area also represents (a && b) (a && c). 30
Short-circuit evaluation In C++, && and implement short-circuit evaluation; the second bool isn t evaluated if the first bool determines the output. int numer = 4, denom = 0; if ( denom!= 0 && ( numer / denom < 7) ) { cout << " Short - circuit eval example " << endl ; This is also called minimal evaluation and McCarthy evaluation. Short-circuit evaluation is efficient and convenient: the program doesn t spend time evaluating the second expression, and we can take advantage of this feature to make code concise. 31
Why does this work? # include < iostream > # include < string > using namespace std ; int main () { string s; while ( true ) { cout << " Enter text : "; cin >> s; if (s == " goodbye ") break ; cout << " You entered : " << s << "\n"; 32
Why does this work? # include < iostream > using namespace std ; int main () { int n; cin >> n; for ( int i=0; i<n; i ++) for ( int j=0; j<n; j ++) cout << i << ", " << j << endl ; The 2 code snippets are in compliance with the rules for constructing if statements and for loops. What are these precise rules? 33
Why bother with precise syntax? We ll learn some precise syntax. Here s why. Generally, you don t have to know the precise syntax. Even with a vague understanding of the rules, you are capable of writing control structures. In real life, you learn the rules more precisely over time and achieve a more deeper understanding. Nothing wrong about this. There is pedagogical value to learning the precise rules upfront, especially since this is a first course in programming. Programs follow rigid instructions. When you program, the compiler, a program itself, converts your program into an executable. So the syntax of a programming language is a collection of precise and rigid set of rules. 34
Statements A C++ program comprises a series of statements. There are several types: declaration statements string s; int i=0; jump statements break; continue; expression statements compound statements selection statements if and if-else statement iteration statements for, while, and do-while loops 35
Expression statements Roughly speaking, an expression is a line of code that evaluates to something. They are things like i = 4 + j i++ 34.23 cout << "UCLA" << endl b1 && b2 (the empty expression) Terminate an expression with ; to get an expression statement. 36
Null statements The null statement is the empty expression terminated with ; So the following 4 statements string s = " UCLA "; cout << s << endl ;;; are legal. The code will compile. Needless to say, 2 of the 3 expression statements are unnecessary. 37
Useful digression: whitespace in C++ Whitespace is the set of characters like space, tab, and newline. In C++, whitespace mostly mean nothing to the computer. So you could write your program like # include < iostream > using namespace std ; int main (){ int i;cin >>i;cout <<" Good morning. The input However, do use whitespace to make your code human-readable. 38
Compound statements A compound statement compounds multiple statements into one with curly braces. { statement statement... statement 39
if and if-else statement The precise syntax for if and if-else statement are if (expression) statement if (expression) statement else statement So if ( true ) { cout << " output 1" << endl ; cout << " output 2" << endl ; is legal since the block of code within { and compose a single compound statement. 40
if and if-else statement When you only have a single expression statement, { and are unnecessary. if ( true ) cout << " output 1" << endl ; else cout << " output 1" << endl ; is legal. 41
if and if-else statement The 2 statements if (i < n) { cout << i << endl ; ; are legal and will compile. However, the extra null statement suggests that the author doesn t understand the language (in particular about expressions and statements) terribly well. An if statement doesn t need a semicolon at the end! 42
while loop The precise syntax for a while loop is while (expression) statement So while ( true ) cout << " This will never end." << endl ; is a single legal (iteration) statement. 43
for loop The precise syntax for a for loop is for (statement expression; expression) statement So for (; true ; ) cout << " This will never end." << endl ; is a single legal (iteration) statement. 44
for loop The following (legal) program contains 3 statements # include < iostream > using namespace std ; int main () { int n; cin >> n; for ( int i=0; i<n; i ++) for ( int j=0; j<n; j ++) cout << i << ", " << j << endl ; What are the 3 statements? Why is the for loop legal? 45
do-while loop The precise syntax for a do-while loop is do statement while (expression); Unlike the other control structures, the do-while loop does require a semicolon at the end! string s; do { cout << " Enter text : "; cin >> s; cout << " You entered : " << s << "\n"; while (s!= " goodbye "); Without ; the code wouldn t compile. 46
The following code doesn t compile int main () { int i = 5; cout << i << endl ; int i = 10; cout << i << endl ; Why does this work? because you can t declare i a variable twice. However, this works. for ( int i=0; i<5; i ++) cout << i << endl ; for ( int i=5; i>0; i - -) cout << i << endl ; Why? 47
Variable scope The scope of a variable is the part of the code where the variable is available. Throughout a program, variables are created and destroyed. A destroyed variable is inaccessible. A variable (not yet destroyed) may be inaccessible for other reasons. More on this later. 48
Variable scope: compound statements Variables declared within a compound statement go out of scope at the end of the compount statement. int i = 0; { i = 2; int j = 5; cout << i << ", " << j << endl ; cout << i << endl ; cout << j << endl ; This won t compile. By the time the program reaches the last line, j went out of scope. 49
Variable scope: for loop A variable declared within the initialization statement of a for loop is in scope throughout the loop, but not after. for ( int i=0; i <5; i ++) { cout << " For loop is looping " << endl ; cout << i << endl ; cout << i << endl ; This doesn t compile: i is destroyed once the for loop is done. 50
Variable scope: for loop In contrast, the following does compile. int i; for (i=0; i <5; i ++) { cout << " For loop is looping " << endl ; cout << i << endl ; cout << i << endl ; 51
Variable scope It is often good to limit the scope of a variable. More on this later. Usually, you don t want to use generic variable names like i or str. You may later accidentally use it when you mean to create a different variable. It s fine to use the variable name i it within a for loop, as it goes out of scope after the loop. 52