Week 4 – Repetition Structures / Loops

Slides:



Advertisements
Similar presentations
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.
Advertisements

COMP 14 Introduction to Programming Miguel A. Otaduy May 20, 2004.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 4 - Program Control Outline 4.1Introduction 4.2The Essentials of Repetition 4.3Counter-Controlled.
© 2004 Pearson Addison-Wesley. All rights reserved5-1 Iterations/ Loops The while Statement Other Repetition Statements.
EGR 2261 Unit 5 Control Structures II: Repetition  Read Malik, Chapter 5.  Homework #5 and Lab #5 due next week.  Quiz next week.
 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 4 - Program Control Outline 4.1Introduction 4.2The Essentials of Repetition 4.3Counter-Controlled.
Lecture 10: Reviews. Control Structures All C programs written in term of 3 control structures Sequence structures Programs executed sequentially by default.
Control Structures Week Introduction -Representation of the theory and principles of structured programming. Demonstration of for, while,do…whil.
Repetitive Structures BBS514 Structured Programming (Yapısal Programlama)1.
C++ Programming Lecture 6 Control Structure II (Repetition) By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department.
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.
Loop.  While Loop  Do-while Loop  For Loop Continue Statement Conclusion Loop Loop.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Flow Control (for) Outline 4.1Introduction 4.2The.
Chapter 3 - Structured Program Development Outline 3.1Introduction 3.2Algorithms 3.3Pseudocode 3.4Control Structures 3.5The If Selection Structure 3.6The.
C Programming Lecture 7 : Control Structures. Control Structures Conditional statement : if, switch Determine a block of statements to execute depending.
+ Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy Walters, and Godfrey Muganda Chapter 5: Looping.
 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 4 - Program Control Outline 4.1Introduction 4.2The Essentials of Repetition 4.3Counter-Controlled.
