C programming Language Chapter 2 Control Flow 04


























- Slides: 26

C programming Language Chapter 2: Control Flow ספטמבר 04 Copyright Meir Kalech 1

Statements and Blocks n n An expression becomes a statement when it’s followed by a semicolon (as a terminator). Examples: n n n i++; n = 0; printf (…); Braces { and } (also called curly brackets) are used to group declarations and statements together into a compound statement, or block. A block is syntactically equivalent to a single statement (but no semicolon after right brace). ספטמבר 04 Copyright Meir Kalech 2

What is Control Flow? n n Sometimes we want a statement to be executed only under certain conditions or be done a few times (not just once). C supplies a set of commands which control the flow of the program: n n n if-else switch-case for while do-while ספטמבר 04 Copyright Meir Kalech 3

if Statement – Flow Diagram • if statement: F logic expression T statement(s) • if-else statement: F logic expression statement(s) ספטמבר 04 Copyright Meir Kalech T statement(s) 4

if Statement n “if” syntax: if (expression) statement; n If there are multiple statements, then add a block (using braces): if (expression) { statements; } ספטמבר 04 Copyright Meir Kalech 5

if-else Statement n “if…else” Syntax: if (expression) statement; else statement; n If there are multiple statements, then add block: if (expression) { statements; } else { statements; } ספטמבר 04 Copyright Meir Kalech 6

Examples (1) n The program gets a character from user. If the character is a digit or ‘y’, the user gets a correct message: char num; scanf(“%c”, &num); if (num >= ‘ 0’ && num <= ‘ 9’ || num == ‘x’+1) printf(“good choicen”); comment: ‘x’+1 is equal to ‘y’ (according to ASCII table). ספטמבר 04 Copyright Meir Kalech 7

Examples (2) n The program gets a character from user. If the character is a digit or ‘y’, the user gets a correct message and increments the character, else the user gets an error message: char num; scanf(“%c”, &num); if (num >= ‘ 0’ && num <= ‘ 9’ || num == ‘x’+1) { printf(“good choicen”); num++; } else printf(“bad choicen”); ספטמבר 04 Copyright Meir Kalech 8

Nested if Statement n n “Nested if” is a condition in the scope of another condition. If the first condition is true then the secondition is active. Example syntax: if (expression 1) { if (expression 2) statement 1; statement 2; } else if (expression 3) { statements 3; } else statement 4; ספטמבר 04 F expression 1 expression 3 statement 4 statements 3 T expression 2 statement 1 statement 2 Copyright Meir Kalech 9

