A loop is a repetition control structure. body - statements to be repeated control statement - decides whether another repetition needs to be made leading.

Slides:



Advertisements
Similar presentations
LOOP / REPETITION while loop. for loop do/while loop We assume that loops are not meant to be infinite. That is, there should always be a way out of the.
Advertisements

Computer Science 1620 Loops.
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.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Sixth Edition Chapter 5: Looping by Tony.
A loop is a repetition control structure. it causes a single statement or block to be executed repeatedly What is a loop?
Chapter 6 - Repetition. Introduction u Many applications require certain operations to be carried out more than once. Such situations require repetition.
1 Lecture 15 Chapter 6 Looping Dale/Weems/Headington.
Switch structure Switch structure selects one from several alternatives depending on the value of the controlling expression. The controlling expression.
Chapter 5: Loops and Files.
1 Lecture 14 Chapter 6 Looping Dale/Weems/Headington.
Chapter 6 Looping Dale/Weems. 2 Chapter 6 Topics l While Statement Syntax l Count-Controlled Loops l Event-Controlled Loops l Using the End-of-File Condition.
1 Chapter 6 Looping Dale/Weems/Headington. 2 l Physical order vs. logical order l A loop is a repetition control structure based on a condition. l it.
Control Structures Control structures control the flow of program execution. 3 types of control structures: sequence, selection.
© 2004 Pearson Addison-Wesley. All rights reserved5-1 Iterations/ Loops The while Statement Other Repetition Statements.
An Object-Oriented Approach to Programming Logic and Design Chapter 6 Looping.
CS 1 Lesson 5 Loops and Files CS 1 -- John Cole.
1 Chapter 5 File Objects and Looping Statements (Some slides have been modified from their original format)
Section 3 - Selection and Repetition Constructs. Control Structures 1. Sequence 2. Selection 3. Repetition.
Chapter 6 Looping.
Chapter 4: Looping. Resource: Starting Out with C++, Third Edition, Tony Gaddis 5.1 The Increment and Decrement Operators ++ and -- are operators that.
1 What is a loop? A loop is a repetition control structure that causes a single statement or block to be executed repeatedly Loops.
CPS120 Introduction to Computer Science Iteration (Looping)
Quiz Answers 1. Show the output from the following code fragment: int a = 5, b = 2, c = 3; cout
Mr. Dave Clausen1 La Cañada High School Chapter 6: Repetition Statements.
 Wednesday, 9/18/02, Slide #1 CS106 Introduction to CS1 Wednesday, 9/18/02  QUESTIONS?? HW #1 due today at 5!!  Today: Loops, and two new data types.
Chapter 4 Loops Write code that prints out the numbers Very often, we want to repeat a (group of) statement(s). In C++, we have 3 major ways of.
Chapter 5 Loops. Overview u Loop Statement Syntax  Loop Statement Structure: while, for, do-while u Count-Controlled Loops u Nested Loops u Loop Testing.
C++ for Engineers and Scientists, Third Edition1 Objectives In this chapter, you will learn about: Basic loop structures while loops Interactive while.
Lecture 4 Looping. Building on the foundation Now that we know a little about  cout  cin  math operators  boolean operators  making decisions using.
Chapter 6 Looping CS185/09 - Introduction to Programming Caldwell College.
Chapter 6 Looping. 2 Chapter 6 Topics l While Statement Syntax l Count-Controlled Loops l Event-Controlled Loops l Using the End-of-File Condition to.
Program Flow Control - Looping Addis Ababa Institute of Technology Yared Semu April 2012.
1 Looping. 2 Chapter 6 Topics  While Statement Syntax  Phases of Loop Execution  Two Types of Loops: Count-Controlled Loops &Event-Controlled Loops.
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.
Control Structures Repetition or Iteration or Looping Part II.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 5 Looping.
+ Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy Walters, and Godfrey Muganda Chapter 5: Looping.
A loop is a repetition control structure. body - statements to be repeated control statement - decides whether another repetition needs to be made leading.
Control Structures RepetitionorIterationorLooping Part I.
Introduction to Loops Iteration Repetition Counting Loops Also known as.
CPS120 Introduction to Computer Science Iteration (Looping)
Repetition Statements (Loops) The do while Loop The last iteration structure in C++ is the do while loop. A do while loop repeats a statement or.
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.
A FIRST BOOK OF C++ CHAPTER 5 REPETITION. OBJECTIVES In this chapter, you will learn about: The while Statement Interactive while Loops The for Statement.
A First Book of C++ Chapter 5 Repetition.
Looping ROBERT REVAES. Logical Operators  && AND  Both have to be true for it to evaluate to be true.  || OR  One or the other has to be true for.
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.
1 Programming in C++ Dale/Weems/Headington Chapter 6 Looping.
Copyright 2006 Addison-Wesley Brief Version of Starting Out with C++ Chapter 5 Looping.
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.
1 Looping Chapter 6 2 Getting Looped in C++ Using flags to control a while statement Trapping for valid input Ending a loop with End Of File condition.
Sesi 0607EKT120/4 Computer Programming Week 5 – Repetition / Loops.
Chapter 6 Looping. 2 l A loop is a repetition control structure. l it causes a single statement or block to be executed repeatedly What is a loop?
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.
A loop is a repetition control structure. it causes a single statement or block to be executed repeatedly What is a loop?
REPETITION CONTROL STRUCTURE
Chapter 6 Looping.
Chapter 5: Looping Starting Out with C++ Early Objects Seventh Edition
Chapter 5: Looping Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley.
Lecture 4B More Repetition Richard Gesick
Iteration with While You can say that again.
Loops A loop is a repetition control structure.
Based on slides created by Bjarne Stroustrup & Tony Gaddis
Based on slides created by Bjarne Stroustrup & Tony Gaddis
Presentation transcript:

A loop is a repetition control structure. body - statements to be repeated control statement - decides whether another repetition needs to be made leading decision loop - control statement before body trailing decision loop - control statement after body Counted loop- for Logical loop – while or do..while Loops

loops2 Leading Decision prime the loop //START while (condition) //TEST { body of loop – //ACTION group of one or more statements indent one level //RESTART }

When the expression is tested and found to be false, the loop is exited and control passes to the statement which follows the loop body. while LOOP FALSE TRUE body statement Expression

loops for While Loops 1.Initial condition //START 2.TEST - while(…) 3.ACTION (steps needed to solve the problem) 4.RESTART (often the same as step 1)

loops5 Example cout <<"Do you want to play?(y/n)";//START cin >> ans; while ((ans == 'y') || (ans == 'Y'))//TEST { …//body//ACTION cout <<"Do you want to continue(y/n)?";//RESTART cin >> ans; } cout <<"Thanks for playing! " << endl;

loops6 Loops Sentinel controlled keep processing data until a special value is entered to indicate that processing should stop Read blood pressures until a special value (like -1) selected by you is read. Count Controlled keep processing data for a specified number of times Read 100 blood pressures. End-of-file Controlled keep processing data as long as there is more data in the file Read all the blood pressures from a file no matter how many are there Flag Controlled keep processing data while a flag condition is true Read blood pressures until a dangerously high BP (200 or more) is read.

A Sentinel-controlled Loop Read numbers until -1, 999 Not always easy to determine sentinel value requires a "priming read" "priming read" means you read one set of data before the while

loops Sentinel Value 1.Initial condition (START) Get first value 2.TEST - while(…) while (val != sentinel) 3.ACTION 4.RESTART- often the same as step 1 Get next value

// Sentinel controlled loop total = 0; cout << "Enter the price of the item (-1 to stop ) ";//START cin >> itemPrice; while (itemPrice > 0) // while not sentinelTEST { total = total + itemPrice; // ACTION cout <<"Enter item price(-1 to stop ) "; // RESTART cin >> itemPrice; } cout << total;

loops10 Example cin >> number; while (number < 0) { cout << "Enter positive values only! "; cin >> number; }

loops11 Reading from a file first open file (later) infile points to file (can be any name) infile >> fahrTemp; 1 infile >> cityName >> fahrTemp;

loops12 Reading from a file with a sentinel value infile >> fahrTemp; //read from a filestart while (fahrTemp != 999)//test { celsTemp = (5 * (fahrTemp – 32))/9 ; //action cout << fahrTemp << celsTemp; infile >>fahrTemp; //restart }

End-of-File Controlled Loop depends on fact that a file goes into fail state when you try to read a data value beyond the end of the file No trailer record while (there is a record) while (not end of file) while (infile) // this is c Computer indicates there are no more records by sending a signal to the program Must read record before entering loop – there may be no records

loops Reading from file 1.START : Read first record 2.TEST- while (infile) 3.ACTIONS 4.RESTART - Read next record- often the same as step 1

loops15 Example infile >> fahrTemp; //start while (infile) //test { celsTemp = (5 * (fahrTemp – 32))/9;//actions cout << fahrTemp <<celsTemp; infile >> fahrTemp;//restart }

//Open file total = 0; infile >> thisBP; // priming read Start while (infile) //test { total = total + thisBP; //action infile >> thisBP; // read another - restart loop } cout << total; // End-of-file controlled loop

Do something a set number of times Need counter –initialize –increment iteration counter - incremented during each iteration of the loop event counter - incremented each time a particular event occurs Count-controlled loop

loops Count 1.Start: Initialize counter 2.Test - while (counter < limit) 3.Actions 4.Restart: Increment counter

//Print Hello 10 times int count ; count = 0;//start while (count < 10)//test { cout << "Hello ";//action count = count + 1;//restart } Known Count

//Print Hello 10 times int count ; cout << "How many times should we print Hello?" cin >> count;1 while (count > 0) 2 { cout << "Hello ";3 count = count -1 ; 4 } variable count

