Control structures in C Going beyond sequential
Flow of control in a program Start (main) Program starts with the first statement in main Instructions proceed sequentially: One at a time Top to bottom Each executes exactly once If a function call occurs, the sequence is interrupted; when the function returns, the sequence resumes Step 1 Step 2 Call F Step 3 End (main) Start (F) F step 1 F step 2 End (F)
Altering flow of control Programming constructs can be employed to alter the flow of logic Two basic categories: Selection (aka branching) Iteration (aka looping) Both constructs rely on the evaluation of logical or relational expressions to determine which instruction(s) to execute
Quick review of logical expressions Logical, or boolean expressions, are expressions that evaluate to true or false In C, there is no boolean data type Int values used instead 0 means false Any other int value means true
Relational & Logical Operators in C Relational operators: >, <, >=, <= ==,!= Logical operators: &&!
Selection structures in C Simplest structure is plain if: if(expression evaluates true) { } Example: /* perform instruction(s) */ if ((x % 10) == 0) { } printf( %d is a multiple of 10\n, x);
Selection structures in C Important syntax notes: Always put parentheses around the expression to be tested in an if clause (it's a syntax error if you don't) Never put a semicolon at the end of the if clause Semicolon, all by itself, is a null (non-operational) statement if (expression); says if expression is true, do nothing Begin/end brackets ({}) are required if more than one statement is to be executed because of an if clause; if there is only one statement, they are optional
Something to watch out for what is output from this program? #include <stdio.h> int main() { int x = 0; if (x = 0) { printf("x is zero"); } return 0; }
Selection structures in C Perhaps the most versatile selection structure is the if/else structure In this structure, the if clause is followed by statement(s) to perform if the expression is true, and an else clause is followed by statement(s) to perform if the expression is false
The if/else structure: syntax if (expression) { } else { } /* statement(s) to perform if expression is true */ /* statement(s) to perform if expression is false */
#include <stdio.h> #include <stdlib.h> #include <time.h> Example int main() { srand(time(null)); int r = rand() % 20-10; if(r >= 0) printf("%d is positive\n", r); else printf("%d is negative\n", r); }
Compound selection (multiple branching) Each if and else clause is followed by one or more statements to execute We can place another if or if/else combination within the set of statements followed by either clause The result is a nested if or nested if/else structure
#include <stdio.h> #include <stdlib.h> Example int main() { srand(time(null)); int r = rand() % 3-1; if(r > 0) printf("%d is positive\n", r); else if (r < 0) printf("%d is negative\n", r); else printf("%d is zero\n", r); }
Notes on nested if/else An else clause never has its own condition; it is always the alternative to the nearest previous if clause If you want to test another condition, therefore, you need another if clause this was the case with the previous program: if(r > 0) printf("%d is positive\n", r); else if (r < 0) /* new condition, new if clause */
Matching ifs and elses An else clause always pairs with the closest if clause that doesn't already have a paired else Example if (A)... if (B)... if (C)... else /* pairs with condition C */... else /* pairs with condition B */... else /* pairs with condition A */...
Alternate branching structures: switch/case & the ternary operator Nested if/else structures are sufficient to cover any program you might want to write that involves logical selection There are a couple of alternative structures you should at least be aware of These are briefly discussed on the next 2 slides
The switch/case structure May be used instead of if/else when the condition being tested is in the form if x == y Instead of using the relational expression, we use the variable (x) as the switch, and the various possible values (y) as cases Instead of a final else, we can use a default case
The ternary operator Is so named because it takes 3 operands Syntax: Logic: expression? statement1 : statement2 If the expression is true, perform statement1 Otherwise, perform statement 2
Loops in C Selection structures, as the name implies, select certain statements to execute while skipping other statements Loops are structures that repeat a set of statements as long as a condition remains true
Loop control We can generally divide all loops into two categories: Count controlled loops are those that execute a set number of iterations Event controlled loops execute an indeterminate number of times; something external to the program (e.g. the user) decides how many times the loop will execute
Loop constructs in C The basic, most general type of loop is the while loop A loop specifically designed for count control is the for loop A loop that is guaranteed to give us at least one iteration regardless of the condition is a do/while loop We will spend most of our time with the first two
While loops Syntax: while (expression) { } /* statements to perform if expression is true */ /* statement or statements that update the condition */
While Statement while ( Expression ) { statement(s); } Expression is test for terminating condition Loop exit occurs when test succeeds (tests false) Loop entry is moment flow of control reaches 1st statement in loop body One iteration means one pass through the loop Even though actual value being tested changes inside loop body, exit does not occur until next time value is tested
Example int x = 0; // control variable initialization while (x < 100) // control variable test { printf ( x=%d\n, x); x ++; // control variable updated }
Another example int main() { int x = 10; while (x > 0) { printf( %2d\n, x); x--; } printf( Lift off!\n ); return 0; } Loop trace: Value of x Output 10 10 9 9 8 8 7 7 6 6 5 5 4 4 3 3 2 2 1 1 0 (loop ends) Lift off!
int sum = 0, number = 1; while ( sum <= 1000000 ) { } sum = sum + number; number = number + 1; Example When will the loop end? A.When number reaches 100 B.When sum equals 1000000 C.When number exceeds 100 D.When sum exceeds 1000000
Example int product = 1, number = 1, count = 20, lastnumber; lastnumber = 2 * count - 1; When the loop concludes, what is the value of number? while (number <= lastnumber) { product = product * number; number = number + 2; }
Example: finding sum and average 100 numeric values need to be added together and averaged Using a while loop: read the 100 values find their total find their average
int main() { int thisnum; int total = 0; // initialize sum int count = 0; // initialize loop control while ( count < 100 ) // test expression { printf ( Enter value: ); scanf( %d, &thisnum); // read 1 value total = total + thisnum ; // add value to sum count++ ; // update loop control } } printf ( The sum of the values is: %d\n, total); printf ( The average is: %lf\n, (double)total/count); return 0;
Event controlled loop In the previous example, a loop was used to find the sum and average of 100 numbers Although it should work, it's pretty rigid User has to hang in there and type 100 values Only works for data sets of size 100 Using an event-controlled loop we can modify the program to be both more user-friendly and more versatile
Infinite loop Loop that never stops iterating Happens when terminating condition can t be reached Need to ensure that the control variable changes during body of loop 31
Examples of infinite loops /* loop body is null statement: */ int x=0; while (x < 10); /* loop body is single statement that doesn t update control variable */ int x=0; while (x < 10) printf( %d\n, x); x++; /* control variable update is incorrectly written */ int x=0; while (x < 10) { printf( %d\n, x); x--; } 32
For loops Count-controlled loops are so common in programming that most languages have a special set of syntax designed specifically for this construct In C, the special syntax for a countcontrolled loop is called a for loop 33
Count-controlled loops Count-controlled while loop: initialize counter before loop starts test counter in loop control expression update counter inside loop body A for loop is a stylized version of a countcontrolled while loop; all of the elements above appear at the top of the loop 34
For Loop Syntax for ( initialization ; test expression ; update ) { 0 or more statements to repeat } 35
The for loop contains an initialization an expression to test for continuing an update to execute after each iteration of the body 36
Count-controlled while loop example int x=0; /* step 1: initialize counter */ while (x < 100) /* step 2: test counter value */ { printf( I will be a good student\n ); x++; /* step 3: increment counter */ } 37
Same logic using for loop for (int x=0; x<100; x++) printf( I will be a good student\n ); Step 1: initialize loop counter (performed once) Step 2: test counter value (performed once for each iteration) Step 3: increment loop counter (performed once per iteration) Body of loop is performed between steps 2 and 3, just as in the while loop version 38
Example using decrement for (int count = 4 ; count > 0 ; count-- ) { printf( %d\n, count); } printf( Done\n ); OUTPUT: 4 3 2 1 Done 39
Notes on for loop Just stylized version of while loop; condition test occurs before each iteration Can contain single statement (making brackets unnecessary) because increment occurs in loop heading Each section of loop heading can contain multiple parts, separated by commas; each section can also be omitted 40
What is output? int count=0; for (; count < 10 ; count++ ) { printf( ) ; } 41
What is output? int count=0; for (; count < 10 ; count++ ); { printf( ) ; } 42
1Potato 2Potato 3Potato 4 5Potato 6Potato 7Potato More Write a loop to produce the following output: 43
Do-while loops Slight variation of while loops Instead of testing condition, then performing loop body, the loop body is performed first, then condition is tested A do-while loop is guaranteed to perform one iteration, because the validity of the condition is not known until after the iteration is complete 44
Syntax for do-while loop do { /* loop body statements */ }while (expression); Notes: do-while loops are almost always event-controlled Often not necessary to initialize loop control Good idea to keep end bracket and while(expression) on same line 45
Applications for do-while loops Often used to display an initial menu of choices, one of which is quit program you want user to see this at least once, even if the option they pick is to quit Can work well for file input Useful for checking validity of input value eliminates having to prompt twice for same data (see examples, next two slides) 46
Do-While Loop vs. While Loop POST-TEST loop (exitcondition) The looping condition is tested after executing the loop body. Loop body is always executed at least once. PRE-TEST loop (entrycondition) The looping condition is tested before executing the loop body. Loop body may not be executed at all. 47
Nested loops Just as a selection structure can be nested within another selection structure (or within a loop), a loop can also be nested When one loop is nested within another, each iteration of the outer loop contains several iterations of the inner loop 48