Lecture 4 - Loops UniMAP EKT120 Sem 1 08/09.

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

CS1061: C Programming Lecture 8: Repetition A. O’Riordan, 2004.
COMP 14 Introduction to Programming Miguel A. Otaduy May 20, 2004.
© 2004 Pearson Addison-Wesley. All rights reserved5-1 Iterations/ Loops The while Statement Other Repetition Statements.
Repetition (Loops) Want to do some repetitive sequence of actions: print vertical line of *s * Corresponding program: printf(“*\n”);
EGR 2261 Unit 5 Control Structures II: Repetition  Read Malik, Chapter 5.  Homework #5 and Lab #5 due next week.  Quiz next week.
Lecture 10: Reviews. Control Structures All C programs written in term of 3 control structures Sequence structures Programs executed sequentially by default.
Repetitive Structures BBS514 Structured Programming (Yapısal Programlama)1.
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.
Lecture 4: Calculating by Iterating. The while Repetition Statement Repetition structure Programmer specifies an action to be repeated while some condition.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Flow Control (for) Outline 4.1Introduction 4.2The.
+ 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;
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5: Looping.
Copyright © 2012 Pearson Education, Inc. Chapter 5: Loops.
Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 5 Looping.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
COMP Loop Statements Yi Hong May 21, 2015.
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.
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.
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.
ECE Application Programming
Chapter 4 – C Program Control
REPETITION CONTROL STRUCTURE
Chapter 5: Control Structures II (Repetition)
EKT120 COMPUTER PROGRAMMING
EKT150 INTRODUCTION TO COMPUTER PROGRAMMING
Chapter 5: Control Structures II
Lecture 7: Repeating a Known Number of Times
Chapter 5: Control Structures II
Chapter 5: Control Structures II
Chapter 4 - Program Control
Week 4 – Repetition Structures / Loops
Repetition-Counter control Loop
Chapter 2.2 Control Structures (Iteration)
Control Statements Kingdom of Saudi Arabia
Lecture 07 More Repetition Richard Gesick.
Chapter 5: Control Structures II
Lecture 4B More Repetition Richard Gesick
Loops CS140: Introduction to Computing 1 Savitch Chapter 4 Flow of Control: Loops 9/18/13 9/23/13.
Control Structures Lecture 7.
- Additional C Statements
Outline Altering flow of control Boolean expressions
Chapter 4 - Program Control
Control Statements Loops.
Chapter 2.2 Control Structures (Iteration)
Chapter 6: Repetition Statements
Repetition and Loop Statements
Let’s all Repeat Together
Chapter 5: Control Structures II (Repetition)
EPSII 59:006 Spring 2004.
More Loops Topics Counter-Controlled (Definite) Repetition
Dale Roberts, Lecturer IUPUI
Repetition Statements (Loops) - 2
Control Statements Loops.
Chapter 4 - Program Control
Based on slides created by Bjarne Stroustrup & Tony Gaddis
Based on slides created by Bjarne Stroustrup & Tony Gaddis
More Loops Topics Counter-Controlled (Definite) Repetition
The while Looping Structure
ICS103: Programming in C 5: Repetition and Loop Statements
More Loops Topics Counter-Controlled (Definite) Repetition
Presentation transcript:

Lecture 4 - Loops UniMAP EKT120 Sem 1 08/09

Outline Introduction While loops Do-while loops For loops Nested loops Three types of while loops Do-while loops For loops Nested loops UniMAP EKT120 Sem 1 08/09

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? UniMAP EKT120 Sem 1 08/09

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 UniMAP EKT120 Sem 1 08/09

The while loop structure The general form of the while statement is: while (expression) statement; The example of pseudocode statement for while statement: While there are more items on my shopping list Purchase next item 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 UniMAP EKT120 Sem 1 08/09

Flowchart of a while statement UniMAP EKT120 Sem 1 08/09

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 UniMAP EKT120 Sem 1 08/09

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) UniMAP EKT120 Sem 1 08/09

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 UniMAP EKT120 Sem 1 08/09

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“ UniMAP EKT120 Sem 1 08/09

Sentinel-Controlled while Loops-cont 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); 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 Sentinel value UniMAP EKT120 Sem 1 08/09

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 UniMAP EKT120 Sem 1 08/09

Flag-Controlled while Loops Uses a boolean variable to control the loop. Loop exit when expression is evaluated to false. Set to false bool found = false; while (!found) { printf(“Enter number between 1 and 200:”); scanf(%d”, &guess); if ((guess>= 88) &&(guess <=128)) {found = true; printf(“\nBINGO!”);} } 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 test condition decision structure Set to true UniMAP EKT120 Sem 1 08/09

Example (while statement) (i) Fix any error you may find: while (c < 5) { product * = c; ++c; (ii) What is wrong with the statements which is supposed to calculate the sum of integers from 1 to 100? while (z > = 0) { sum + = z; UniMAP EKT120 Sem 1 08/09

Example (while statement) What does the following program print? UniMAP EKT120 Sem 1 08/09

Example (while statement) Write a program that calculates the sum of integer from 1 to 10. Use the while statement. UniMAP EKT120 Sem 1 08/09

UniMAP EKT120 Sem 1 08/09

The do-while Repetition 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 );   UniMAP EKT120 Sem 1 08/09

Flowchart of a do-while structure true false action(s) condition UniMAP EKT120 Sem 1 08/09

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’) count-controlled   sentinel-controlled UniMAP EKT120 Sem 1 08/09

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 “, i); i = i + 5; } while (i <= 20); The output is: 0 5 10 15 20 UniMAP EKT120 Sem 1 08/09

The do-while Looping Structure (Example) Example: Consider the following two loops printf("%d “, i); printf("%d “, i); UniMAP EKT120 Sem 1 08/09

The do-while Looping Structure (Example) In (a), the while loop, produces nothing In (b) the do...while loop, outputs the number 11 UniMAP EKT120 Sem 1 08/09

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   UniMAP EKT120 Sem 1 08/09

The for Repetition Structure Example: For loops and while loops are equivalent: expression1; while (expression2 ) { statement; expression3; } for ( expression1; expression2 ; expression3) UniMAP EKT120 Sem 1 08/09

The for Repetition Structure 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 ); UniMAP EKT120 Sem 1 08/09

Flowchart of a for statement UniMAP EKT120 Sem 1 08/09

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 UniMAP EKT120 Sem 1 08/09

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’); UniMAP EKT120 Sem 1 08/09

Example (for statement) What is the program output for the following: UniMAP EKT120 Sem 1 08/09

Example (for statement) Write C codes for the following: Sum the odd integers between 1 and 99 using for statement. Assume the integer variable and sum have been defined. Write for statement that prints the following values in sequence: a) 1 2 3 4 5 6 7 b) 1 2 3 4 5 6 7 UniMAP EKT120 Sem 1 08/09

Example (for statement) What is the program output if number 3 and 4 are entered by user? UniMAP EKT120 Sem 1 08/09

Example (for statement) (i) Write a program that calculates and prints the sum of the even integers from 2 to 30 UniMAP EKT120 Sem 1 08/09

Example (for statement) (ii) Write a program that reads five integers. For each integer read, your program should print a line containing the amount of symbol *. UniMAP EKT120 Sem 1 08/09

End Lecture 4 - Loops Q & A! UniMAP EKT120 Sem 1 08/09