Lecture 9: Making Decisions Final Section Professor: Dr. Miguel Alonso Jr. Fall 2008 CGS2423/COP1220.

Slides:



Advertisements
Similar presentations
Computer Science 1620 Loops.
Advertisements

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.
Starting Out with C++, 3 rd Edition 1 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.
1 10/20/08CS150 Introduction to Computer Science 1 do/while and Nested Loops Section 5.5 & 5.11.
1 10/11/06CS150 Introduction to Computer Science 1 do/while and Nested Loops.
Chapter 5: Loops and Files.
Summary of Loops Programming. COMP102 Prog Fundamentals I: Summary of Loops /Slide 2 Which Loop to Use? l for loop n for calculations that are repeated.
CS 1 Lesson 5 Loops and Files CS 1 -- John Cole.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Brief Edition Chapter 5 Looping.
CHAPTER 5 CONTROL STRUCTURES II (Repetition). In this chapter, you will:  Learn about repetition (looping) control structures  Explore how to construct.
REPETITION STRUCTURES. Topics Introduction to Repetition Structures The while Loop: a Condition- Controlled Loop The for Loop: a Count-Controlled Loop.
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.
Chapter 4: Looping. Resource: Starting Out with C++, Third Edition, Tony Gaddis 5.1 The Increment and Decrement Operators ++ and -- are operators that.
Chapter 4: Loops and Files. The Increment and Decrement Operators  There are numerous times where a variable must simply be incremented or decremented.
Chapter 5: Control Structures II (Repetition). Objectives In this chapter, you will: – Learn about repetition (looping) control structures – Learn how.
Chapter 7 Additional Control Structures. 2 2 void GetYesOrNo (/* out */ char& response) // Inputs a character from the user // Postcondition: response.
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.
Program Flow Control - Looping Addis Ababa Institute of Technology Yared Semu April 2012.
Control Structures Repetition or Iteration or Looping Part II.
Lecture 8: Making Decisions Professor: Dr. Miguel Alonso Jr. Fall 2008 CGS2423/COP1220.
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.
Lecture 7: Making Decisions Professor: Dr. Miguel Alonso Jr. Fall 2008 CGS2423/COP1220.
Control Structures RepetitionorIterationorLooping Part I.
Lecture 9: Making Decisions Final Section Professor: Dr. Miguel Alonso Jr. Fall 2008 CGS2423/COP1220.
Introduction to Loops Iteration Repetition Counting Loops Also known as.
Before we get started…. First, a few things… Weighted Grading System Programming Style Submitting your assignments… The char and string variable types.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Programming Logic & Design Second Edition by Tony Gaddis.
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.
Starting Out with C++: From Control Structures through Objects
Copyright © 2012 Pearson Education, Inc. Chapter 5: Loops.
Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 5 Looping.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 5: Control Structures II (Repetition)
CS102 Introduction to Computer Programming Chapter 5 Looping.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
Copyright 2006 Addison-Wesley Brief Version of Starting Out with C++ Chapter 5 Looping.
Chapter 5: Loops. Slide 5- 2 Outline Increment and Decrement while loop do-while loop for loop.
CS0007: Introduction to Computer Programming The for Loop, Accumulator Variables, Seninel Values, and The Random Class.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
Lecture 7 – Repetition (Loop) FTMK, UTeM – Sem /2014.
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. CSC 110 – INTRO TO COMPUTING - PROGRAMMING For Loop.
Chapter 4 Repetition Statements Program Development and Design Using C++, Third Edition.
Starting Out with C++, 3 rd Edition 1 Chapter 5. Looping.
Computer Programming -1-
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.
Control Structures Repetition or Iteration or Looping Part II.
Chapter 4 Repetition Structures
REPETITION CONTROL STRUCTURE
Review If you want to display a floating-point number in a particular format use The DecimalFormat Class printf A loop is… a control structure that causes.
Chapter 5. Looping.
Chapter 5: Repetition Structures
Chapter 5: Looping Starting Out with C++ Early Objects Seventh Edition
Chapter 5: Looping Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley.
TOPIC 4: REPETITION CONTROL STRUCTURE
Alternate Version of STARTING OUT WITH C++ 4th Edition
Chapter 5. Looping.
Chapter 6: Repetition Structures
Chapter 5: Repetition Structures
Chapter 4: Loops and Files
Let’s all Repeat Together
Objectives You should be able to describe: The while Statement
Based on slides created by Bjarne Stroustrup & Tony Gaddis
Based on slides created by Bjarne Stroustrup & Tony Gaddis
Presentation transcript:

