Download presentation
Presentation is loading. Please wait.
1
Miscellaneous Flow Control
2
Part I: basics of conditional statements
If (cond) A; else B;
3
Part II: Alternative ways of writing choice statements --- mostly a syntax problem
If (cond) { A; } else { B; If statement Nested if If-else-if statement Operator ? Selection statement
4
The if Statement Syntax if(Expression)
Action If the Expression is true then execute Action Action is either a single statement or a group of statements within braces Example: absolute value if(value < 0) value = -value; Expression true false Action If (cond) A; If (cond) A; else {};
5
Example: Absolute Value (3rd )
// program to read number & print its absolute value #include <iostream> using namespace std; int main(){ int value; cout << "Enter integer: "; cin >> value; if(value < 0) value = -value; cout << "The absolute value is " << value << endl; return 0; }
6
Example: Sorting Two Numbers
int value1; int value2; int temp; cout << "Enter two integers: "; cin >> value1 >> value2; if(value1 > value2){ temp = value1; value1 = value2; value2 = temp; } cout << "The input in sorted order: " << value1 << " " << value2 << endl;
7
Nested if Statements Nested means that one complete statement is inside another if <condition 1 exists>{ <do A> if <condition 2 exists>{ <do B> if <condition 3 exists>{ <do C> } <do D> <do E> <do F: sleep>
8
Nested if Statements Example: if <it's Tuesday>{
if <it's 9:00 am>{ if <it's raining>{ <bring umbrella> } <go to COMP 104> <call your friends>
9
if-else-if Statements
if <condition 1 exists>{ <do Q> } else if <condition 2 exists>{ <do R> else if <condition 3 exists>{ <do S> else{ <do T> Q R S T
10
if <Tu, or Thur AM>{
<goto COMP 104> } else if <Mon, Wed, or Fri AM>{ <goto MATH 113> else if <1PM or 7PM>{ <eat> else{ <sleep>
11
“Dangling Else” Problem
Problem: Nested if statements can seem ambiguous in their meaning. What is the value of c after the following is executed? int a=-1, b=1, c=1; if(a>0) if(b>0) c = 2; else c = 3;
12
C++ groups a dangling else with the most recent if.
The following indentation shows how C++ would group this example (answer: c=1). int a=-1, b=1, c=1; if(a>0) if(b>0) c = 2; else // dangling else grouped to nearest if c = 3;
13
Use extra braces { } to clarify the intended meaning, even if not necessary.
int a=-1, b=1, c=1; if(a>0){ if(b>0) c = 2; else // parenthesis avoid dangling else c = 3; }
14
Summary on conditional statement
The fundamental If-else statement if, nested if, if-else-if Bool type and boolean expression for a test true/false relational operators (==, <, …) logical operators (&&, ||, !) Full table of operator precedence (c++ technicality) ‘==‘ vs ‘=‘, ‘&&’ vs ‘&’: different!
15
Compact if-else operator: ?
if (condition) { A } else { B (condition) ? A : B; In addition, the expression has a value: larger = (value1>value2) ? Value1 : value2;
16
(low-level) Bitwise operators (be careful!)
& and 61&122-> & > >56 | or 61|122-> > >127 ~ not ~61-> -> ^ xor << left shift >> right shift
17
Selection Often we want to perform a particular action depending on the value of an expression Two ways to do this if-else-if statement if-else statements “glued” together switch statement An advanced construct
18
switch Statement An alternative way of writing nested if-else-if statements for multiple choice. if Exp==constant_1 { action1; } else if Exp==constant_2 { action2; else if … { … else{ actionDefault switch (Expression) { case constant_1: action1; break; case constant_2: action2; break; … case constant_n: actionN; break; default: actionDefault } =
19
Example using if-else-if:
if(score >= 90) cout << "Grade = A" << endl; else if(score >= 80) cout << "Grade = B" << endl; else if(score >= 70) cout << "Grade = C" << endl; else if(score >= 60) cout << "Grade = D" << endl; else cout << "Grade = F" << endl;
20
Example using switch: This version is much easier to understand!
switch(int(score)/10){ case 10: case 9: cout << "Grade = A" << endl; break; case 8: cout << "Grade = B" << endl; case 7: cout << "Grade = C" << endl; case 6: cout << "Grade = D" << endl; default: cout << "Grade = F" << endl; } Logical OR This version is much easier to understand!
21
Another example: int left; int right; char oper;
cout << "Enter simple expression: "; cin >> left >> oper >> right; cout << left << " " << oper << " " << right << " = "; switch (oper) { case '+' : cout << left + right << endl; break; case '-' : cout << left - right << endl; break; case '*' : cout << left * right << endl; break; case '/' : cout << left / right << endl; break; default: cout << "Illegal operation" << endl; }
22
Loops
23
Part I: basics of loops Initialization While (cond) { A; }
24
Part II: loops with ‘break’ and ‘continue’
25
break break is not necessary in well designed programs!!!
break leaves the current loop immediately. It is recommended that break be used for situations where the loop needs to be terminated immediately (e.g., due to user intervention or if a fatal error occurs) break is not necessary in well designed programs!!!
26
while(cond1){ A; if (cond2) continue; B; } while(cond1){ A; if (cond2) break; B; } If cond2 is true, then the loop is finished. If cond2 is true, then skip only B, and the loop continues. !!! break and continue are not necessary in well designed programs, and continue is even less used thant break !!!
27
Example: stop with negative score
int score,sum; number=100; n = 1; sum = 0; cin >> score; while((n <= number) && (score>=0)){ sum=sum+score n=n+1; } cout << sum/number << endl; int score,sum; number=100; n = 1; sum = 0; while(n <= number){ cin >> score; if (score<0) break; sum=sum+score n=n+1; } cout << sum/number << endl;
28
Example: ignore negative score
int score,sum; number=100; n = 1; sum = 0; while(n <= number){ cin >> score; if (score<0) continue; sum=sum+score n=n+1; } cout << sum/number << endl; int score,sum; number=100; n = 1; sum = 0; while(n <= number){ cin >> score; if (score>=0) { sum=sum+score; n=n+1; } cout << sum/number << endl;
29
Tracing a program … int j=0; while(j<3){
cout << j << endl; if (j==1) break; j=j+1; } } int j=0; while(j<3){ cout << j << endl; if (j==1) continue; j=j+1; } }
30
Shorthand forms Very peculiar features of C and C++
31
Shortcut Assignment C++ has a set of operators for applying an
operation to a variable and then storing the result back into the variable Shortcut assignments: *=, /=, +=, -=, %= Examples int i = 3; i += 4; // i = i + 4 cout << i << endl; // i is now 7 double a = 3.2; a *= 2.0; // a = a * 2.0 cout << a << endl; // a is now 6.4 int change = 1265; change %= 100; // change = change % 100 cout << change << endl; // change is now 65
32
Count += 2; Total -= discount; Bonus *= 2; Time /= rushfactor; Change %= 100; Amount *= c1 + c2; Count = Count + 2; Total = Total - discount; Bonus = Bonus*2; Time = Time*rushfactor; Change = Change % 100; Amount = Amount*(c1 + c2);
33
Cascading assignments
It’s possible, but may not be clear, to do: int w,x,y,z; y = z = 5; y = (z = 5); w = x = y + z; w = (x = (y+z)); Not recommended at all !!!
34
Increment and Decrement
C++ has special operators for incrementing or decrementing an object by one Examples int k = 4; ++k; // k=k+1 : k is 5 k++; // k=k+1 : k is 6 cout << k << endl; int i = k++; // i is 6, k is 7 cout << i << " " << k << endl; int j = ++k; // j is 8, k is 8 cout << j << " " << k << endl;
35
What is the difference between k++ and ++k?
++k increments first, and the incremented value is used in the expression (1+k in place value) k++ uses the initial value of k in the expression, and increments afterwards (k in place value) Examples int a, b, c, d, k; k = 3; a = ++k; // k=4, a=4 b = --a; // a=3, b=3 c = b++; // c=3, b=4 d = c--; // d=3, c=2
36
a = k++; a = ++k; a = k; k = k+1; = k = k+1 ; a = k; =
37
N! (while, shorthand) int number, factorial, n;
cout << "Enter number: "; cin >> number; factorial = 1; n = 1; while(n <= number){ factorial *= n; n++; } cout << "The factorial of " << number << " is " << factorial << endl;
38
2N (while, shorthand) int number, result, n;
cout << "Enter number: "; cin >> number; result = 1; n = 1; while(n <= number){ result *= 2; n++; } cout << "Two raised to the " << number << " power is " << result << endl;
39
Part II: Alternative ways of writing loops
For-statement Do-while statement (Break )
40
The for Statement Init; while (Expression) { Action; update; } Syntax
for (Init; Expression; Update) { Action; } How it works: Execute Init statement While Expression is true Execute Action Execute Update Example int i; for(i=1; i<=20; i=i+1) cout << "i is " << i << endl; Init; while (Expression) { Action; update; }
41
Iteration Using the for Statement
ForInit ForExpression true false Action PostExpression (update)
42
= for loop summary: a compact form of while loop!
for (init(x); expression(x); update(x)) action(x,V) Init(x); while (expression(x)) { action(x,V); update(x); } =
43
N! (for) int number, factorial, n; cout << "Enter number: ";
cin >> number; factorial = 1; for(n=1; n<=number; n=n+1) factorial = factorial*n; cout << "The factorial of " << number << " is " << factorial << endl;
44
2N (for) int number, result, n; cout << "Enter number: ";
cin >> number; result = 1; for(n=1; n<=number; n=n+1) result = result*2; cout << "Two raised to the " << number << " power is " << result << endl;
45
The Do-While Statement
Syntax do Action while (Expression) How it works: Execute Action if Expression is true then execute Action again Repeat this process until Expression evaluates to false Action is either a single statement or a group of statements within braces Action true Expression false
46
= do-while loop: init(V); do action(V); while (expression(V));
Difference is here!!! init(V); do action(V); while (expression(V)); Init(V); action(V); while (expression(V)) { } =
47
Example: N! (do-while) int number, factorial, n;
cout << "Enter number: "; cin >> number; factorial = 1; n = 1; do{ factorial = factorial*n; n=n+1; }while(n <= number); cout << "The factorial of " << number << " is " << factorial << endl; (when input number is 0, the behavior is different from the while loop! ‘while’ loop is better than ‘do-while’ for this example)
48
Example: 2N (do-while) int number, result, n;
cout << "Enter number: "; cin >> number; result = 1; n = 1; do{ if(number != 0) result = result*2; n=n+1; }while (n <= number); cout << "Two raised to the " << number << " power is " << result << endl; (‘while’ loop is better than ‘do-while’ for this example!)
49
Waiting for a Reply (‘do-while’ is better than ‘while’ here!)
char reply; cout << "Continue(y/n): "; cin >> reply; while(reply!='n') { //do something } char reply; do{ //do something cout << "Continue(y/n): "; cin >> reply; }while(reply!='n'); (‘do-while’ is better than ‘while’ here!)
50
Summary with Maximum example
Three loop statements: while, for, do-while One more example: Maximum The user is to input a sequence of positive integer values from the keyboard. The end of the sequence is marked as the integer value –1. Write a programme which computes the maximum of the given sequence of integer values.
51
Maximum (while) MAX int value=0; //input value
cin >> value; Max = value; must initialise ‘value’ int value=0; //input value int max=0; //maximum value while (value != -1) { cout << "Enter a value (-1 to stop): "; cin >> value; if(value > max) max = value; } cout << "The maximum value found" << " is " << max << endl; MAX
52
Maximum (do-while) int value; //input value int max=0; //maximum value
No need to initialize ‘value’ int value; //input value int max=0; //maximum value do{ cout << "Enter a value (-1 to stop): "; cin >> value; if(value > max) max = value; } while (value!=-1); cout << "The maximum value found is " << " is " << max << endl; ‘do-while’ is slightly better than ‘while’ for this example!
53
Maximum (for) ‘for’ loop is not suitable for this example!
54
Which Loop to Use? While loop --- the fundamental one, always think it first! You want to repeat an action without knowing exactly how many times it will be repeated. You are working with user input There are situations when the action should not be executed. For loop Usually best for sums, products, and counting loops. Do-while loop The action should always be executed at least once. Otherwise, the do-while loops and while loops are used in similar situations.
55
Print out the following triangular pattern *
* * * * * * * * * * * * * * * * * * * * * * * *
56
print triangular pattern: row=1; while(row<=5) { print-spaces;
print-stars; row++; } print spaces: space=1; while(space<=5-row) { cout << “ “; space++; } print stars: star=1; while(star<=2*row-1) { cout << “*”; star++;
57
row=1; while(row<=5) { // print spaces space=1; while(space<=5-row) { cout << “ “; space++; } // print stars star=1; while(star<=2*row-1) { cout << “*”; star++; cout << endl; row++; for(row=1; row<=5; row++){ for(space=1; space<=5-row; space++) cout << " "; for(star=1; star<=2*row-1; star++) cout << "*"; cout << endl ; }
58
Example: Write a function void staircase(int n) to print a "staircase" on the screen with n steps. We assume that n is always greater than 0. For example, if n is 1, the output should be: +-+ | | If n is 4, it should be: | +-+ | | | +-+ | | | | |
59
void print-first-row(int i)
{ if (i == 0) { print +-+ } else { print 2*i-1 spaces void print-second-row(int i) print | print 2*i+1 spaces void StairCase(int n) { int i = 0; while (i < n) print-first-row(i); print-second-row(i); i++; } print-last-row;
60
void StairCase(int n) { char SPACE = ' '; char STROKE = '|'; char PLUS = '+'; char HYPEN = '-'; int i = 0; while (i < n) if (i != 0) print_one_row(STROKE, SPACE, SPACE, 2*i-2); cout << "+-+" << endl; print_one_row(STROKE, SPACE, STROKE, 2*i+1); cout << endl; i++; } print_one_row(PLUS, HYPEN, PLUS, 2*n-1); void print_one_row(char start_symbol, char mid_symbol, char end_symbol, int length) { cout << start_symbol; int j = 0; while (j < length) cout << mid_symbol; ++j; } cout << end_symbol;
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.