CHAPTER 4 REPETITION STRUCTURES 1 st semester 1432 -1433 1 King Saud University College of Applied studies and Community Service Csc 1101 A.AlOsaimi.

Slides:



Advertisements
Similar presentations
Computer Science 1620 Loops.
Advertisements

Chapter 5 Repetition and Loop Statements Instructor: Alkar & Demirer.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie July 5, 2005.
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.
Topic 6 – Repetition and Loops. CISC 105 – Topic 6 Program Repetition Repetition refers to the repeats of certain program statements within a program.
1 CS 201 Repetition Debzani Deb. 2 Overview Loops  Endfile-Controlled loop  Nested loop  Do-While loop  Flag-Controlled loop Hand Tracing the code.
Chapter 5: Control Structures II (Repetition)
CS 201 Selection Structures (2) and Repetition
COMP 14 Introduction to Programming Miguel A. Otaduy May 20, 2004.
Chapter 5: Control Structures II (Repetition)
Chapter 5 (Loop Statements)
COMP 110 Introduction to Programming Mr. Joshua Stough September 24, 2007.
CONTROL STATEMENTS Lakhbir Singh(Lect.IT) S.R.S.G.P.C.G. Ludhiana.
Control Structures II. Why is Repetition Needed? There are many situations in which the same statements need to be executed several times. Example: Formulas.
Chapter 4: Control Structures II
Chapter 5: Control Structures II (Repetition)
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 5: Control Structures II (Repetition)
Chapter 5: Control Structures II (Repetition)
CHAPTER 5: CONTROL STRUCTURES II INSTRUCTOR: MOHAMMAD MOJADDAM.
EGR 2261 Unit 5 Control Structures II: Repetition  Read Malik, Chapter 5.  Homework #5 and Lab #5 due next week.  Quiz next week.
Repetitive Structures BBS514 Structured Programming (Yapısal Programlama)1.
1 ICS103 Programming in C Ch5: Repetition and Loop Statements.
Chapter 5 Control Structure (Repetition). Objectives In this chapter, you will: Learn about repetition (looping) control structures Explore how to construct.
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,
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Flow Control (for) Outline 4.1Introduction 4.2The.
Chapter 4: Control Structures II
Chapter 5: Control Structures II
1 ICS103 Programming in C Lecture 7: Repetition Structures.
CONTROL STATEMENTS LOOPS. WHY IS REPETITION NEEDED?  There are many situations in which the same statements need to be executed several times.  Example:
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5: Looping.
Chapter 5: Repetition and Loop Statements By: Suraya Alias.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 5: Control Structures II (Repetition)
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.
CONTROL STRUCTURE Chapter 3. CONTROL STRUCTURES ONE-WAY SELECTION Syntax: if (expression) statement Expression referred to as decision maker. Statement.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
CISC105 – General Computer Science Class 4 – 06/14/2006.
1 ICS103 Programming in C Lecture 7: Repetition Structures.
PGT C Programming1 Week 4 – Repetition Structures / Loops.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Chapter 5: Control Structures II (Repetition)
CC213 Programming Applications Week #2 2 Control Structures Control structures –control the flow of execution in a program or function. Three basic control.
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 6: REPETITION AND LOOP STATEMENTS Learning outcomes  Define the concept of repetition structure.  Specify.
CHAPTER 4 REPETITION STRUCTURES 1 st Semester King Saud University College of Applied studies and Community Service CSC1101 By: Asma Alosaimi.
Chapter 4 Repetition Structures
REPETITION CONTROL STRUCTURE
CHAPTER 4 REPETITION CONTROL STRUCTURE / LOOPING
EKT120 COMPUTER PROGRAMMING
EKT150 INTRODUCTION TO COMPUTER PROGRAMMING
CHAPTER 6: REPETITION AND LOOP STATEMENTS
ICS103 Programming in C Lecture 7: Repetition Structures
Lecture 4 - Loops UniMAP EKT120 Sem 1 08/09.
Week 4 – Repetition Structures / Loops
Repetition-Sentinel,Flag Loop/Do_While
Control Structures Lecture 7.
Chapter 4 Repetition Structures
Looping.
Chapter 4 Repetition Structures
Repetition and Loop Statements
Control Statements Loops.
Repetition and Loop Statements
Control Statements Loops.
Chapter 4 Repetition Structures
ICS103: Programming in C 5: Repetition and Loop Statements
Presentation transcript:

