1 / 51

Topic 6 – Repetition and Loops

Topic 6 – Repetition and Loops. Program Repetition. Repetition refers to the repeats of certain program statements within a program. As this is often something that is desired, programming languages offer the ability to create loops .

tiana
Download Presentation

Topic 6 – Repetition and Loops

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Topic 6 – Repetition and Loops

  2. Program Repetition • Repetition refers to the repeats of certain program statements within a program. • As this is often something that is desired, programming languages offer the ability to create loops. • A loop body consists of the program statements that are to be repeated. CISC 105 – Topic 6

  3. Counting Loops • The simplest type of loop is a counting loop. This means that the statements inside the loop body are repeated a set number of times. • This type of loop can be used when it is known exactly how many loop iterations are needed in order to solve the necessary problem. CISC 105 – Topic 6

  4. Counting Loops • An example of a counting loop (although a somewhat uninteresting example) is displaying twenty lines of stars on the screen. The loop body consists of one printf statement and is repeated twenty times. CISC 105 – Topic 6

  5. The while Statement • In order to create loops in the C language, the while statement can be used. This statement follows the form: while (condition) { statement1; statement2; . . . } CISC 105 – Topic 6

  6. The while Statement • When the while statement is first encountered, the condition is evaluated. If it is true (nonzero), the loop body executes sequentially. If the condition is false, the loop body is skipped. Notice that this behavior is exactly the same as a simple if statement. while (condition) { statement1; statement2; . . . } CISC 105 – Topic 6

  7. The while Statement • At the end of the loop body (when the closing brace “}” is encountered) the condition is evaluated again. If it is true, the loop body begins to execute again, beginning with the first statement in the body (immediately following the open brace “{”) and continuing to the end sequentially. while (condition) { statement1; statement2; . . . } CISC 105 – Topic 6

  8. Creating a Counting Loop Using the while Statement • So, how can a counting loop be created using the while statement? • This can be done by using a loop control variable to count the loop iterations. • Before the loop begins, we set this variable to it’s initial condition (usually zero). CISC 105 – Topic 6

  9. Creating a Counting Loop Using the while Statement • The last statement in the loop body increments the loop control variable (which is counting the number of loop iterations that have been executed) by one. • The condition should be true if the control variable is less than the number of iterations desired and false once the control variable reaches (is equal to) the number of iterations desired. CISC 105 – Topic 6

  10. Creating a Counting Loop Using the while Statement • So…a simple counting loop looks like: counter = 0; while (counter < 14) { statement1; statement2; . . . counter++; } How many times does this loop run? CISC 105 – Topic 6

  11. A Simple Counting Loop Example printf(“How many employees do you have?”); scanf(“%d”,&number_employees); counter = 0; while (counter < number_employees) { printf(“Hours?”); scanf(“%d”,&hours); printf(“Pay rate?”); scanf(“%lf”,&rate); pay = hours * rate; printf(“The pay is %f.\n”,pay); counter += 1; } CISC 105 – Topic 6

  12. Counting Loops and while Statements • As we have seen, counting loops have three principle components when created with a while statement: • Initialization – set the initial value of the loop control variable (usually to zero) • Testing – Test the value of the loop control variable according to the condition • Updating – Update the loop control variable as the last statement in the loop CISC 105 – Topic 6

  13. A Common Loop Error • What happens if, when writing a counting loop, the programmer does not update the loop control variable? The condition will always be true (assuming it starts off as true). Thus, the loop with execute forever. This is referred to as an infinite loop. CISC 105 – Topic 6

  14. Running Sum (or Product) Loops • Counting loops, such as these, can also be used to create running sums, running products, etc… • Suppose a company wishes to use the previous employee pay program loop to perform payroll functions for its employees. However, total pay for all employees is also required information. CISC 105 – Topic 6

  15. The Simple ExampleWith Total Amount Paid printf(“How many employees do you have?”); scanf(“%d”,&number_employees); counter = 0; total_pay = 0.0; while (counter < number_employees) { printf(“Hours?”); scanf(“%d”,&hours); printf(“Pay rate?”); scanf(“%lf”,&rate); pay = hours * rate; printf(“The pay is %f.\n”,pay); total_pay += pay; counter += 1; } printf(“Total pay = %f.\n”,total_pay); CISC 105 – Topic 6

  16. The for Statement • As we have seen, many loops have three components in addition to the loop body: • Initialization – set the initial value of the loop control variable • Testing – Test the value of the loop control variable according to the condition • Updating – Update the loop control variable CISC 105 – Topic 6

  17. The for Statement • The for statement offers a designed place for each of these three components. If follows the form: for (counter = 0; counter < high_value; counter++) { statement1; statement2; . . . } CISC 105 – Topic 6

  18. The for Statement • Thus, the for statement consists of an initialization, a semicolon, the condition, a semicolon, and the an update statement. for (counter = 0; counter < high_value; counter++) { statement1; statement2; . . . } CISC 105 – Topic 6

  19. The for Statement • Notice that the update statement does NOT have a semicolon. • Also, the initialization and update statements can actually be composed of more than one statement. for (counter = 0; counter < high_value; counter++) { statement1; statement2; . . . } CISC 105 – Topic 6

  20. The for Statement • If more than one statement is to be used for initialization or update, these statements are separated by commas. for (counter = 0, x = 0; counter < high_value; counter++, x += 2) { statement1; statement2; . . . } CISC 105 – Topic 6

  21. for / while Loop Equivalence • Notice that any for loop can be rewritten into a while loop. • The for loop is simply a special case of the while loop, with provisions for initialization and updating build into the loop statement itself. CISC 105 – Topic 6

  22. for / while Loop Equivalence • To convert from a for loop to a while loop, simply move the initialization statement(s) before the loop statement and move the update statement(s) inside the loop body. • We can rewrite the payroll example using a for loop instead of a while loop. CISC 105 – Topic 6

  23. The Payroll Examplewith a for Loop printf(“How many employees do you have?”); scanf(“%d”,&number_employees); total_pay = 0.0; for (counter = 0; counter < number_employees; counter++) { printf(“Hours?”); scanf(“%d”,&hours); printf(“Pay rate?”); scanf(“%lf”,&rate); pay = hours * rate; printf(“The pay is %f.\n”,pay); total_pay += pay; } printf(“Total pay = %f.\n”,total_pay); CISC 105 – Topic 6

  24. Another Example:Factorial with a for Loop int factorial(int x) { int counter, product; product = 1; for (counter = x; counter > 1; counter--) { product = product * counter; } return product; } CISC 105 – Topic 6

  25. Review of Simple Loop Design • Construct a function that takes one argument, an integer. • This function will display the first x Fibonacci numbers, where x is the parameter passed into the function. • This function will return an integer, the xth Fibonacci number. • This function should use a loop, either a while or for loop. CISC 105 – Topic 6

  26. Other Types of Loops • The while and for loop statements can be used to create many different types of loops besides counting loops. • The condition given to these loop statements can be anything that evaluates to true or false; they do not have to be simple counting conditions. CISC 105 – Topic 6

  27. Conditional Loops • In many programming situations, the programmer will not be able to determine the exact number of loop iterations that are required to solve the problem. • As an example, suppose a programmer wishes to ask for a number and keep asking until a valid, positive number is supplied by the user. CISC 105 – Topic 6

  28. A Simple Example of a Conditional Loop printf(“Enter a positive number>”); scanf(“%d”,&number); while (number < 0) { printf(“Enter a POSITIVE number>”); scanf(“%d”,&number); } printf(“Your number was %d.\n”,number); CISC 105 – Topic 6

  29. A Simple Example of a Conditional Loop • Notice that this loop also has the three primary components of a loop that were previously discussed: • Initialization – Set the initial value of some control variable. • Testing – Test the condition (inside the while statement). • Update – Update the value of the loop control variable. CISC 105 – Topic 6

  30. Update Sets the new value of the number variable to the user’s input. Initialization Sets the initial value of the number variable to the user’s input. Testing If number is not positive, perform the loop body (again). A Simple Example of a Conditional Loop printf(“Enter a positive number>”); scanf(“%d”,&number); while (number <= 0) { printf(“Enter a POSITIVE number>”); scanf(“%d”,&number); } printf(“Your number was %d.\n”,number); CISC 105 – Topic 6

  31. Sentinel-Controlled Loops • In some programming situations, the programmer may wish to keep looping until a special, sentinel value is encountered. • As an example, suppose a program is to be written to keep track of salesmen. At the end of each day, all salesmen who make at least one sale will report how much money they made to the company. The program should compute a sum of all money made by the company that day. The number of salesmen who make sales each day is not known. CISC 105 – Topic 6

  32. Sentinel-Controlled Loops • Such a program would keep asking for salesmen and their daily sales, until the special sentinel value is entered. • In this case, the program will use –99 as the special value that indicates there are no more salesmen to be processed that day. CISC 105 – Topic 6

  33. A Simple Example of aSentinel-Controlled Loop company_total = 0; printf(“At any time, type –99 when all data is entered.”); printf(“Enter the first salesman’s total>”); scanf(“%f”,&individual_total); while (individual_total != -99) { company_total += individual_total; printf(“Enter the next salesman’s total>”); scanf(“%f”,&individual_total); } printf(“The company made %f in sales today.\n”, company_total); CISC 105 – Topic 6

  34. Nested Loops • Loops can also be nested. This refers to the putting of one loop inside another loop. • In the previous example, the sales program computed the sales total for one day. • The program can be rewritten to continue to process, day-to-day. This can be done by putting the daily-processing loop inside another loop. Thus, when one day is done, the processing starts all over, for the next day. CISC 105 – Topic 6

  35. A Simple Example of Nested Loops while (1) { company_total = 0; printf(“At any time, type –99 when all data is entered.”); printf(“Enter the first salesman’s total>”); scanf(“%f”,&individual_total); while (individual_total != -99) { company_total += individual_total; printf(“Enter the next salesman’s total>”); scanf(“%f”,&individual_total); } printf(“The company made %f in sales today.\n”, company_total); } CISC 105 – Topic 6

  36. A Simple Exampleof Nested Loops • Notice that the outside loop is an infinite loop. Therefore, once one day’s processing is complete, the next day’s processing will begin. • This will continue indefinitely as the condition of the outside loop (1) is always true, as it is always nonzero. • Suppose the program should ask, at the conclusion of each day, if it should proceed to the next day. CISC 105 – Topic 6

  37. A Simple Example of Nested Loops continue = ‘Y’; while (continue == ‘Y’ || continue == ‘y’) { company_total = 0; printf(“At any time, type –99 when all data is entered.”); printf(“Enter the first salesman’s total>”); scanf(“%f”,&individual_total); while (individual_total != -99) { company_total += individual_total; printf(“Enter the next salesman’s total>”); scanf(“%f”,&individual_total); } printf(“The company made %f in sales today.\n”, company_total); printf(“Type Y to continue, anything else to quit>”); scanf(“%c”,&continue); } CISC 105 – Topic 6

  38. for Loop Equivalence • Notice we could also rewrite this program, using a for statement to construct the outside loop. • This involves simply moving the initialization and update statements into the for statement, as previously discussed. CISC 105 – Topic 6

  39. for Loop Equivalence for (continue = ‘Y’; continue == ‘Y’ || continue == ‘y’; scanf(“%c”,&continue)) { company_total = 0; printf(“At any time, type –99 when all data is entered.”); printf(“Enter the first salesman’s total>”); scanf(“%f”,&individual_total); while (individual_total != -99) { company_total += individual_total; printf(“Enter the next salesman’s total>”); scanf(“%f”,&individual_total); } printf(“The company made %f in sales today.\n”, company_total); printf(“Type Y to continue, anything else to quit>”); } CISC 105 – Topic 6

  40. for Loop Equivalence • This program could also be rewritten to use a for statement for the inner loop. • This, just as before, is done by moving the initialization and update statements into the for statement. CISC 105 – Topic 6

  41. for Loop Equivalence for (continue = ‘Y’; continue == ‘Y’ || continue == ‘y’; scanf(“%c”,&continue)) { company_total = 0; printf(“At any time, type –99 when all data is entered.”); printf(“Enter the first salesman’s total>”); for(scanf(“%f”,&individual_total); individual_total != -99; scanf(“%f”,&individual_total)) { company_total += individual_total; printf(“Enter the next salesman’s total>”); } printf(“The company made %f in sales today.\n”, company_total); printf(“Type Y to continue, anything else to quit>”); } CISC 105 – Topic 6

  42. The do-while Statement • Both of the loop statements we have seen evaluate the condition before the first loop iteration. • Sometimes, we wish to check the condition at the end of the loop iteration, instead of at the beginning of the loop iteration. • This has the effect of ALWAYS executing the loop the first time, then testing the condition at the end of the loop iteration. CISC 105 – Topic 6

  43. The do-while Statement • In order to create such loops, C offers the do-while statement. • This loop follows the format: do { statement1; statement2; . . . } while (condition); CISC 105 – Topic 6

  44. The do-while Statement • When the do statement is first encountered, the loop body begins to execute immediately. • When the loop body completes, the while statement is reached. • The condition is then evaluated. statement1; do { statement2; statement3; . . . } while (condition); statement4; CISC 105 – Topic 6

  45. The do-while Statement • Notice that the while statement has a semicolon at the end of the condition. statement1; do { statement2; statement3; . . . } while (condition); statement4; CISC 105 – Topic 6

  46. The do-while Statement • So…the do-while loop statement is the same as the while statement except the condition is tested at the end of the loop iteration rather than the beginning. • Thus, a do-while loop ALWAYS executes at least once. statement1; do { statement2; statement3; . . . } while (condition); statement4; CISC 105 – Topic 6

  47. The do-while Statement • This type of loop statement is particularly useful when dealing with user input, and the program should only accept certain input values. • As an example, suppose a program should ask the user for a letter grade and only accept A, B, C, D, or F. CISC 105 – Topic 6

  48. A Simple Example of ado-while Loop do { printf (“Enter a letter grade>”); scanf(“%c”,&letter_grade); } while (letter_grade < ‘A’ || letter_grade > ‘F’ || letter_grade == ‘E’); CISC 105 – Topic 6

  49. do-while and while Comparison • Do the following loops do the same thing? Loop #1 scanf(“%d”, &num); while (num != SENTINEL) { /* do something with num */ scanf(“%d”, &num); } Loop #2 do { scanf(“%d”, &num); if (num != SENTINEL) { /* do something with num */ } } while (num != SENTINEL) Yes, the loops do the same thing. Is one better than the other? Why? CISC 105 – Topic 6

  50. Common Loop Errors • Find the error(s) in the following code: #include <stdio.h> /* This program asks for a number and displays that many lines of stars on the screen. */ int main() { int count, num_lines; printf (“How many lines would you like?”); scanf(“%d”,&num_lines); for (count = 0; count <= num_lines; count++) printf (“********************\n”); return 0; } CISC 105 – Topic 6

More Related