Topics covered Information Science 1 Fundamental Programming Constructs (1) Week 11 Terms and concepts from Week 10 Flow of control and conditional statements Selection structures if statement switch statement counter-controlled loops event (sentinel) -controlled loops College of Information Science and Engineering Ritsumeikan University Repetition structures Quiz Recall Week 10 Boolean logic, algebra, variables, expressions Relational and logic operators Logical NOT, negation Logical OR, Boolean sum, disjunction Logical AND, Boolean product, conjunction Truth table De Morgan s laws Class objectives Learn about selection structures in high-level programming languages Learn about repetition structures in high-level programming languages Flow of control Unless specified otherwise, the order of statement execution through a method is linear: one statement after another in sequence To change this order, there are, however, special programming constructs conditional statements which allow us to: decide whether or not to execute a particular statement, or execute a statement over and over, repetitively These statements are based on Boolean expressions that evaluate to either true or false The (overall) order of statement execution in an algorithm is called the flow of control Two-way selection The most basic selection structure is the if conditional statement that has the following format: if ( condition ) clauseif; clauseelse; Previous Statements Yes Is No condition true? Execute rest of program Execute clauseif Execute clauseelse
if syntax The condition is interpreted as a boolean expression (i.e. is evaluated to TRUE or FALSE), and it must be enclosed in parentheses No semicolon is required after the condition parenthesis, but clauseif and clauseelse may require them The condition can have a side effect (i.e. change a variable s value) clauseif and clauseelse can be any expression, even another if statement clauseif and clauseelse can each only be one statement, but it may be a compound statement or block is optional Bugs in condition Nested if statements The statements executed as a result of clauseif and clauseelse could be other if statements These are called nested if statements A clauseelse is optional, but it is always matched to the last unmatched if Nested if statements are most useful when you are categorizing something, e.g. student grades: if (90 <= numbergrade) lettergrade = A+ ; if (80 <= numbergrade) lettergrade = A ; if (70 <= numbergrade) lettergrade = B ; if (60 <= numbergrade) lettergrade = C ; lettergrade = F ; Indentation Since is optional, nested if statements can be confusing, e.g. if (testa) if (testb) if (testc) print( abc ); print( now what? ); Despite indentation, belongs to if (testc) because when evaluated, an will always be paired to the closest if The clause controlled by the if statements is usually indented by the programmer. The use of a consistent indentation style makes a program easier to read and understand, e.g. if ((1 <= value) && (value <= MAX)) anothervalue = value; anothervalue = MAX/2; Or the same source code but indented: if ((1 <= value) && (value <= MAX)) anothervalue = value; anothervalue = MAX/2; Bugs in a nested if Note that you should never check if a boolean variable is true (or false) in the following way: if (myboolean == TRUE) Indeed, think what happens if you mistyped and instead wrote: if (myboolean = TRUE) Statements with the relational equality operator == are a huge source of bugs! Therefore, you should simply write: if (myboolean) Remember that indentation (white space) is for the human reader, but is ignored by the computer Multiple choice if provides the most general way to make choices in a program. Another way is using the switch statement that is a very special form of nested if switch is used when a discrete variable of type char or int (or other integer-compatible type) specifies what should be done, and it has the following format: switch (selector){ statements_1; case CONSTANT_1: case CONSTANT_2: statements_2; break; case CONSTANT_n: statements_n; default: statements_d;
switch syntax Selector should not be a boolean value, a floating point value, or other complex data types The CONSTANTs must be constants, and not variables! No two case labels can have the same CONSTANT For a given case label (i.e. CONSTANT), one or more statements can be sequentially executed statements can include a special statement break that transfers control to outside the switch statement The default label is optional it is equivalent to. Only one default is allowed, and it can go anywhere (good to place it at the end) Repetition structures Initialization that sets values which need to be set before the repetition begins, Test condition that sets the repetition to continue if the condition is true, and Update that updates the test condition to see whether to continue the repetition Loop classification In general, loops can be classified in one of two categories: Counter-Controlled Loops are used when we need to perform an action a particular number of time consists of initializing, testing, and updating a counter the number of iterations may or may not be constant Event (or sentinel) -Controlled Loops are used when actions should be performed until a particular event occurs or a particular state is reached The while statement Infinite loops The body of a loop should eventually make the condition false. If not, it is called an infinite loop, which will execute forever, or until the user interrupts the program This is one of the most common logical errors. E.g. consider the following loop: int counter = 1; while ( counter <= 10 ) { Print counter; We forgot counter++ and this loop would run forever Repetition structures allow us to execute a statement multiple times. Similar to selection structures, they are based on Boolean expressions conditions Repetition structures are often called loops: groups of instructions a computer executes repeatedly while some conditions remain true Thus, there are three parts of a loop: A while statement has the following format: while(condition) If the condition is true, the statement is executed Then the condition is evaluated again, and if it is still true, the statement is executed again The statement is executed repeatedly until the condition becomes false The statement will, thus, be executed zero or more times It is the most basic repetition structure Nested loops Similar to nested if statements, loops can be nested as well the body of a loop can contain another loop For each iteration of the outer loop, the inner loop iterates completely Example: What is the value of count3 after execution of the following code? int count1 = count2 = count3 = 1; while (count1 <= 10) //Outer loop { while (count2 <= 20) //Inner loop { count3++; count2++; count1++;count2=1;
The do/while statement A do/while statement has the following format: do while(condition) The statement is executed once initially, and then the condition is evaluated The statement will, thus, be executed at least 1 time The statement is executed repeatedly until the condition becomes false (i.e. remains true) The for statement A for statement has the following format: for(initialization; condition; increment) Each expression in the header of a for loop is optional: If the initialization is missed, no initialization is performed If the condition is missed, it is always considered to be true, and therefore creates an infinite loop If the increment is missed, no increment operation is performed (which may cause an infinite loop) You can even miss them all: for( ; ; ) Event-controlled loops An example (a class-averaging algorithm in pseudocode) with sentinel-controlled repetition: Summary Initialize total to zero Initialize counter to zero Input the first grade (possibly the sentinel) While the user has not as yet entered the sentinel { Add this grade into the running total Add one to the grade counter Input the next grade (possibly the sentinel) If the counter is not equal to zero { Set the average to the total divided by the counter Print the average Print No grades were entered Concepts you need to know after this class Flow of control Selection statements Repetition statements (including event-controlled) Indentation All programs can be broken down into 3 structures: Sequence: handled automatically by compiler Selection: if or switch Repetition: while, do/while or for The structures can only be combined in 2 ways: Sequencing Nesting Any selection can be rewritten as an if statement, and any repetition can be rewritten as a while statement Homework Read these slides again Do the self-preparation assignments Learn the vocabulary Consult, whenever necessary, the textbook materials
Fundamental Programming Constructs (2) Structural decomposition Program models and parameter passing Next class Quiz 05 Write your name (in English), student ID number, and solve the following problems (write only answers):