CHAPTER 4 REPETITION STRUCTURES 1 st semester King Saud University College of Applied studies and Community Service Csc 1101 A.AlOsaimi

Overview 2  Repetition in Programs  Counting Loops  Using while statement  Using for statement Increment and Decrement Operators  Conditional Loops  Sentinel-Controlled loops  Flag-Controlled loop  Nested loop  Do-While loop  break and continue statement A.AlOsaimi

Types of Control Structures 3 A.AlOsaimi

What is Meant By Loops? Why We Need Them?  Loop Group of instructions computer executes repeatedly while some condition remains true  Why we need them? To repeat statements until a certain condition becomes false 4 A.AlOsaimi

Loop Statementes A.AlOsaimi 5  Loop statements are:  For loop  While loop  Do While loop Loop Counting loop For loop Counter- controlled while loop Conditional Loop Flag- Controlled while loop Sentinel- Controlled while loops

Loop Statements A.AlOsaimi 6 Repetition T F do … while statement T F while statement T F for statement while (condition) { … } for (initialize; condition; update) {.. } do {.. } while ( condition);

Counting Loop A.AlOsaimi 7  Definite repetition: know how many times loop will executeute  Control variable used to count repetitions Two type of Counting loop:  Counter-Controlled while loop  For loop

Counter–controlled while loop 8  The loop shown below in pseudo code is called a counter- controlled while loop because its repetition is managed by a loop control variable whose value represents a count. Set loop control variable to an initial value of 0 While loop control variable < final value... //Do something multiple times Increase loop control variable by 1. A.AlOsaimi

Counter–controlled while loop Example 1 A.AlOsaimi 9  This slide shows a program fragment that computes and displays the gross pay for seven employees. The loop body is the compound statements (those between { and }).  The loop repetition condition controls the while loop. count_emp = 0; while (count_emp < 7) { printf("Hours> "); scanf("%d",&hours); printf("Rate> "); scanf("%lf",&rate); pay = hours * rate; printf("Pay is $%6.2f\n", pay); count_emp = count_emp + 1; } printf("\nAll employees processed\n"); loop repetition condition

Counter–controlled while loop while Statement A.AlOsaimi 10  Syntax of the while Statement:  Initialization. i.e. count_emp = 0;  Testing(condition). i.e. count_emp < 7  Updating i.e. count_emp = count_emp + 1;  The above steps must be followed for every while loop.  If any of these are skipped it may produce an infinite loop

Counter–controlled while loop Example 2: Computing Sum  If we want to compute, we need to go  We can use a while loop. /* computes the sum: */ #include int main(void) { int sum =0, i = 1; while (i <= 100) { sum = sum + i; i = i + 1; } printf("Sum is %d\n", sum); return 0; } 11 A.AlOsaimi

The for loop 12  A better way to construct a counting loop is to use the for statement.  C provides the for statement as another form for implementing loops.  As before we need to  Initialize the loop control variable  Test the loop repetition condition  Update the loop control variable.  An important feature of the for statement in C is that it supplies a designated place for each of these three components. A.AlOsaimi

The for Repetition Statement 13 No semicolon ( ; ) after last expression A.AlOsaimi

