DOC PREVIEW
MIT 16 070 - Lecture Notes

This preview shows page 1-2-21-22 out of 22 pages.

Save
View full document
View full document
Premium Document
Do you want full access? Go Premium and unlock all 22 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 22 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 22 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 22 pages.
Access to all documents
Download any document
Ad free experience
Premium Document
Do you want full access? Go Premium and unlock all 22 pages.
Access to all documents
Download any document
Ad free experience

Unformatted text preview:

Fesq2/23/01 1 16.070Program Control Flow - Iteration2/23/01 Lecture #8 16.070Basic Constructs of Structured ProgrammingDo first part to completionDo second part to completionSub-task 1Sub-task 2Test conditionSub-taskFalseTest conditionIterativeSequentialConditionalTrueFesq2/23/01 2 16.070Clarification: The switch Statement• Once a case is matched in a switch statement, all subsequent cases willbe executed, including the default case!• Driving directions to the airportswitch (location) {case MIT: walk_to_Kendall();case kendall: board_redline();case redline: switch_greenline();case greenline:switch_blue_line();break;default: ask_directions(); }Fesq2/23/01 3 16.070Program Control Flow - Iteration• Iteration constructs repeat a sequence of code in a controlled manner• Iteration directs the computer to perform the same set of operationsover and over until a specified condition is met• Three C statements for looping! while! for! do … whileFesq2/23/01 4 16.070FalsetestTrueLoop bodyIteration - The while Statement• Repeatedly executes a statement while a test condition (an expression)evaluates to truewhile (<expression>)statement;! Test condition is checked before each cycle, or iteration, through the loop! If expression evaluates to TRUE (non-zero), statement is executed (again)• Pretest: expression is tested before each execution of thestatement• Use brackets to group multiple statementswhile (<expression>){statement1;statement2;}/* end while */Fesq2/23/01 5 16.070 The while Statement Template• Recommended approach to using whileget first value to be testedwhile the test is successfulprocess valueget next value• Note that the body includes something that changes the value of thetest expression. Why? What happens if value being tested doesn'tchange?int variable = 1;while (variable == 1){statement1;update value of variable;statement3;}/* end while */Fesq2/23/01 6 16.070The while Statement for Counter Controlled Loops• while can be used for counter-controlled loops! Declare loop control variable! Assign initial value to the variable! Test loop control variable by comparing to a final value! Update loop control variable: increment/decrement by a certain value! E.g., This loop iterates while the value of x is less than 10.int x = 0;while (x < 10) {printf ("%d ", x);x = x + 1;}/* end while */! Produces the following output:0 1 2 3 4 5 6 7 8 9Fesq2/23/01 7 16.070The while Statement for Sentinel Controlled Loops• while can be used for sentinel-controlled loops! Declare sentinel variable and decide on termination value! Initialize sentinel variable! Use sentinel variable in loop control expression! Change value of sentinel variable so that loop is eventually exited! Example: code to compute the square of a number entered via keyboardint number;printf ("Enter an integer to square; enter zero to stop: ");scanf ("%d", &number);while (number) {printf ("The square of %d is: %d\n", number, number *number);printf ("Enter an integer to square; enter zero to stop: ");scanf ("%d", &number);}/* end while */Fesq2/23/01 8 16.070The while Statement - Initialization• !Caution: Always be sure that the variable being checked in thewhile test has been initialized!! In example above, omit the printf and scanf lines prior to while statement.What would be the outcome?int number;while (number){printf ("Enter an integer to square; enter zero to stop: ");scanf ("%d", &number);printf ("The square of %d is: %d\n", number, number *number);}/* end while */Fesq2/23/01 9 16.070The while Statement - Termination• !Common mistake when using while -- loop termination! Mistakes in body can cause an infinite loop, causing program to neverterminateint x = 0;while (x < 10)printf ("%d ", x);/* end while */! Mistakes in test condition can cause an infinite loop, causing program tonever terminateint x = 0;while (x > -10){printf ("%d ", x);x = x + 1;}/* end while */• Make sure test value changes, and changes in right direction!Fesq2/23/01 10 16.070FalsetestTrueLoop bodyInitialize CounterUpdate CounterIteration - The for Statement• The for statement is designed as shorthand for looping with thefollowing conditions! When you need to initialize one or more variables before entering the loop! When you need to change the value of one or morevariables each time through the loop• Most frequently used of all iterative statementsfor (<initialize>; <test>; <update>)loop_body;• Combines three actions into one! Initialize: Initialize counter! Test: Compare counter to limiting value! Update: Increment counter each time through the loopFesq2/23/01 11 16.070 Execution of the for Statement• Initialize: Initialization is performed just once before the first iteration,but is always performed regardless of test result• Test: <test> expression gets evaluated before every iteration todetermine if another iteration should be executed• Update: <update> expression is evaluated at the end of every iteration.Used to prepare for the next iteration• Loop body: Defines the work to be performed in each iterationint num;int x = 5;for (num = 5; num < x; num++){ /* begin loop body */statement1;statement2;} /* end loop body *//* end for */printf ("After loop, num = %d\n", num);Fesq2/23/01 12 16.070Iteration: for vs while• Compare the for statement to the while statement! The for statementfor (<init_exp>; <test_exp>; <update_exp>)statement1;/* end for */----------------------- is equivalent to ------------------------! The while statement<init_exp>;while (<test_exp>){statement1;<update_exp>;}/* end while */Fesq2/23/01 13 16.070Recommended Uses of for vs while• The while statement used for sentinel-controlled loops; where numberof repetitions depends on value of variable being tested• The for statement used for counter-controlled: perform "n" number ofrepetitions• Note: The for statement provides some level of reliability:! Compiler will not let you forget an "initialize" expression (although it canbe a null statement)! Compiler will not let you forget an "update" expression (although it can bea null statement)Fesq2/23/01 14 16.070Flexibility of for• Decrement operator to count down instead of upint secs;for (sec = 5; sec > 0; sec--)printf ("%d seconds!\n", secs);/* end for */printf ("We have ignition!\n");• Count by twos, threes, or any number you defineint num;for (num = 2; num < 60; num = num + 2)printf ("%d \n", num);/* end for */• Test condition can be other than


View Full Document

MIT 16 070 - Lecture Notes

Documents in this Course
optim

optim

20 pages

Load more
Download Lecture Notes
Our administrator received your request to download this document. We will send you the file to your email shortly.
Loading Unlocking...
Login

Join to view Lecture Notes and access 3M+ class-specific study document.

or
We will never post anything without your permission.
Don't have an account?
Sign Up

Join to view Lecture Notes 2 2 and access 3M+ class-specific study document.

or

By creating an account you agree to our Privacy Policy and Terms Of Use

Already a member?