loops21 Accumulators and Counters To find the average of a group of numbers-need running total and how many numbers Counter – storage area in which we count –Initialize: count = 0; –Increment: count = count + 1 or count++ Accumulator – storage area for keeping cumulative or running totals –Initialize: total = 0; –Update: total = total + number total_wages_paid = total_wages_paid + net_pay

Counter: initialize : count = 0; increment : count++;

Adding a Counter to a Sentinel-Controlled While Loop int count; count = 0; // initialize cin >> item; while (item != sentinel) { count++; // increment Process(item); cin >> item; }

Accumulator: Initialize: total = 0; Update: total = total + num;

total = 0; cin >> item; while (item != Sentinel) { total = total + item; cin >> item; } Adding a Running Total to a Sentinel- Controlled While Loop

int thisBP, total, count ; //Open file count = 0; // initialize 1 total = 0; infile >>thisBP ; while ( count < 100 && infile) 2 { total = total + thisBP ; 3 count= count + 1 infile >> thisBP;4 } cout << "The total = " << total << endl; if (count != 0) cout << "The average is " << (float)total/count ; 26

loops27 Infinite Loop index = 1; while (index < 5) cout << "Good Morning!“ << endl;

loops28 Never executed while (ans == "yes" ) { …. cout << “Add another number? "; cin >> answer; }

loops29 Don't forget to prime the loop! Initialize initial condition by reading in or setting value cin >> ans while (ans == 'y') index = 0 while (index < 10) infile >> name >> ssNum >>phone; //read record while (infile)

loops30 int count; float total, avg, num; total = 0; count = 0; infile >> num; while (infile) { total = total + num; count = count + 1; infile >> num; } if (count == 0) cout << "No numbers entered“ << endl; else { avg = total/count; cout << "The average is “ << avg << endl; }

Flag Controlled Loop countGoodReadings = 0; isDangerous = false; // initialize Boolean flag while (!isDangerous) //test { cin >> thisBP; //action if ( thisBP >= 200 ) isDangerous = true; // change flag value else countGoodReadings++; } cout << countGoodReadings << endl;

loops32 Trailing Decision Loop do { Body } while (condition); Test at the bottom Statements are executed at least once

loops33 Trailing decision loop Body condition TRUE FALSE

loops34 Example do { cout << "Enter two numbers“; cin >> num1 >>num2; cout <<num1 << " + " << num2 << " = " << num1+num2 << endl; cout << "Do you want to enter two numbers again? "; cin >> ans; } while (ans == "yes" );

do { DisplayMenu(); cin >> choice; switch (choice) { case 1: PlayBeginner(); break; case 2: PlayAdvBeginner(); break case 3: PlayIntermediate(); break case 4: break; default: cout << “ Invalid option” << endl; break; } } while (choice != 4);

loops36 Counted loop Fixed number of iterations Use a variable as a counter which starts at a specified number and increments the variable each time the loop is processed Repeats until the counter is greater than an ending number Beginning value, ending value, increment value

loops37 Counted Loop for (initial step; cond; expression) body (3) Automatic: 1.initial step: counter = initVal 2.Check cond: counter < finalVal 3. If true execute body, else exit 4. Expression: counter++ Back to 2

loops38 Examples for (count = 1; count <= 10; count++) cout <<"Hello“ << endl; for (count = 1; count <= 10; count++) cout << count << endl; for (num = 10; num > 0; num--) cout >>num cout << "Blast off“ << endl;

Nested Loops placing of one loop inside the body of another loop is called nesting. When you "nest" two loops, the outer loop takes control of the number of complete repetitions of the inner loop. All types of loops may be nested, the most commonly nested loops are for loops. When working with nested loops, the outer loop changes only after the inner loop is completely finished

NESTED LOOPS

Exercises: 1.Show screen output: for (outer = 0; outer < 2; outer++) { for (inner = 0; inner <=2; inner++) { cout<< outer<< '\t' << inner << '\n'; } } 2.Show screen output: for (outer = 0; outer < 3; outer++) { for(inner = 2; inner <=4; inner++) { cout<< inner << ' '; } cout<< '\n'; }

3. The following set of nested loops is NOT working. Can you find what is wrong?? for (ctr1 = 1; ctr1 <=10; ctr1++); { for(ctr2 = 1; ctr2 <=5; ctr2++) { number = ctr1 * ctr2; cout<< number << '\n'; } } 4. Show the output for the following program fragment: for (ctr1 = 8; ctr1 > 5; ctr1--) { for(ctr2 = 1; ctr2 < 3; ctr2++) { cout<<ctr1<<" "<<ctr2<<" "; } cout<<"\n"; } 5. Show the output: for(j=0; j<=5; j++) { for(k=1; k<=j; k++) { cout<<"&"; } cout<<"\n"; }

6. Write a program using nested loops to produce the following design: * ** *** **** ***** ****** 7. Write a program using nested loops to produce the following design: A AB ABC ABCD ABCDE ABCDEF 8. Write a program using nested loops to produce a rectangle of *'s with 6 rows and 20 *'s per row.