General Form of for statement 14 for (initialize; test; update) { //Steps to perform each iteration }  First, the initialization expression is executed.  Then, the loop repetition condition is tested.  If the condition is true, the statement enclosed in { } are executed.  After that the update expression is evaluated.  Then the loop repetition condition is retested.  The statement is repeated as long as the condition is true.  For loop can be used to count up or down by any interval. A.AlOsaimi

for Example 1 15  To compute the sum of 1 to 100: int sum = 0; int i; for (i = 1; i <= 100; i++) { sum = sum + i; }  Note: i++ is the same as i = i + 1 and as i += 1. A.AlOsaimi

Example 2 – using while loop 16  Example: Print the number from 1 to A.AlOsaimi

Example 3– using for 17  Example: Print the number from 1 to A.AlOsaimi

Increment and Decrement Operators 18  The counting loops that we have seen have all included assignment expressions of the form counter = counter + 1 or counter++ or counter += 1  This will add 1 to the variable counter. If we use a - instead of a +, it will subtract 1 from the variable counter.  Be careful about using the ++ or -- options. A.AlOsaimi

Prefix and Postfix Increment/Decrement 19  The values of the expression in which the ++ operator is used depends on the position of the operator.  When the ++ operator is placed immediately in front of its operand (prefix increment, Ex: ++x ), the value of the expression is the variable’s value after incrementing.  When the ++ operator is placed immediately after the operand (postfix increment, Ex: x++ ), the value of the expression is the value of the variable before it is incremented. A.AlOsaimi

Comparison of Prefix and Postfix Increments 20 A.AlOsaimi

More on Prefix and Postfix Operator printf(“%3d”, --n); printf(“%3d”, n); printf(“%3d”, n--); printf(“%3d”, n); 21 If n = 4, what will be the output of the following? A.AlOsaimi

Conditional Loops 22  In many programming situations, we will not be able to determine the exact number of loop repetitions before loop execution begins.  Sentinel-Controlled loops  Flag-Controlled loop

Sentinel-Controlled while Loop 23  Used when exact number of entry pieces is unknown, but last entry (special/sentinel value) is known.  General form: Input the first data item into variable; while (variable != sentinel) {. input a data item into variable;. }

Sentinel-Controlled while Loop example1 24 temp = 1; printf("Enter a value, 0 will stop the program> "); scanf("%d",&value); while(value != 0) { temp = temp * value; printf("Enter a value, 0 will stop the program>"); scanf("%d",&value); } printf("The product is %d", temp);  It is very common for loops to have identical initialization and update steps while performing input operations where the number of input values is not known in advance. Initialization Testing Update

Sentinel-Controlled while Loop example2 25 /* Compute the sum of a list of exam scores. */ #include #define SENTINEL -99 int main(void) { int sum = 0, /* sum of scores input so far */ score; /* current score */ printf("Enter first score (or %d to quit)> ", SENTINEL); scanf("%d", &score ); while (score != SENTINEL) { sum += score; printf("Enter next score (%d to quit)> ", SENTINEL); scanf("%d", &score); } printf("\nSum of exam scores is %d\n", sum); system("pause"); return (0); }

Convert Sentinel Controlled while loop for loop 26  Because the for statement combines the initialization, test, and update in once place, some programmers prefer to use it to implement sentinel-controlled loops. printf("Enter first score (or %d to quit)> ", SENTINEL); for( scanf("%d",&score); score != SENTINEL; scanf("%d",&score)) { sum += score; printf("Enter next score (%d to quit)> ", SENTINEL); }

27 Flag-Controlled while Loop  int value used to control loop ( true 1 or false 0).  General form: int found = 0; while (!found) {. if (expression) found = 1;. }

28 Flag-Controlled while Loop- Example 1 /Flag-controlled while loop. //Guessing the number game. #include #include int main(void) { //declare the variables int num; //variable to store the random number int guess; //variable to store the number guessed by the user int done; //boolean variable to control the loop num = (int) (rand() % 100); don e = 0;

29 Flag-Controlled while Loop- Example 1 (continued) while (!done) { printf ("Enter an integer greater than or equal to 0 and less than 100: "); scanf("%d",& guess); printf("\n"); if (guess == num) { printf("You guessed the correct number."); done = 1; } else if (guess < num) printf("Your guess is lower than the number.\n Guess again!"); else printf("Your guess is higher than the number.\nGuess again!"); } //end while return(0); }

Nested Loops 30  Usually used to work with two dimensional arrays (later).  Nested loops consist of an outer loop with one or more inner loops.  Each time the outer loop is repeated, the inner loops are reentered  Their loop control expressions are reevaluated  All required iterations are performed again.

Example: Sum of Scores of 12 sections 31 /*calculate the total scores in each section for 12 sections. Each section's * scores are terminated by the sentinel -99. */ #include #define SENTINEL -99 #define NUM_SECTIONS 12 int main(void){ int sec, /* number of section being processed */ score, /* one score for this sec*/ sum; /* total scores so far for this section */ printf(“sum of scores for each section\n"); for (sec= 1 ; sec <= NUM_SECTIONS ; ++sec) { sum = 0; for (scanf("%d", &score); score != SENTINEL; scanf("%d", &score)) { sum += score; } printf(" Section %2d: %2d\n", sec, sum); } return (0);}

What is the Output? 32 /* * Illustrates a pair of nested counting loops */ #include int main(void) { int i, j; /* loop control variables */ printf(" I J\n"); for (i = 1; i < 4; ++i) { printf("Outer %6d\n", i); for (j = 0; j < i; ++j) { printf(" Inner%9d\n", j); } /* end of inner loop */ } /* end of outer loop */ return (0); } //output: I J Outer 1 Inner 0 Outer 2 Inner 0 Inner 1 Outer 3 Inner 0 Inner 1 Inner 2

do while statement 33  Both the for statement and the while statement evaluate the loop condition before the first execution of the loop body.  In most cases, this pretest is desirable and prevents the loop from executing when there may be no data items to process.  There are some situations, generally involving interactive input, when we know that a loop must execute at least one time.

do while Example1 34 #include #define KMS_PER_MILE /* converts miles to kilometers - repeateadly */ int main(void) { double kms, miles; char res; //for user response [y/n] do { printf("Enter the distance in miles> "); scanf("%lf", &miles); kms = KMS_PER_MILE * miles; printf("That equals %f kilometers. \n", kms); printf("\nDo you wish to try again [y/n]? "); scanf(“ %c", &res); } while (res == 'Y' || res == 'y'); return (0);}

do while Example2 35 #include int main () { // Another use of do-while is to check valid input int n_min, n_max, /* minimum and maximum values*/ inval; /* data value which user enters*/ // check validity of input. n_min must be < n_max do { printf("Enter minimum and maximum valid values> "); scanf("%d%d", &n_min, &n_max); if (n_min >= n_max) printf("Wrong input\n"); } while ( n_min >= n_max); // condition of while is true as long as the input is wrong

do while Example3 36 /* next do-while checks that the entered value is between n_min and n_max */ do { printf("Enter an integer between %d and %d inclusive> ", n_min, n_max); scanf("%d", &inval); if (inval n_max) printf("Sorry wrong input, try agin\n"); } while (inval n_max) ; printf("input checked successfully"); return 0; }

break Statements 37  Used to  exit early from a loop. ( while, for, and do... while)  skip remainder of switch structure.  Can be placed within if statement of a loop.  If condition is met, loop is exited immediately.  After the break statement executes, the program continues to execute with the first statement after the structure

break Statements 38 Example : int count ; for ( count = 1 ; count <= 10 ; count ++ ) {if ( count == 5) break ; printf( “ %d ”,count ); } Output

continue Statements 39  Used in while, for, and do... while structures.  When executed in a loop, the remaining statements in the loop are skipped; proceeds with the next iteration of the loop.  When executed in a while / do … while structure, expression is evaluated immediately after continue statement.  In a for structure, the update statement is executed after the continue statement; the loop condition then executes.

continue Statements 40 Example : int count ; for ( count = 1; count <= 10 ; count ++ ) {if ( count == 5) continue; printf( “%d ”,count ); } Output