200 likes | 400 Views
Branching and Loops. Introduction. C Language supports the following decision-making statements : if statement switch statement Conditional operator statement while statement for statement In this lecture we study do while, for and switch statements . The For Loop and Comma Operator.
E N D
Introduction • C Language supports the following decision-making statements: • ifstatement • switchstatement • Conditional operator statement • whilestatement • forstatement In this lecture we study do while, for andswitch statements.
The For Loop and Comma Operator The comma operator extends the flexibility of the for loop by enabling you to include more than one initialization or update expression in a single for loop specification a program that prints first-class postage rates Comma Operator
The program uses a for loop to print the "Powers of 2" table for the power 0 to 20, both positive and negative. The program evaluates the value successively by multiplying 2 by itself ntimes and . Note that we have declared p as a long int and q as a double.
Zeno Meets the for Loop • The Greek philosopher Zeno once argued that an arrow will never reach its target. First, he said, the arrow covers half the distance to the target. Then it has to cover half of the remaining distance. Then it still has half of what's left to cover, ad infinitum. Because the journey has an infinite number of parts, Zeno argued, it would take the arrow an infinite amount of time to reach its journey's end. • Let's take a quantitative approach and suppose that it takes the arrow 1 second to travel the first half. Then it would take 1/2 second to travel half of what was left, 1/4 second to travel half of what was left next, and so on. You can represent the total time by the following infinite series: 1 + 1/2 + 1/4 + 1/8 + 1/16 +....
The short program finds the sum of the first few terms 1 + 1/2 + 1/4 + 1/8 + 1/16 +....
Nested Loops • A nested loop is one loop inside another. • A common use for nested loops is to display data in rows and columns.
A Nested Variation The inner loop may behave differently each cycle depending on the outer loop.
An Exit-Condition Loop: do while The while loop and the for loop are both entry-condition loops. First do the loop and the check an exit condition.
Structure of a do while loop The general form of the do while loop do statement while ( expression ); You should restrict the use of do while loops to cases that require at least one iteration: do { prompt for password read user input } while (input not equal to password); Avoid a do while structure of the type shown in the following pseudocode: do { ask user if he or she wants to continue some clever stuff } while (answer is yes);
Nested do while loop A program to print the multiplication table from 1 x 1 to 12 x 10 This program contains two do.... whileloops in nested form. The outer loop is controlled by the variable row and executed 12 times. The inner loop is controlled by the variable column and is executed 10 times, each time the outer loop is executed. That is, the inner loop is executed a total of 120 times, each time printing a value in the table.
Summary: The do while Statement • The do while statement creates a loop that repeats until the test expression becomes false or zero. do statement while (expression); Example: do scanf("%d", &number); while (number != 20);
Which Loop? • First, decide whether you need an entry-condition loop or an exit-condition loop. • Assume that you need an entry-condition loop. Should it be a for or a while? for ( ;test; ) while (test) initialize; while (test) { body; update; } for (initialize; test; update) body; • A while loop is natural for the following condition while (scanf("%ld", &num) == 1) • The for loop is a more natural choice for loops involving counting with an index: for (count = 1; count <= 100; count++)
Loop flow controls: break; and continue; • C uses two different orders to control loop’s flow • break – escapes from the nearest outer loop • continue – • inside “while” and “do” loop: switches program execution to test condition, • inside “for” loop: switches program execution to “for” loop step and then to condition test (also applies for nearest outer loop) Possible algorithm enhancements (decreasing number of loop’s iterations/repeats): • It is enough to loop n/2 times, better, only till sqrt(n). • Test if the number is dividable with 2, and if it isn’t, test inside loop if the number is dividable with odd numbers bigger than 2.
The example illustrates the use of the break statement in a C program. • The program reads a list of positive values and calculates their average. The for loop is written to read 1000 values. However, if we want the program to calculate the average of any set of values less than 1000, then we must enter a 'negative' number after the last value in the list, to mark the end of input.
The example illustrates the use of continue statement. The program evaluates the square root of a series of numbers and prints the results. The process stops when the number 9999 is typed in.
Branching condition order switch – case Used instead of multisided if selection Pay attention: if the keyword break isn’t stated inside case block; program continues to next case block in the list! switch( expression ){caseconst_expression1: orders1;caseconst_expression2: orders2; …default: ordersN; } Example If break; was to be left-out from every case block, for given grade 3 (example), the result would be false and following:
Review questions What errors can you find?
Review questions What will each of the following programs print?
Review questions Given the input "Go west, young man!", what would each of the following programs produce for output?