Chapter 5 Computer Science & Engineering 155E 5.1 Repetition in Programs Computer Science I: Systems Engineering Focus 5.2 Counting Loops and the While Statement Lecture 05 - Loops 5.3 Computing a Sum or a Product in a Loop 5.4 The for Statement 5.5 Conditional Loops Christopher M. Bourke 5.6 Loop Design [email protected] 5.7 Nested Loops 5.8 Do While Statement and Flag-Controlled Loops 5.10 How to Debug and Test 5.11 Common Programming Errors Repetition in Programs Counting Loops A counter-controlled loop (or counting loop) is a loop whose repetition is Just as the ability to make decisions (if-else selection statements) is an managed by a loop control variable whose value represents a count. Also important programming tool, so too is the ability to specify the repetition of called a while loop. a group of operations. When solving a general problem, it is sometimes helpful to write a solution to 1 Set counter to an initial value of 0 ; a specific case. Once this is done, ask yourself: 2 while counter < someF inalV alue do 3 I Were there any steps that I repeated? If so, which ones? Block of program code ; 4 Increase counter by 1 ; I Do I know how many times I will have to repeat the steps? 5 I If not, how did I know how long to keep repeating the steps? end Algorithm 1: Counter-Controlled Loop The C While Loop While Loop Syntax This while loop computes and displays the gross pay for seven employees. Syntax of the while Statement: The loop body is a compound statement (between brackets) The loop I Initialize the loop control variable repetition condition controls the while loop. I Without initialization, the loop control variable value is meaningless. 1 int count_emp = 0;// Set counter to0 I Test the loop control variable before the start of each loop repetition 2 while(count_emp<7){//If count_emp< 7, do stmts I Update the loop control variable during the iteration 3 printf("Hours>"); 4 scanf("%d",&hours); I Ensures that the program progresses to the final goal 5 printf("Rate>"); 6 scanf("%lf",&rate); 1 count = 1; 7 pay= hours* rate; 2 while(count <= 10) { 8 printf("Pay is$%6.2f\n", pay); 9 count_emp= count_emp + 1;/* Increment count_emp*/ 3 printf("Count=%d\n",count); 10 } 4 count= count + 1; 11 printf("\nAll employees processed\n"); 5 } Common Programming Errors General While Loops Best to generalize code whenever possible. I Skipping crucial steps could lead to an infinite loop 1 int numEmployees =7, I Common error: forgetting to increment your loop control variable 2 count_emp=0; I Syntax error: misplaced semicolons 3 printf("How many employees>"); 4 scanf("%d",&numEmployees); 1 count = 1; 5 while(count_emp< numEmployees){ 2 while(count <= 10); WRONG ← 6 ... 3 { 7 count_emp= count_emp + 1; 4 printf("Count=%d\n",count); 8 } 5 count= count + 1; 6 } Using numEmployees instead of the constant 7 allows our code to be more general. While Loop Exercise While Loop Exercise Answer Exercise Write a while loop to compute the sum of natural numbers 1 to 100: 1 int sum = 0; 100 2 inti = 1;/* our loop control variable*/ i = 1 + 2 + + 100 3 while(i <= 100) ··· Xi=1 4 { 5 sum= sum+i; Generalize the loop so that the sum from 1 to any n can be computed. 6 i=i + 1; 7 } Steps to design: 8 printf("Sum is%d\n", sum); I Identify and define a loop control variable. I Write the syntax for the loop control structure I Fill in the code used within the loop to compute the sum While Loop Exercise While Loop Example II Answer: Generalized Instead of the sum of integers 1 to n, compute the product: 100 1 int sum = 0; i = 1 2 ... 100 × × × 2 intn = 100;/* general variable, may be i=1 Y 3 * changed or read from input*/ What changes need to be made? 4 inti = 1;/* our loop control variable*/ while(i <=n) 5 I Variable names? 6 { I Initialized variable value? 7 sum= sum+i; 8 i=i + 1; I Operators? 9 } Note: this is the factorial function, 10 printf("Sum1 to%d is%d\n",n, sum); n n! = i Yi=1 While Loop Example II Program Failed Answer 1 int product = 1; 2 intn = 100;/* general variable, may be Run the previous program: it gives an answer of 0—why? 3 * changed or read from input*/ 4 inti = 1;/* our loop control variable*/ I Debug your code: use a printf statement in the loop to see what 5 while(i <=n) intermediate values are computed: 6 { printf("i= %3d product=%d\n",i,product); 7 product= product*i; I Check the answers with a calculator 8 i=i + 1; I For what i does this program fail? 9 } 10 printf("Product1 to%d is%d\n",n, product); Overflow Compound Assignment Operators I Expressions such as variable= variable op expression; (where op is a C operator such as +,-,*,/,) occur frequently I We got the wrong answer for i = 13, I C provides several syntax shortcuts I x=x + 1; and x += 1; are “equivalent” 13! = 6, 227, 020, 800 I Can do this with other operators (see table) I We used a 32-bit integer to store product 31 I Maximum representable value is 2 = 2, 147, 483, 648 Expression Shortcut I When a number is too large (or too small!) to be represented by its x=x + 1;x += 1; type, overflow occurs (or underflow) x=x - 1;x -= 1; I More sophisticated solutions are available, but beyond this course x=x * 5;x *= 5; x=x / 2;x /= 2; Table: Compound Assignment Operators Compound Assignment Operators For Loops Example Revisited 1 int product = 1; 2 intn = 100;/* general variable, may be 3 * changed or read from input*/ 4 inti = 1;/* our loop control variable*/ I Program Style 5 while(i <=n) I Increment and Decrement Operators 6 { I Increment and Decrement Other Than 1 7 product *=i; 8 i += 1; 9 } 10 printf("Product1 to%d is%d\n",n, product); For Loops For Loop Example Computing the sum using a for-loop: 1 int sum = 0; 2 intn = 100; I Any repetition can be implemented using a while loop 3 inti; I Another way to construct a counting loop is to use a for loop 4 for(i = 0;i <=n;i++) I C provides for statements as another form for implementing loops. 5 { I As before we need to initialize, test, and update the loop control variable. 6 sum= sum+i; 7 } I The syntax for a for statement is more rigid: it designates a specific place for the initialization, testing, and update components I Advantages: more readable, more predictable I Easier to debug I Pitfall: note the placement of semicolons! Increment Operators Program Style I New syntax: i++ For clarity, the book usually places each expression of the for heading on a I Known as a (postfix) increment separate line. If all three expressions are very short, however, they will be placed on one line. I “Equivalent” to i=i+1 I Also available: (postfix) decrement: i-- (“equivalent” to i=i-1 ) The body of the for loop is indented just as the if statement. Increment and Decrement Operators Increment and Decrement Other Than 1 The counting loops that we have seen have all included assignment expressions of the form We can use the “shortcut” compound assignment operators with values other than 1 I counter= counter+1 I Increment operations: sum= sum+x or sum +=x , will take the I counter++ value of sum, add x to it, and then assign the new value to sum I counter += 1 I Decrement operations: temp= temp-x or temp -=x , will take the This will add 1 to the variable counter. value of temp, subtract x from it and then assign the new value to temp Using -- will subtract one from the counter. Increment and Decrement Other Than 1 Conditional Loops Example 1 /* increment by 10*/ 2 intx = 10; 3 inti; 4 for(i=0;i<100;i+=x) I The exact number of loop repetitions we need to run for a loop will not 5 printf("i=%d\n",i); always be known before loop execution begins. 6 Initialization step? Test? Update action? 7 /* decrement by5*/ 8 inty = 5; 9 for(i=25;i>=0;i-=y) 10 printf("i=%d\n",i); Exercise Exercise Pseudocode 1 Set x to an initial value of 1 ; Exercise 2 Prompt the user for a value input; Create a program that prompts the user for a value x and multiplies it by the 3 while input is not zero do previous value of x storing the result in x until the user enters a 0. 4 Set x to x multiplied by input; 5 Prompt the user for a new input value ; 6 end Algorithm 2: Prompt Product Loop Exercise Loop Design Translated to C 1 intx = 1; 2 int value; 3 printf("Entera value, (0 to quit)>"); To this point, we have been analyzing the actions a loop performs. 4 scanf("%d",&value); Now, we also want to design our own loops: 5 while(value != 0) 6 { I Sentinel-Controlled Loops 7 x=x* value; I Using a for Statement to Implement a Sentinel Loop 8 printf("Entera value, (0 to quit)>"); 9 scanf("%d",&value); 10 } 11 printf("The product is%d", value); Sentinel-Controlled Loops Sentinel-Controlled Loops I Often we don’t know how many data items the loop should process when it begins execution.
Details
-
File Typepdf
-
Upload Time-
-
Content LanguagesEnglish
-
Upload UserAnonymous/Not logged-in
-
File Pages9 Page
-
File Size-