switch-case Statement When few constant alternatives exist, we can select the correct one by using if-else, or even better by switch-case: switch(expression) { case constant 1: [break; ] case constant 2: statement(s); [break; ] case constant 3: statement(s); [break; ] default: // // // The value of the statement will be looked for in the existing cases. The matched case will be executed up to the end of the switch block or a break. // The default statement is optional. // If no matching case was found, the // statements in default will be executed. } ספטמבר 04 Copyright Meir Kalech 10

switch-case Statement n n n switch-case is useful for constructing menus. A menu is composed of two parts: 1. Menu 2. Selection Example: Menu: Selection: int selection; printf(“choose an option: n” “ 1 – additionn” “ 2 – subtractionn” “ 3 – multiplicationn”); scanf(“%d”, &selection); If we remove ‘break’ from case 1 and selection is 1, then both case 1 and case 2 will be executed!! ספטמבר 04 switch(selection) { case 1: case 2: case 3: default: } Copyright Meir Kalech printf(“%d”, x+y); break; printf(“%d”, x-y); break; printf(“%d”, x*y); break; printf(“wrong”); break; 11

Loops n n When we want to execute statement(s) multiple times, we can use a loop statement. Two categories of loops: 1. Counter loop: the number of iterations is known in advance. 2. Conditional loop: the number of iterations depends on a condition. ספטמבר 04 Copyright Meir Kalech 12

for – Flow Diagram n for is a kind of counter loop. expression + F logic expression T loop body continue program ספטמבר 04 Copyright Meir Kalech 13

for - Syntax for(counter initialization; condition; counter increment) statement; for(initialization; condition; increment) For multiple { statements: use a block statements; } n n n Initialization: initialization of the counter. Initialization is applied only once at the start. Condition: for each iteration, the condition is checked. If the condition is true, the statement(s) are executed, else the program continues after the ‘for’ block. Usually the condition checks the counter. Increment: Increment (or decrement) the counter. After incrementing the counter, the condition is checked. ספטמבר 04 Copyright Meir Kalech 14

for - Examples n Printing numbered “hello world” 3 times: int i; for(i=0; i<3; i++) printf(“no. %d hello worldn”, i+1); n Explanation: Condition is true when i=0, 1, 2. In these cases, “hello world” will be printed. When i=3, the “for” loop will be exited. n Calculating the sum of the teens group (10 -19): int i, sum=0; for(i=10; i<20; i++) sum += i; n Explanation: In this case, i is initialized to 10, and the condition is i<20. ספטמבר 04 Copyright Meir Kalech 15

for - Comments n Increment can be any mathematical operation: int i; for (i = 20; i > 0; i /= 2) n The counter can be any number type: n Each of the 3 expressions can include more than one expression: char c; for (c='a'; c<='z'; c++) double i, j; for (i=11. 1, j=22. 2; i<j && j>=15; i*=2, --j) n One or more expressions can be left blank: int i = 10; //instead of initialization for ( ; i<20; ) { printf(“hello worldn”); i++; //instead of increment } ספטמבר 04 Copyright Meir Kalech 16

while – Flow Diagram While is a kind of condition loop: logic statement true execute loop body false (expression equals zero) skip loop body and continue the serial execution of the program ספטמבר 04 Copyright Meir Kalech 17

while – Syntax while (condition) statement; while (condition) { statements; } For multiple statements: use a block Condition: In each iteration, the condition is checked. If the condition is true, the statement(s) are executed, else the program continues after the ‘while’ block. The value of the condition must be changed through the statement(s), otherwise it’s an infinite loop. ספטמבר 04 Copyright Meir Kalech 18

while – Examples n Printing numbered “hello world” 3 times: n int i=0; while(i<3) printf(“no. %d hello worldn”, ++i); Explanation: Condition is true when i=0, 1, 2. In these cases, “hello world” will be printed. When i=3, the “while” loop will be exited. Attention: this loop is a counter loop, which is implemented within the while loop. Generally, prefer a “for loop” for a counter loop. n Sum digits: int num=345, sum=0; while(num) //exactly as: while(num != 0) { sum += num%10; num /= 10; } ספטמבר 04 Copyright Meir Kalech 19

while – Examples n Getting a digit from the user: char digit; while(digit <‘ 0’ || digit >‘ 9’) { printf(“enter a digit”); scanf(“%c”, &digit); } n problem: In this example, the initial digit’s value is garbage – not good! Garbage could also be some character between ‘ 0’ to ‘ 9’. In this case, the while loop will not be applied at all, and the user is never asked to enter a digit. ספטמבר 04 Copyright Meir Kalech 20

do-while Statement n n We can solve this problem by using a do-while loop: char digit; do { printf(“enter a digit”); scanf(“%c”, &digit); } while(digit <‘ 0’ || digit >‘ 9’); In do-while loop, the statements are executed before the condition test. This kind of loop is used mainly in case the statement(s) need to be performed at least once. Syntax: n Parenthesis after the while are mandatory (even if there is only one statement). n Semicolon is mandatory at the end of do-while. ספטמבר 04 Copyright Meir Kalech 21

break Statement n “break” command is intended to break out of a loop execution. n n Example: Getting a digit from the user for up to 3 times: int flag = 0; int i; char digit; for(i=0; i<3; i++) { printf(“enter a digit”); scanf(“%c”, &digit); if(digit >=‘ 0’ && digit <=‘ 9’) { flag = 1; break; } } Flag is necessary to inform us if the digit has been gotten. ספטמבר 04 Copyright Meir Kalech 22

continue Statement n n n “continue” command is used to skip over the rest of the statements in the body of the loop. Example: Adding a sequence of numbers, except those that are divisible by 4: int i, sum=0; for(i=0; i<20; i++) { if(!(i%4)) continue; sum += i; } When i is divided by 4 without a remainder, the ‘continue’ command is applied, and the statement “sum += i; ” is not executed but skipped (to proceed with increment of i). ספטמבר 04 Copyright Meir Kalech 23

Nested Loop n n A nested loop is a loop within a loop. In each external loop iteration, the internal loop is executed. In other words, the body of the external loop (statement) is an internal loop. The external and internal loops are independent of each other - they could be of different types (say for and while). A nested loop is used when we want to execute a task multiple times and the task itself executes another task multiple times. For instance: the teacher collects from some students their grades in various subjects: 1. collecting from each student is the first task (external loop). 2. collecting each grade of the student is the second task (internal loop). ספטמבר 04 Copyright Meir Kalech 24

Nested Loop n n Example: do you remember the multiplication table? ? ? (without using a calculator ): for(i=1; i<=3; i++) { for(j=1; j<=3; j++) First task printf(“%d ”, i*j); printf(“n”); Second task } In each external iteration, we have 2 tasks: 1. Calculate the row of i multiplier. 2. Move to a new line. ספטמבר 04 Copyright Meir Kalech 25

Nested Loop n n Comment: j is initialized in the internal loop whenever the internal loop is started. Let’s view a table of the variable’s values: i 1 1 1 2 2 2 3 3 3 j 1 2 3 first external loop ספטמבר 04 second external loop Copyright Meir Kalech third external loop 26