Miscellaneous Flow Control

Slides:



Advertisements
Similar presentations
Dr. Yang, QingXiong (with slides borrowed from Dr. Yuen, Joe) LT3: Conditional Statements CS2311 Computer Programming.
Advertisements

Dr. Yang, Qingxiong (with slides borrowed from Dr. Yuen, Joe) LT4: Control Flow - Loop CS2311 Computer Programming.
If Statements & Relational Operators Programming.
While Loops Programming. COMP102 Prog Fundamentals I: while Loops/Slide 2 Shortcut Assignments l C++ has a set of shortcut operators for applying an operation.
True or false A variable of type char can hold the value 301. ( F )
Computer Science 1620 Loops.
1 Engineering Problem Solving With C++ An Object Based Approach Chapter 3 Control Structures.
Slide 1 Summary Two basic concepts: variables and assignments Some C++ practical issues: division rule, operator precedence  Sequential structure of a.
Programming Switch command. COMP102 Prog. Fundamentals: Switch command / Slide 2 Multiple Selection: The switch Statement value1 action 1 value2 action.
Iteration This week we will learn how to use iteration in C++ Iteration is the repetition of a statement or block of statements in a program. C++ has three.
Loops. COMP104 Loops / Slide 2 Shortcut Assignment * C++ has a set of operators for applying an operation to a variable and then storing the result back.
Chapter 5: Control Structures II (Repetition)
If Statements. COMP104 If / Slide 2 Three Program Structures * Sequence - executable statements which the computer processes in the given order * Choice.
Summary of Loops Programming. COMP102 Prog Fundamentals I: Summary of Loops /Slide 2 Which Loop to Use? l for loop n for calculations that are repeated.
Loops Programming. COMP104 Lecture 9 / Slide 2 Shortcut Assignment l C++ has a set of operators for applying an operation to a variable and then storing.
For Loops Programming. COMP102 Prog Fundamentals I: for Loops/Slide 2 The for Statement condition action true false initialization update.
Section 3 - Selection and Repetition Constructs. Control Structures 1. Sequence 2. Selection 3. Repetition.
Lecture 3.1 Operators and Expressions Structured Programming Instructor: Prof. K. T. Tsang 1.
Department of Computer Science and Engineering, HKUST 1 HKUST Summer Programming Course 2008 C++ Control Statements ~ Selection and Iteration.
Chapter 4: Looping. Resource: Starting Out with C++, Third Edition, Tony Gaddis 5.1 The Increment and Decrement Operators ++ and -- are operators that.
More on Input Output Input Stream : A sequence of characters from an input device (like the keyboard) to the computer (the program running). Output Stream.
Dr. Yang, QingXiong (with slides borrowed from Dr. Yuen, Joe) LT3: Conditional Statements CS2311 Computer Programming.
Basic Of Computer Science
CONTROLLING PROGRAM FLOW
Chapter 4 Loops Write code that prints out the numbers Very often, we want to repeat a (group of) statement(s). In C++, we have 3 major ways of.
Chapter 5 Loops. Overview u Loop Statement Syntax  Loop Statement Structure: while, for, do-while u Count-Controlled Loops u Nested Loops u Loop Testing.
Lecture 4 Looping. Building on the foundation Now that we know a little about  cout  cin  math operators  boolean operators  making decisions using.
Control Structures II (Repetition). Objectives In this chapter you will: Learn about repetition (looping) control structures Explore how to construct.
While Loops Programming. COMP102 Prog Fundamentals I: while Loops/Slide 2 Shortcut Assignments l C++ has a set of shortcut operators for applying an operation.
COMPUTER PROGRAMMING. Iteration structures (loops) There may be a situation when you need to execute a block of code several number of times. In general,
Program Flow Control - Looping Addis Ababa Institute of Technology Yared Semu April 2012.
1 COMS 261 Computer Science I Title: C++ Fundamentals Date: September 21, 2005 Lecture Number: 10.
Chapter 05 (Part III) Control Statements: Part II.
1 ELEC 206 Chapter 3 Control Structures 5-Step Problem Solving Methodology 1. State the problem clearly. 2. Describe the input and output. 3. Work a.
1 Compound Assignment C++ has a large set of operators for applying an operation to an object and then storing the result back into the object Examples.
Chapter 7 Selection Dept of Computer Engineering Khon Kaen University.
1 Chapter 4, Part 1 If Control Construct A mechanism for deciding whether an action should be taken JPC and JWD © 2002 McGraw-Hill, Inc. Modified by S.
Control Structures RepetitionorIterationorLooping Part I.
Introduction to Loops Iteration Repetition Counting Loops Also known as.
Loops cause a section of a program to be repeated a certain number of times. The repetition continues while a condition remains true. When a condition.
REPETITION STATEMENTS - Part2 Structuring Input Loops Counter-Controlled Repetition Structure Sentinel-Controlled Repetition Structure eof()-Controlled.
If Statements Programming. COMP104 Lecture 7 / Slide 2 Review: Rules for Division l C++ treats integers different than doubles. 100 is an int. l 100.0,
Lecture 3.1 Operators and Expressions Structured Programming Instructor: Prof. K. T. Tsang 1.
1 Chapter 4 - Control Statements: Part 1 Outline 4.1 Introduction 4.4 Control Structures 4.5 if Selection Structure 4.6 if/else Selection Structure 4.7.
Branching statements.
Chapter 3 Selection Statements
Programming Loops (continued).
Review 1.
REPETITION CONTROL STRUCTURE
CHAPTER 4 REPETITION CONTROL STRUCTURE / LOOPING
A mechanism for deciding whether an action should be taken
Engineering Problem Solving with C++, Etter/Ingber
Chapter 2.2 Control Structures (Iteration)
Control Structures Combine individual statements into a single logical unit with one entry point and one exit point. Used to regulate the flow of execution.
Programming Fundamentals
JavaScript: Control Statements.
Control Structures - Repetition
Control Structures Combine individual statements into a single logical unit with one entry point and one exit point. Used to regulate the flow of execution.
TOPIC 4: REPETITION CONTROL STRUCTURE
COMS 261 Computer Science I
Compound Assignment Operators in C++
Additional Control Structures
Loops (iterations, repetitions)
Chapter 7 Additional Control Structures
Chapter 2.2 Control Structures (Iteration)
Summary Two basic concepts: variables and assignments Basic types:
Computing Fundamentals
Chapter 4: Control Structures I (Selection)
2.6 The if/else Selection Structure
Chap 7. Advanced Control Statements in Java
Presentation transcript:

Miscellaneous Flow Control

Part I: basics of conditional statements If (cond) A; else B;

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

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 {};

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; }

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;

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>

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>

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

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>

“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;

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;

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; }

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!

Compact if-else operator: ? if (condition) { A } else { B (condition) ? A : B; In addition, the expression has a value: larger = (value1>value2) ? Value1 : value2;

(low-level) Bitwise operators (be careful!) & and 61&122->00111101&01111010->01111111->56 | or 61|122-> ->01111111->127 ~ not ~61-> ->11000010 ^ xor << left shift >> right shift

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

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 } =

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;

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!

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; }

Loops

Part I: basics of loops Initialization While (cond) { A; }

Part II: loops with ‘break’ and ‘continue’

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!!!

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 !!!

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;

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;

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; } }

Shorthand forms Very peculiar features of C and C++ 

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

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);

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 !!!

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;

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

a = k++; a = ++k; a = k; k = k+1; = k = k+1 ; a = k; =

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;

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;

Part II: Alternative ways of writing loops For-statement Do-while statement (Break )

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; }

Iteration Using the for Statement ForInit ForExpression true false Action PostExpression (update)

= 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); } =

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;

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;

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

= 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)) { } =

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)

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!)

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!)

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.

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

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!

Maximum (for) ‘for’ loop is not suitable for this example!

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.

Print out the following triangular pattern * * * * * * * * * * * * * * * * * * * * * * * * *

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++;

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 ; }

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: | +-+ | | | +-+ | | | +-+ | | +-------+

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;

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;