Information Science 1 Fundamental Programming Constructs (1) Week 11 College of Information Science and Engineering Ritsumeikan University
Topics covered l Terms and concepts from Week 10 l Flow of control and conditional statements l Selection structures if else statement switch statement l Repetition structures counter-controlled loops event (sentinel) -controlled loops l Quiz 2
Recall Week 10 l Boolean logic, algebra, variables, expressions l Relational and logic operators l Logical NOT, negation l Logical OR, Boolean sum, disjunction l Logical AND, Boolean product, conjunction l Truth table l De Morgan s laws 3
Class objectives l Learn about selection structures in high-level programming languages l Learn about repetition structures in high-level programming languages 4
Flow of control l Unless specified otherwise, the order of statement execution through a method is linear: one statement after another in sequence l 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 l These statements are based on Boolean expressions that evaluate to either true or false l The (overall) order of statement execution in an algorithm is called the flow of control 5
Two-way selection l The most basic selection structure is the if else conditional statement that has the following format: if ( condition ) clauseif; else clauseelse; Previous Statements Yes Is condition true? No Execute rest of program Execute clauseif Execute clauseelse 6
if else syntax l The condition is interpreted as a boolean expression (i.e. is evaluated to TRUE or FALSE), and it must be enclosed in parentheses l No semicolon is required after the condition parenthesis, but clauseif and clauseelse may require them l The condition can have a side effect (i.e. change a variable s value) l clauseif and clauseelse can be any expression, even another if else statement l clauseif and clauseelse can each only be one statement, but it may be a compound statement or block l else is optional 7
Bugs in condition l Note that you should never check if a boolean variable is true (or false) in the following way: if (myboolean == TRUE) l Indeed, think what happens if you mistyped and instead wrote: if (myboolean = TRUE) l Statements with the relational equality operator == are a huge source of bugs! l Therefore, you should simply write: if (myboolean) 8
Nested if else statements l l l l The statements executed as a result of clauseif and clauseelse could be other if else statements These are called nested if else statements A clauseelse is optional, but it is always matched to the last unmatched if Nested if else statements are most useful when you are categorizing something, e.g. student grades: if (90 <= numbergrade) lettergrade = A+ ; else if (80 <= numbergrade) lettergrade = A ; else if (70 <= numbergrade) lettergrade = B ; else if (60 <= numbergrade) lettergrade = C ; else lettergrade = F ; 9
Nested if else statements l l l l The statements executed as a result of clauseif and clauseelse could be other if else statements These are called nested if else statements A clauseelse is optional, but it is always matched to the last unmatched if Nested if else statements are most useful when you are categorizing something, e.g. student grades: if (90 <= numbergrade) lettergrade = A+ ; else if (80 <= numbergrade) lettergrade = A ; else if (70 <= numbergrade) lettergrade = B ; else if (60 <= numbergrade) lettergrade = C ; else lettergrade = F ; 10
Indentation l The clause controlled by the if else 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; else anothervalue = MAX/2; Or the same source code but indented: if ((1 <= value) && (value <= MAX)) anothervalue = value; else anothervalue = MAX/2; l Remember that indentation (white space) is for the human reader, but is ignored by the computer 11
Bugs in a nested if else l Since else is optional, nested if else statements can be confusing, e.g. if (testa) if (testb) if (testc) else print( abc ); print( now what? ); l Despite indentation, else belongs to if (testc) because when evaluated, an else will always be paired to the closest if 12
Multiple choice l l if else 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 else 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){ case CONSTANT_1: statements_1; } case CONSTANT_2: statements_2; break; case CONSTANT_n: statements_n; default: statements_d; 13
switch syntax l Selector should not be a boolean value, a floating point value, or other complex data types l The CONSTANTs must be constants, and not variables! l No two case labels can have the same CONSTANT l For a given case label (i.e. CONSTANT), one or more statements can be sequentially executed l statements can include a special statement break that transfers control to outside the switch statement l The default label is optional it is equivalent to else. Only one default is allowed, and it can go anywhere (good to place it at the end) 14
Repetition structures l Repetition structures allow us to execute a statement multiple times. Similar to selection structures, they are based on Boolean expressions conditions l Repetition structures are often called loops: groups of instructions a computer executes repeatedly while some conditions remain true l Thus, there are three parts of a loop: 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 15
Loop classification l 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 16
The while statement l A while statement has the following format: while(condition) statement; l If the condition is true, the statement is executed l Then the condition is evaluated again, and if it is still true, the statement is executed again l The statement is executed repeatedly until the condition becomes false l The statement will, thus, be executed zero or more times l It is the most basic repetition structure 17
Infinite loops l 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 l This is one of the most common logical errors. E.g. consider the following loop: int counter = 1; while ( counter <= 10 ) { Print counter; } l We forgot counter++ and this loop would run forever 18
Nested loops l Similar to nested if else statements, loops can be nested as well the body of a loop can contain another loop l For each iteration of the outer loop, the inner loop iterates completely l 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; } 19
The do/while statement l A do/while statement has the following format: do statement; while(condition) l The statement is executed once initially, and then the condition is evaluated l The statement will, thus, be executed at least 1 time l The statement is executed repeatedly until the condition becomes false (i.e. remains true) 20
The for statement l A for statement has the following format: for(initialization; condition; increment) statement; l 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( ; ; )statement; 21
Event-controlled loops l An example (a class-averaging algorithm in pseudocode) with sentinel-controlled repetition: 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 } else Print No grades were entered 22
Summary l All programs can be broken down into 3 structures: Sequence: handled automatically by compiler Selection: if else or switch Repetition: while, do/while or for l The structures can only be combined in 2 ways: Sequencing Nesting l Any selection can be rewritten as an if else statement, and any repetition can be rewritten as a while statement 23
Concepts you need to know after this class l Flow of control l Selection statements l Repetition statements (including event-controlled) l Indentation 24
l Read these slides again l Do the self-preparation assignments l Learn the vocabulary Homework l Consult, whenever necessary, the textbook materials 25
Next class l Fundamental Programming Constructs (2) Structural decomposition Program models and parameter passing 26