Topic 6 – Repetition and Loops. CISC 105 – Topic 6 Program Repetition Repetition refers to the repeats of certain program statements within a program.

Slides:



Advertisements
Similar presentations
CS0004: Introduction to Programming Repetition – Do Loops.
Advertisements

Loops (Part 1) Computer Science Erwin High School Fall 2014.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 4 – C Program Control Outline 4.1Introduction.
Computer Science 1620 Loops.
Topic 9 – Introduction To Arrays. CISC105 – Topic 9 Introduction to Data Structures Thus far, we have seen “simple” data types. These refers to a single.
Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5 th Edition Chapter 5 Looping.
1 ICS103 Programming in C Lecture 7: Repetition Structures.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Sixth Edition Chapter 5: Looping by Tony.
Chapter 5: Loops and Files.
CS1061: C Programming Lecture 8: Repetition A. O’Riordan, 2004.
© 2004 Pearson Addison-Wesley. All rights reserved5-1 Iterations/ Loops The while Statement Other Repetition Statements.
Chapter 5 (Loop Statements)
ECE122 L9: While loops March 1, 2007 ECE 122 Engineering Problem Solving with Java Lecture 9 While Loops.
Chapter 4: Control Structures II
11 Chapter 4 LOOPS AND FILES. 22 THE INCREMENT AND DECREMENT OPERATORS To increment a variable means to increase its value by one. To decrement a variable.
Chapter 5: Control Structures II (Repetition)
CHAPTER 5: CONTROL STRUCTURES II INSTRUCTOR: MOHAMMAD MOJADDAM.
Principles of Programming - NI July Chapter 5: Structured Programming In this chapter you will learn about: Sequential structure Selection structure.
CSEB 114: PRINCIPLE OF PROGRAMMING Chapter 5: Structured Programming.
Repetitive Structures BBS514 Structured Programming (Yapısal Programlama)1.
Mr. Dave Clausen1 La Cañada High School Chapter 6: Repetition Statements.
Copyright © Nancy Acemian 2004 For Loops-Break-Continue COMP For loop is a counter controlled loop. For loop is a pretest loop. Used when number.
1 Loops. 2 Topics The while Loop Program Versatility Sentinel Values and Priming Reads Checking User Input Using a while Loop Counter-Controlled (Definite)
Chapter 5: Control Structures II (Repetition). Objectives In this chapter, you will: – Learn about repetition (looping) control structures – Learn how.
Control Structures II Repetition (Loops). Why Is Repetition Needed? How can you solve the following problem: What is the sum of all the numbers from 1.
Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,
Chapter 5: Structured Programming
CMSC 104, Lecture 171 More Loops Topics l Counter-Controlled (Definite) Repetition l Event-Controlled (Indefinite) Repetition l for Loops l do-while Loops.
Chapter 4: Control Structures II
+ Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy Walters, and Godfrey Muganda Chapter 5: Looping.
CMSC 104, Version 9/011 More Loops Topics Counter-Controlled (Definite) Repetition Event-Controlled (Indefinite) Repetition for Loops do-while Loops Choosing.
Introduction to Loops Iteration Repetition Counting Loops Also known as.
Java iteration statements ● Iteration statements are statements which appear in the source code only once, but it execute many times. ● Such kind of statements.
Loops and Files. 5.1 The Increment and Decrement Operators.
1 Standard Version of Starting Out with C++, 4th Brief Edition Chapter 5 Looping.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5: Looping.
Agenda Perform Quiz #1 (20 minutes) Loops –Introduction / Purpose –while loops Structure / Examples involving a while loop –do/while loops Structure /
A First Book of C++ Chapter 5 Repetition.
Chapter 5: Repetition and Loop Statements By: Suraya Alias.
Think Possibility 1 Iterative Constructs ITERATION / LOOPS C provides three loop structures: the for-loop, the while-loop, and the do-while-loop. Each.
Repetition Repetition allows you to repeat an operation or a series of operations many times. This is called looping and is one of the basic structured.
Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 5 Looping.
Repetition Statements (Loops). 2 Introduction to Loops We all know that much of the work a computer does is repeated many times. When a program repeats.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
LECTURE # 8 : REPETITION STATEMENTS By Mr. Ali Edan.
1 ICS103 Programming in C Lecture 7: Repetition Structures.
PGT C Programming1 Week 4 – Repetition Structures / Loops.
Java Programming: From Problem Analysis to Program Design, 3e Chapter 5 Control Structures II: Repetition.
While loops. Iteration We’ve seen many places where repetition is necessary in a problem. We’ve been using the for loop for that purpose For loops are.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
Lecture 7 – Repetition (Loop) FTMK, UTeM – Sem /2014.
Chapter 4 Repetition Statements Program Development and Design Using C++, Third Edition.
Sesi 0607EKT120/4 Computer Programming Week 5 – Repetition / Loops.
1 ICS103 Programming in C Lecture 7: Repetition Structures.
Problem Solving and Program Design in C Chap. 5 Repetition and Loop Statement Chow-Sing Lin.
CHAPTER 4 REPETITION STRUCTURES 1 st semester King Saud University College of Applied studies and Community Service Csc 1101 A.AlOsaimi.
Chapter 4 – C Program Control
REPETITION CONTROL STRUCTURE
CHAPTER 4 REPETITION CONTROL STRUCTURE / LOOPING
Lecture 7: Repeating a Known Number of Times
Lecture 4 - Loops UniMAP EKT120 Sem 1 08/09.
Week 4 – Repetition Structures / Loops
Quick Test What do you mean by pre-test and post-test loops in C?
Arrays, For loop While loop Do while loop
More Loops Topics Counter-Controlled (Definite) Repetition
More Loops Topics Counter-Controlled (Definite) Repetition
LOOPS The loop is the control structure we use to specify that a statement or group of statements is to be repeatedly executed. Java provides three kinds.
ICS103: Programming in C 5: Repetition and Loop Statements
More Loops Topics Counter-Controlled (Definite) Repetition
Presentation transcript:

Topic 6 – Repetition and Loops

CISC 105 – Topic 6 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 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 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 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 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 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 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 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 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 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 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 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 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 The Simple Example With 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 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 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 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 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 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 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 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 The Payroll Example with 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 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 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 x th Fibonacci number. This function should use a loop, either a while or for loop.

CISC 105 – Topic 6 Other Types of Loops The while and for loop statements can be used to create many different types of loop 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 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 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 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 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); 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). Update Sets the new value of the number variable to the user’s input.

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

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

CISC 105 – Topic 6 Common Loop Errors Find the error(s) in the following code: #include /* 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 Common Loop Errors Find the error(s) in the following code: #include /* This program asks for numbers and keeps a running sum. It terminates when –99 is entered. */ int main() { int sum, number; do { printf(“Enter a number (-99 to quit)>”); scanf(“%d”,&number); sum += number; } while (number != -99); printf (“The sum is %d.\n”,sum); return 0; }