Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "Lecture 9: Making Decisions Final Section Professor: Dr. Miguel Alonso Jr. Fall 2008 CGS2423/COP1220."— Presentation transcript:

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

2 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

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

4 // 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; }

5 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

6 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

7 // 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; }

8 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

9 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

10 // 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; }

11 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; }

12 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

13 // 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; }

14 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

15 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; }

16 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

17 // 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; }

18 // 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; }


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

Similar presentations


Ads by Google