CSCI 171 Presentation 5. The while loop Executes a block as long as the condition is true general form: while (condition) { statement 1; statement 2;
Think Possibility 1 Iterative Constructs ITERATION / LOOPS C provides three loop structures: the for-loop, the while-loop, and the do-while-loop. Each.
Copyright © 2012 Pearson Education, Inc. Chapter 5: Loops.
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.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
LECTURE # 8 : REPETITION STATEMENTS By Mr. Ali Edan.
PGT C Programming1 Week 4 – Repetition Structures / Loops.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
Chapter 4 Repetition Statements Program Development and Design Using C++, Third Edition.
Sesi 0607EKT120/4 Computer Programming Week 5 – Repetition / Loops.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 3 - Structured Program Development Outline.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Flow Control (while) Outline 3.7The While Repetition.
Week 3.  TO PRINT NUMBERS FROM 1 TO 20  TO PRINT EVEN NUMBERS FROM 1 TO 20 2.
Introduction to Loop. Introduction to Loops: The while Loop Loop: part of program that may execute > 1 time (i.e., it repeats) while loop format: while.
CHAPTER 2.2 CONTROL STRUCTURES (ITERATION) Dr. Shady Yehia Elmashad.
Chapter 4 – C Program Control
Algorithm: procedure in terms of
REPETITION CONTROL STRUCTURE
while Repetition Structure
Chapter 5: Control Structures II (Repetition)
EKT120 COMPUTER PROGRAMMING
EKT150 INTRODUCTION TO COMPUTER PROGRAMMING
- Standard C Statements
Lecture 7: Repeating a Known Number of Times
Chapter 4 - Program Control
Lecture 4 - Loops UniMAP EKT120 Sem 1 08/09.
Chapter 2.2 Control Structures (Iteration)
Control Statements Kingdom of Saudi Arabia
Control Structures Lecture 7.
- Additional C Statements
Outline Altering flow of control Boolean expressions
Structured Program
Chapter 4 - Program Control
Chapter 3 - Structured Program Development
The while Looping Structure
Chapter 3 - Structured Program Development
Repetition and Loop Statements
Week 6 CPS125.
Let’s all Repeat Together
EPSII 59:006 Spring 2004.
More Loops Topics Counter-Controlled (Definite) Repetition
Dale Roberts, Lecturer IUPUI
Repetition Statements (Loops) - 2
Chapter 4 - Program Control
Based on slides created by Bjarne Stroustrup & Tony Gaddis
More Loops Topics Counter-Controlled (Definite) Repetition
Dale Roberts, Lecturer IUPUI
Dale Roberts, Lecturer IUPUI
The while Looping Structure
ICS103: Programming in C 5: Repetition and Loop Statements
More Loops Topics Counter-Controlled (Definite) Repetition
Presentation transcript:

Week 4 – Repetition Structures / Loops EKT 150 SEM 1 10/11

Outline Introduction While loops Do-while loops For loops Nested loops Three types of while loops Do-while loops For loops Nested loops EKT 120 SEM II 09/10

Outline Introduction While loops Do-while loops For loops Nested loops Three types of while loops Do-while loops For loops Nested loops

Why Need Loops ? Suppose we want to add five numbers and find the average. From what you have learned so far, you could proceed as follows scanf(“%d %d %d %d %d”, &num1, &num2, &num3, &num4,&num5); sum = num1 + num2 + num3 + num4 + num5; average = sum / 5; If 100 numbers, 1000 numbers?

Repetition (Loop)‏ Used to control the flow of a program Loops are basically repetitions or iterations used to repeat a segment of code Three statements can be used to implement loops in C while statement do-while statement for statement while and for statements are similar in implementation, but have different syntax The do-while statement is different - the following code is executed at least once

The while loop structure The general form of the while statement is: while (expression)‏ statement; To avoid an infinite loop, make sure that the loop’s body contains statement (s) that assure that the exit condition i.e. the expression in the while statement will eventually be false. while loop repeated until condition becomes false

Flowchart of a while statement

The while loop structure-cont There are basically three types of while loops: Counter-controlled while loop Sentinel-controlled while loop Flag-controlled while loop

Counter-Controlled while Loops Definite repetition: know how many times loop will execute Control variable used to count repetitions Example: int counter = 1; // declare and initialize while ( counter <= 10 ) // test condition { printf( "%d\n", counter ); ++counter; // update } Requirement: 1. Declare and initialize control variable value (or loop counter)‏ 2. A condition that tests for the final value of the control variable (i.e., whether looping should continue)‏ 3. Update control variable (incr/decr)‏

Counter-Controlled while Loops Another example: int product = 2; while ( product <= 1000 ) product = 2 * product; declare and initialize test condition increment product <= 1000 product = 2 * product true false

Example: A class of ten students took a quiz Example: A class of ten students took a quiz. The grades (integers in the range 0 to 100) for this quiz are available to you. Determine the class average on the quiz Pseudocode: Set total to zero Set grade counter to one While grade counter is less than or equal to ten Input the next grade Add the grade into the total Add one to the grade counter Set the class average to the total divided by ten Print the class average

1. Initialize Variables 2. Execute Loop 3. Output results 1 /* Fig. 3.6: fig03_06.c 2 Class average program with 3 counter-controlled repetition */ 4 #include <stdio.h> 5 6 int main()‏ 7 { 8 int counter, grade, total, average; 9 10 /* initialization phase */ 11 total = 0; 12 counter = 1; 13 14 /* processing phase */ 15 while ( counter <= 10 ) { 16 printf( "Enter grade: " ); 17 scanf( "%d", &grade ); 18 total = total + grade; 19 counter = counter + 1; 20 } 21 22 /* termination phase */ 23 average = total / 10; 24 printf( "Class average is %d\n", average ); 25 26 return 0; /* indicate program ended successfully */ 27 } 1. Initialize Variables 2. Execute Loop 3. Output results OUTPUT Enter grade: 98 Enter grade: 76 Enter grade: 71 Enter grade: 87 Enter grade: 83 Enter grade: 90 Enter grade: 57 Enter grade: 79 Enter grade: 82 Enter grade: 94 Class average is 81

Sentinel-Controlled while Loops Indefinite repetition Used when number of repetitions not known and loop needs to input value repeatedly for each iteration Sentinel value indicates "end of data“

Sentinel-Controlled while Loops-cont Requirement: 1. Read control variable value before enter loop 2. A condition that tests control variable’s validity (i.e., whether looping should continue)‏ 3. Read again control variable before end of loop Example: int number, count, sum; printf(“To stop enter -999. Enter positive numbers : " ); scanf(“%d”, &number); while (number != -999)‏ { sum = sum + number; //find sum of numbers entered count++; //count how many numbers entered } printf(“\nThe sum of %d numbers is %d“, count, sum); Sentinel value

Sentinel-Controlled while Loops-cont Another example: char choice; printf(“Continue?y-yes n-no :”); scanf(“%c”, &choice); while ( choice == ‘y’)‏ { printf(“\nEnter grade point:”); scanf(“%f”, &grade_pt); if(grade_pt > 2.0)‏ printf(“\nPass); } read control variable test condition read again

1. Initialize Variables 2. Get user input 2.1 Perform Loop 1 /* Fig. 3.8: fig03_08.c 2 Class average program with 3 sentinel-controlled repetition */ 4 #include <stdio.h> 5 6 int main()‏ 7 { 8 float average,total; /* new data type */ 9 int counter, grade,; 10 11 /* initialization phase */ 12 total = 0; 13 counter = 0; 14 15 /* processing phase */ 16 printf( "Enter grade, -1 to end: " ); 17 scanf( "%d", &grade ); 18 19 while ( grade != -1 ) { 20 total = total + grade; 21 counter = counter + 1; 22 printf( "Enter grade, -1 to end: " ); 23 scanf( "%d", &grade ); 24 } 1. Initialize Variables 2. Get user input 2.1 Perform Loop

3. Calculate Average 3.1 Print Results Program Output 25 26 /* termination phase */ 27 if ( counter != 0 ) { 28 average = total / counter; 29 printf( "Class average is %.2f", average ); 30 } 31 else 32 printf( "No grades were entered\n" ); 33 34 return 0; /* indicate program ended successfully */ 35 } 3. Calculate Average 3.1 Print Results Program Output Enter grade, -1 to end: 75 Enter grade, -1 to end: 94 Enter grade, -1 to end: 97 Enter grade, -1 to end: 88 Enter grade, -1 to end: 70 Enter grade, -1 to end: 64 Enter grade, -1 to end: 83 Enter grade, -1 to end: 89 Enter grade, -1 to end: -1 Class average is 82.50

Flag-Controlled while Loops Uses a boolean variable to control the loop. Loop exit when expression is evaluated to false. Set to false Requirement: 1. Set control variable to false before loop 2. A condition that tests control variable. If expr evaluated to true, loop continue 3. A decision structure to test value validity 4. Set control variable to true to indicate found bool found = false; while (!found) { printf(“Enter number between 1 and 200:”); scanf(%d”, &guess); if ((guess>= 88) &&(guess <=128))‏ {found = true; printf(“\nBINGO!”);} } test condition Decision structure Set to true

The do-while Repetition Structure Similar to the while structure Condition for repetition tested after the body of the loop is performed All actions are performed at least once Expression can be written as count-controlled or sentinel-controlled Format: do { statement; } while ( condition );  

Flowchart of a do-while structure true false action(s)‏ condition

The do-while Repetition Structure Example : prints the integers from 1 to 10 int counter = 1; do { printf( "%d ", counter ); } while (++counter <= 10); Another example: do{ printf(“\nEnter grade point:”); scanf(“%f”, &grade_pt); if(grade_pt > 2.0)‏ printf(“\nPass); printf(“Continue?y-yes n-no :”); scanf(“%c”, &choice); }while ( choice == ‘y’)‏ counter-controlled   sentinel-controlled

The do-while Repetition Structure To avoid an infinite loop, make sure that the loop body contains a statement that ultimately makes the expression false and assures that it exits Another example: int i = 0; do { printf(“%d\t”,i); i = i + 5; } while (i <= 20); The output is: 0 5 10 15 20

The do-while Looping Structure (Example)‏ Example: Consider the following two loops a) i=11; while(i<=10); { printf(“%d”,i); i=i+5; } b) i=11; do { printf(“%d”,i); i=i+5; } while(i<=10);

