SYSC 2006: Imperative Programming Lecture 3 - Flow of Control (Carleton University)

Summary

This document contains lecture notes for SYSC 2006: Foundations of Imperative Programming, Lecture 3: Flow of Control, taught at Carleton University. Topics covered include a summary of previous lectures, examples of flow of control structures (conditionals and loops), in C and Python. This document also provides examples and explanations of conditional statements (if/else, switch/case).

Full Transcript

Copyright © 2024 1 Department of Systems and Computer Engineering, Carleton University SYSC 2006: Foundations of Imperative Programming Lecture 3: Flow of Control 2 Previous Lecture Su...

Copyright © 2024 1 Department of Systems and Computer Engineering, Carleton University SYSC 2006: Foundations of Imperative Programming Lecture 3: Flow of Control 2 Previous Lecture Summary ❑Become familiar with basic C syntax and variables ❑Explain and properly use basic C data types ❑Distinguish between static and dynamic typing in programming languages ❑Use C operators to write expressions to implement C programs ❑Understand how operators’ precedence affects the execution of expressions Be able to apply the previous concepts to write programs in C 3 Objectives ❑Use flow of control expressions (conditionals and loops) to write C programs 4 Control Structures 5 Control Flow Flow of control: order in which the statements in an imperative program are executed Imperative programming languages provide control structures that choose the statements that are executed The execution "path" through the code is altered based on whether a programmer-defined condition evaluates to true or false if; if-else; in Python if; if-else; in C 6 Conditional Statement if (condition) if (condition) then if (condition) then then consequent consequent consequent else else if (condition) then end alternative alternative 1 end else alternative 2 end Alternative blocks are not mandatory Normal flow of execution continues after end Can nest as many conditions as needed C Python 7 Conditional if (expression) { if expression: Statement } statements; statements C syntax if (expression) { if expression: Condition must be in statements; statements parenthesis } else { else: statements; statements Curly brackets are } mandatory ONLY if more than one statement if (expr1) { if expr1: statements; statements Indentation is optional. Not } else if (expr2) { elif expr2: doing it is a poor coding statements; statements style } else { else: No elif keyword statements; statements } 8 Conditional Statement (Switch/Case) The “if/else if/else” control structure group is the most generic of all available However, this means that simple tasks can become quite cumbersome Example: Different operations based on whether a variable was equal to 1, 2, 3 or anything else Conditional if/else if/else Switch/Case 9 Statement (Switch/Case) if (myVar == 10) { switch(myVar){... case 10: The code that needs to be }... executed goes after the else if (myVar == 2) { break; colon (:) and before the... case 2: break; }... else if (myVar == 13) { break; The break statement is... case 13: used to stop execution }... within the switch statement else { break; and exit the scope of the... default: switch }... } The default is equivalent to the else in if-statement 10 Conditional Statement (Switch/Case) What if you forget or decide not to include the break statement? No compilation error If you forgot… Unexpected behavior Can also be a design decision… but… not a good practice 11 Conditional Statement (Switch/Case) #include int main(void) { char section = 'A'; switch (section) { What will happen in case 'A' : this case? printf("You are in SYSC2006A"); case 'B' : Why is it wrong? printf("You are in SYSC2006B"); break; case 'C' : printf("You are in SYSC2006C"); break; default: printf("Enjoy the weekend"); } return 0; } 12 Conditional Statement (Switch/Case) Will switch/case work with floats? No: The switch expression must be an integer or character constant. You cannot use float, double, or other data types in the switch expression. 13 Conditional Statement (Ternary Operator : ?) It is essentially a short implementation of a simple if/else “If this condition is true, do this, otherwise do that” Syntax: variable = (condition) ? (value if true) : (value if false); Example 1: int x = 10; int y = (x > 5) ? -4 : 8; // y will be -4 as x > 5 This is the same as: 14 Conditional Statement (Ternary Operator : ?) Example 1: int x = 10; int y; if (x > 5) { y = -4; } else { y = 8; } 15 Conditional Statement (Ternary Operator : ?) Example 2: int x = 10, y = -4; int z = (x < 0) ? 8 : (y < 0) ? abs(y) : y; // z will be 4 This is the same as: int x = 10, y = -4, z; if (x < 0) { z = 8; } else if (y < 0) { z = abs(y); } else { z = y; } 16 Loops Block of statements (the loop body) is specified once, but may be executed multiple times Imperative programming languages may provide more than one type of loop control structure as per the pseudo code on this slide and the next: Counter loops: block repeated a certain nu mber of times for i = 1 to n begin block ECOR1041 – Python! end Not supported in C! Collection-controlled loops: iterates over all elements in a collection foreach elem in collection begin block end 17 Loops Block of statements (the loop body) is specified once, but may be executed multiple times Imperative programming languages may provide more than one type of loop control structure Condition-controlled loops: While: block executed as long as condition evaluates to True while (condition) begin block end Do-while: block executed once, and then as long as condition evaluates to True do begin block while (condition) 18 While Loops C Python while (expression) { while expression: statements; statements } else C syntax statements Condition must be in parenthesis https://www.pythontutori Curly brackets are mandatory ONLY if more than one al.net/python- basics/python-while-else/ statement Indentation is optional. Not indenting is a poor coding style No else clause available 19 Do-While Loops C Python do { Not supported statements; } while (expression); C syntax Condition must be in parenthesis Curly brackets (braces) are mandatory ONLY if more than one statement Indentation is optional. Not doing it is a poor coding style 20 For Loops C Python for (init ; cond; update) { for expression: statements; statements else } statements C syntax init – used to set up the variable(s) used in the loop with an initial value; called once when entering the “for” loop cond – condition that will permit the loop to exit and checks the variables included; checked at the beginning of the loop and after the update expression is executed update – used to update the variable(s); executed at the end of each iteration of the loop Curly brackets are mandatory ONLY if more than one statement https://www.pythontut Indentation is optional. Not indenting is a poor coding style orial.net/python- No else clause available basics/python-for-else/ 21 For Loops in C for (expr1; expr2; expr3) { for (int i = 0; i < n; i++) { statements; statements; } } is a concise way of writing: is a concise way of writing: expr1; int i = 0; while (expr2) { while (i < n) { statements; statements; expr3; i += 1; } } C 22 For Loops in C for (init ; cond; update) { statements; } init, cond, update are not mandatory for( ; i < 10 ; ) { … } is valid Assumes that variable i is initialized outside the for loop The variable i must be updated inside the for loop What happens if we forget to update i? C 23 For Loops in C for ( init ; cond; update) { statements; } each of the expressions can have complex statements: multiple initialized variables (separated by commas) multiple conditions multiple increments (separated by commas) Example: for (int i = 0, j = 10; i < 10 && j > 5; j--, i++){... } C 24 For Loops in C for ( init ; cond; update) { statements; } If a variable (i.e. i) is declared in the init part of the for loop, it will be only accessible within the scope of the for loop. Ok as i is inside Example: the scope of the for loop for (int i = 0; i < 10; i++){ i += 1; } Produces identifier "i" is undefined error. i = 10; As i is outside the scope of the for loop 25 PRACTICE Discount Customer age A product cost is discounted based on Percentage the age of the customers. For No less than 18 years example, if a customer's age is 60 discount years, the customer gets a discount Between 18 (included) worth 16% of the product price (See and 40 (not included) 5% the table). years old Write a program that prints the value Between 40 and 60 13% of the discount in dollars. years old For now, assume two variables inside Between 60 and 80 16% your program with hard-coded values: years old customer age 80 or more years old 20% product price 26 Recap Learning Outcomes ❑Use flow of control expressions (conditionals and loops) to write C programs Copyright © 2024 27 Department of Systems and Computer Engineering, Carleton University SYSC 2006: Foundations of Imperative Programming Lecture 3: Flow of Control

Use Quizgecko on...
Browser
Browser