Lecture 9: Making Decisions Final Section Professor: Dr. Miguel Alonso Jr. Fall 2008 CGS2423/COP1220

The for loop The for loop is perfect for performing a known number of iterations Two types: Conditional while, do-while Count-controlled For Count controlled posses three elements It must initialize a counter variable It must test the counter by comparing it to a max for termination It must update the counter during each iteration

for(initialization; test; update) statement; for(initialization; test; update) { statement; // as many as you //need }

// This program demonstrates a user controlled for loop. #include using namespace std; int main() { int num; // Loop counter variable int maxValue; // Maximum value to display // Get the maximum value to display. cout << "I will display a table of numbers and\n"; cout << "their squares. How high should I go? "; cin >> maxValue; cout << "\nNumber Number Squared\n"; cout << " \n"; for (num = 1; num <= maxValue; num++) cout << num << "\t\t" << (num * num) << endl; return 0; }

Using the for loop instead of while or do-while Use the for loop when situation that requires initialization uses a false condition to stop the loop requires an update to occur at the end of each iteration

Tips for for!!! For is a pretest loop! Avoid modifying the counter variable in the body of the loop Other forms of the update for(num=2; num<=100; num+=2) for(num=10; num>=0; num--) Defining a variable in the for statement for(int num=2; num<=100; num+=2) User Controlled loop

// This program demonstrates a user controlled for loop. #include using namespace std; int main() { int num; // Loop counter variable int maxValue; // Maximum value to display // Get the maximum value to display. cout << "I will display a table of numbers and\n"; cout << "their squares. How high should I go? "; cin >> maxValue; cout << "\nNumber Number Squared\n"; cout << " \n"; for (num = 1; num <= maxValue; num++) cout << num << "\t\t" << (num * num) << endl; return 0; }

Using multiple statements in the initialization and update for(x = 1, y = 1; x <=5; x++, y++) Omitting the for loop’s expressions for(; x <=5; x++) for(; x <=5;) Class practice: In the spotlight pg 279

Keeping a running total A running total is a sum of numbers that accumulates with each iteration of a loop. The variable used to keep the running total is a called an accumulator

// This program takes daily sales figures over a period of time // and calculates their total. #include using namespace std; int main() { int days; // Number of days double total = 0.0; // Accumulator, initialized with 0 // Get the number of days. cout << "For how many days do you have sales figures? "; cin >> days; // Get the sales for each day and accumulate a total. for (int count = 1; count <= days; count++) { double sales; cout << "Enter the sales for day " << count << ": "; cin >> sales; total += sales; // Accumulate the running total. } // Display the total sales. cout << fixed << showpoint << setprecision(2); cout << "The total sales are $" << total << endl; return 0; }

Sentinels A sentinel is a special value that marks the end of a list of values It cannot be mistaken as a member of the list // This program calculates the total number of points a // soccer team has earned over a series of games. The user // enters a series of point values, then -1 when finished. #include using namespace std; int main() { int game = 1, // Game counter points, // To hold a number of points total = 0; // Accumulator cout << "Enter the number of points your team has earned\n"; cout << "so far in the season, then enter -1 when finished.\n\n"; cout << "Enter the points for game " << game << ": "; cin >> points; while (points != -1) { total += points; game++; cout << "Enter the points for game " << game << ": "; cin >> points; } cout << "\nThe total points are " << total << endl; return 0; }

Using a loop to read data from a file When reading a value from a file with the stream extraction operator, the operator returns a true or false value indicating whether the value was successfully read This can be used to detect when the end of the a file has been reached

// This program displays five numbers in a file. #include using namespace std; int main() { ifstream inputFile; // File stream object int number; // To hold a value from the file int count = 1; // Loop counter, initialized with 1 inputFile.open("numbers.txt"); // Open the file. if (!inputFile) // Test for errors. cout << "Error opening file.\n"; else { while (count <= 5) { inputFile >> number; // Read a number. cout << number << endl; // Display the number. count++; // Increment the counter. } inputFile.close(); // Close the file. } return 0; } // This program displays all of the numbers in a file. #include using namespace std; int main() { ifstream inputFile; // File stream object int number; // To hold a value from the file inputFile.open("numbers.txt"); // Open the file. if (!inputFile) // Test for errors. cout << "Error opening file.\n"; else { while (inputFile >> number) // Read a number { cout << number << endl; // Display the number. } inputFile.close(); // Close the file. } return 0; }

Deciding which loop to use Although most repetitive algorithms can be written with any of the three types of loops, each works best in different situations While Conditional loop; good for validation and when iteration if true (pretest loop) Do-while Conditional: good for situations when you want to loop at least once ( posttest loop) For loop: Pretest loop; built in initialization, testing, and update Good for counting type iterations and when the exact number of iterations is known

Nested Loops Loop inside another loop // This program averages test scores. It asks the user for the // number of students and the number of test scores per student. #include using namespace std; int main() { int numStudents, // Number of students numTests; // Number of test per student double total, // Accumulator for total scores average; // Average test score // Set up numeric output formatting. cout << fixed << showpoint << setprecision(1); // Get the number of students. cout << "This program averages test scores.\n"; cout << "For how many students do you have scores? "; cin >> numStudents; // Get the number of test scores per student. cout << "How many test scores does each student have? "; cin >> numTests; // Determine each student's average score. for (int student = 1; student <= numStudents; student++) { total = 0; // Initialize the accumulator. for (int test = 1; test <= numTests; test++) { double score; cout << "Enter score " << test << " for "; cout << "student " << student << ": "; cin >> score; total += score; } average = total / numTests; cout << "The average score for student " << student; cout << " is " << average << ".\n\n"; } return 0; }

Break and Continue Break: causes a loop to terminate early Be careful! It bypasses the loop termination condition Tough to debug and understand Break only interrupts the loop it is in Continue: causes a loop to stop its current iteration and begin the next one

// This program raises the user's number to the powers // of 0 through 10. #include using namespace std; int main() { int value; char choice; cout << "Enter a number: "; cin >> value; cout << "This program will raise " << value; cout << " to the powers of 0 through 10.\n"; for (int count = 0; count <= 10; count++) { cout << value << " raised to the power of "; cout << count << " is " << pow(value, count); cout << "\nEnter Q to quit or any other key "; cout << "to continue. "; cin >> choice; if (choice == 'Q' || choice == 'q') break; } return 0; }

// This program calculates the charges for DVD rentals. // Every third DVD is free. #include using namespace std; int main() { int dvdCount = 1; // DVD counter int numDVDs; // Number of DVDs rented double total = 0.0; // Accumulator char current; // Current release, Y or N // Get the number of DVDs. cout << "How many DVDs are being rented? "; cin >> numDVDs; // Determine the charges. do { if ((dvdCount % 3) == 0) { cout << "DVD #" << dvdCount << " is free!\n"; continue; // Immediately start the next iteration } cout << "Is DVD #" << dvdCount; cout << " a current release? (Y/N) "; cin >> current; if (current == 'Y' || current == 'y') total += 3.50; else total += 2.50; } while (dvdCount++ < numDVDs); // Display the total. cout << fixed << showpoint << setprecision(2); cout << "The total is $" << total << endl; return 0; }