The do-while Looping Structure (Example)‏ In (a), the while loop, produces nothing In (b) the do...while loop, outputs the number 11

The for Repetition Structure Format when using for loops for ( initialization; loopContinuationTest; increment statement)‏ Use for loops when already know how many times to repeat Example: for(counter = 1; counter <= 10;counter++ )‏ printf( "%d\n", counter ); Prints the integers from one to ten  

The for Repetition Structure For loops can usually be rewritten as while loops: initialization; while ( loopContinuationTest ) { statement; increment statement; } Initialization and increment Can be comma-separated lists Example: for (int i = 0, j = 0; j + i <= 10; j++, i++)‏ printf( "%d\n", j + i );

Flow of a for statement

Nested loop Loop within a loop Inner loop is performed first E.g. for(i=1;i<4;i++){ for(j=1;j<5;j++)‏ printf(“%d”, j); printf(“\n”);} Output 1234

Nested loop Another example: Program find and print avg of three test scores, then asks whether want to continue do{ for(count=0; count <3;count++)‏ { printf(“\nEnter test marks:”); scanf(“%d”, marks); total=total+marks; } avg=total/count; printf(“\nAverage:%5.2f”, avg); printf(“\nContinue?”); scanf(“%c”, &choice); }while(choice == ‘y’);

End Week 4- Loops Q & A!