1 / 56

Chapter 6

Chapter 6. Looping. Example: MAX of three numbers. int num1, num2, num3, max; cin >> num1 >> num2 >> num3; if ( num1 > num2 ) if ( num1 > num3 ) max = num1; else max = num3; else if ( num2 > num3 ) max = num2; else max = num3;

aileen
Download Presentation

Chapter 6

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Chapter 6 Looping

  2. Example: MAX of three numbers int num1, num2, num3, max; cin >> num1 >> num2 >> num3; if ( num1 > num2 ) if ( num1 > num3 ) max = num1; else max = num3; else if ( num2 > num3 ) max = num2; else max = num3; cout << “The max value is ” << max << endl; max = num1; if ( num2 > max ) max = num2; if ( num3 > max ) max = num3; How about finding the MAX of n number?

  3. Example: MAX of n numbers int num, max; cin >> num; • max = num; while ( num != -1 ) { if ( num > max ) max = num; cin >> num; } cout << “The max value is ” << max << endl; return 0; • pseudo-code: • read 1st number • max = 1st number • while not the end read a number if the new number is larger than max, then max = new number • How do we know it is the end? • use -1 to indicate the end. • What if the first input is -1? if ( num == -1 ) { cout << “No input!”; return 0; }

  4. Loop Control Variable (LCV) • when to exit a loop • avoid infinite loops • LCV: num • cin >> num; • max = num; while ( num != -1 ) { if ( num > max ) max = num; cin >> num; }

  5. Four parts of a loop • Loop initialization • LCV and others • Testing LCV • Loop Body • do the work • LCV update • cin >> num; • max = num; while ( num != -1 ) { if ( num > max ) max = num; cin >> num; }

  6. While Loop Initialization (LCV and others) while (LogicalExpression) (Testing LCV) false true Do Work Update LCV Statement after loop

  7. Example: MAX of n numbers within [0,50] const int LOW_BOUND = 0; const int UP_BOUND = 50; const int END_VALUE = -1; int num, max; cin >> num; if ( num == END_VALUE ) { cout << “No input!”; return 0; } • max = num; while ( num != END_VALUE ) { if ( num >= LOW_BOUND && num <= UP_BOUND ) if ( num > max ) max = num; else cout << “Out of range!” << endl; cin >> num; } cout << “The max value is ” << max << endl; return 0; Is this correct? else is paired with the closest if. { }

  8. Getting Valid Values Pseudo Code Input a value While the input value is out of range Display a message Input a new value cin >> score; while ( score < 0 || score > 50 ) cout << “Invalid score!”; cin >> score; //Correct?

  9. Getting Valid Values Pseudo Code Input a value While the input value is out of range Display a message Input a value cin >> score; while ( score < 0 || score > 50 ) { cout << “Invalid score!”; cin >> score; } //How about the end value -1?

  10. Getting Valid Values Pseudo Code Input a value While the input value is out of range and not -1 Display a message Input a value cin >> score; while ( ( score < 0 || score > 50) && score != -1 ) { cout << “Invalid score!”; cin >> score; } // Can we have while (score < 0 || score > 50 && score != -1) // NO! It’s the same as the following: while (score < 0 || (score > 50 && score != -1))

  11. Getting Valid Scores const int LOW_BOUND = 0; const int UP_BOUND = 50; const int END_VALUE = -1; int num, max; cin >> num; • while ((num < LOW_BOUND || num > UP_BOUND) && num!= END_VALUE) • { • cout << “Invalid number!” << endl; • cin >> num; • } • if ( num == END_VALUE ) { cout << “No input!” << endl; return 0; } • max = num; while ( num != -1 ) { if ( num > max ) max = num; cin >> num; while ( num != END_VALUE && (num < LOW_BOUND|| num > UP_BOUND)) { cout << “Invalid number!” << endl; cin >> num; } } cout << “The max value is ” << max << endl; return 0;

  12. Three Types of Loops • Sentinel-controlled loop • the loop stops when LCV become certain value. while ( LCV != END_VALUE ) • Count-controlled loop • the loop executes LIMIT times. while ( count <= LIMIT ) • End-of-file-controlled loop • the loops stops when reaching the end of the input file. while ( !cin.eof() )

  13. AVERAGE of 10 numbers Pseudo Code While count is not 10 yet input a number add the number to total increase count by 1 average = total / count

  14. AVERAGE of 10 numbers const int LIMIT = 10; int main() { float num, total = 0, average; int count = 0; cout << "Please input " << LIMIT << " numbers: " << endl; while ( count < LIMIT ) { cin >> num; total += num; // total = total + num; count ++; // count = count + 1; } average = total / count; cout << "The average is " << average << "." << endl; return 0; }

  15. AVERAGE of 10 numbers const int LIMIT = 10; int main() { float num, total = 0, average; int count; cout << "Please input " << LIMIT << " numbers: " << endl; cin >> num; count = 1; while ( count < LIMIT ) { total += num; cin >> num; count ++; } average = total / count; cout << "The average is " << average << "." << endl; return 0; } How about this design? Wrong! sum 9 numbers / 10 How to fix it?

  16. AVERAGE of 10 numbers const int LIMIT = 10; int main() { float num, total = 0, average; int count; cout << "Please input " << LIMIT << " numbers: " << endl; cin >> num; count = 0; while ( count < LIMIT ) { total += num; cin >> num; count ++; } average = total / count; cout << "The average is " << average << "." << endl; return 0; } How about this design? Correct answer, but extra input! How to fix it?

  17. AVERAGE of 10 numbers const int LIMIT = 10; int main() { float num, total = 0, average; int count; cout << "Please input " << LIMIT << " numbers: " << endl; cin >> num; count = 0; while ( count < LIMIT ) { total += num; count ++; if ( count != LIMIT ) cin >> num; } average = total / count; cout << "The average is " << average << "." << endl; return 0; } How about this design? Correct! Carefully check the final status when designing loops!

  18. More Arithmetic Operators validCount ++; // validCount = validCount + 1; totalCount --; // totalCount = totalCount - 1; total += score; // total = total + score; total -= score; // total = total - score; yValue /= xValue; // yValue = yValue / xValue; yValue %= xValue; // yValue = yValue % xValue; yValue *= xValue; // yValue = yValue * xValue;

  19. Exercise • int num = 5, result = 10; What is the value of result? • result /= num; • result *= num – 3; • result -= result % num; • result %= 3 * 2; 2 20 10 4

  20. AVERAGE of 10 numbers const int LIMIT = 10; int main() { float num, total = 0, average; int count = LIMIT; cout << "Please input " << LIMIT << " numbers: " << endl; while ( count > 0 ) { cin >> num; count --; total += num; } average = total / LIMIT; cout << "The average is " << average << "." << endl; return 0; }

  21. Count-controlled loop • Two ways: • increase a counter till reaching the up-limit • decrease a counter till reaching the bottom-limit • Which one to choose depends on the problem and your design.

  22. Three Types of Loops • Sentinel-controlled loop • the loop stops when LCV become certain value. while ( LCV != END_VALUE ) • Count-controlled loop • the loop executes LIMIT times. while ( count <= LIMIT ) • End-of-file-controlled loop • the loops stops when reaching the end of the input file. while ( !cin.eof() )

  23. Loading an Input File in HiC • Click the RUN menu • Select option "Set Input File …" • Click “Load Input” • Browse to the file and open it • Select the Input (Interactive) radio button • Click OK

  24. Function cin.eof() • returns true (end of file) or false • eof(): end of file OR end of input • From keyboard: [CTRL-D] to indicate eof. • From File: • Not True after reading the last item in the file • True when trying to read after reading the last item in the file • while ( ! cin.eof() ) is the same as while ( cin )

  25. Example of cin.eof() int theInput; int count = 0; cout << "What is your input: "; cin >> theInput; while (!cin.eof()) { count ++; cout << "What is your input: "; cin >> theInput; } cout << endl << "Last input: " << theInput; cout << endl << "Count: " << count; What is the output if input 1\n2\n3\n4[ctrl-d]? What is the output if input 1\n2\n3\n4\n[ctrl-d]? What is the output if input 50\n55.5\n60?

  26. How to design loops • What is the condition that ends the loop? • How should the condition be initialized? • How should the condition be updated? • What is the process being repeated? • What variables do we need to store the information? • How should the process be initialized? • How should the process be updated? • What is the state of the program on exiting the loop?

  27. Example: Find the nth Fibonacci number • Fibonacci number: 0,1,1,2,3,5,8,13,… Pseudo Code previous = 0 current = 1 count = 1 While count is not n yet fibonacci = current + previous previous = current current = fibonacci increase count by 1 print fibonacci int previous, current, fibonacci; int count, limit; cout << "Please input the index of “ << "the fibonacci number “ << (starting with 0): "; cin >> limit; previous = 0; current = 1; count = 1; while ( count < limit ) { fibonacci = current + previous; previous = current; current = fibonacci; count ++; } cout << "The " << limit << "thfibonacci number is " << fibonacci << "." << endl; Keep track of a previous value is sometimes important!

  28. Nested Loop: table calculation • print 30 numbers as a 5*6 table: Pseudo Code While row is not 5 yet first cell = row * 10 print cell while column is not 6 yet current cell = previous cell + #row print cell column ++ row++

  29. Nested Loop: table calculation const int ROW_LIMIT = 5; const int COLUMN_LIMIT = 6; int main() { int rowCount = 1, columnCount; int cellValue; while ( rowCount <= ROW_LIMIT ) { columnCount = 1; cellValue = rowCount * 10; cout << endl << cellValue; columnCount ++; while ( columnCount <= COLUMN_LIMIT ) { cellValue = cellValue + rowCount; cout << " " << cellValue; columnCount ++; } rowCount ++; } return 0; } What if rowCount and columnCount are initialized as 0?

  30. Nested Loop Example: print a pyramid • print a pyramid using $ sign. Pseudo Code height = HEIGHT While height is not 0 yet print (height-1) spaces print (2*(HEIGHT-height)+1 )$ decrease height by 1 $ $$$ $$$$$ $$$$$$$ $$$$$$$$$ $$$$$$$$$$$

  31. Nested Loop Example: print a pyramid const int HEIGHT = 10; string spaceLine; string dollarLine; int height = HEIGHT; int count; while ( height > 0 ) { spaceLine = ""; dollarLine = ""; count = 0; while ( count < height - 1 ) { spaceLine+= " "; count ++; } count = 0; while ( count < 2 * ( HEIGHT - height ) + 1 ) { dollarLine+= "$"; count ++; } cout << spaceLine << dollarLine << endl; height --; }

  32. Trace in HiC Window/Console View/Status Window Break Point Step Over Run/Watch Reset

  33. Trace Execution Range unknown int score, max, count; count = 0; cin >> score; while (score != -1) { count ++; if (count == 1) max = score; else { if (score > max) max = score; } cin >> score; } if (count == 0) cout << “No scores!”; else cout << “The maximal score is ” << max; Input Scores: 45 55 39 -1 ? score max count 45 55 39 -1 ? 55 45 ? 0 1 2 3

  34. Tracing • Tracing • Input: 48 54 66 53 59 -1 • score max • ? 0 • 48 • 48 • 54 • 54 • 66 • 53 • 59 • 59 • -1 • How to do it? • One statement each line • Do not cross old values • Blank when no new value • WILL BE ON QUIZ • And Test 1 • And Final! Range Known const int LOW_LIMIT = 0; const int HIGH_LIMIT = 60; int score, max = LOW_LIMIT; cin >> score; while (score != -1) { if (score < LOW_LIMIT || score > HIGH_LIMIT) cout << “Invalid score: ” << score; else { if (score > max) max = score; } cin >> score; }

  35. Tracing Nested Loops int xValue, yValue, zValue; xValue = 3; while (xValue > 1) { zValue = 1; yValue = xValue; while (yValue > 0) { zValue *= yValue; yValue --; } cout << "What is this: " << zValue; xValue --; } xValueyValuezValue ? ? ? 3 1 3 3 2 6 1 6 0 2 1 2 2 1 2 0 1

  36. Tracing exercise int previous, current, fibonacci; int count, limit; cout << "Please input the index of “ << "the fibonacci number “ << (starting with 0): "; cin >> limit; previous = 0; current = 1; count = 1; while ( count < limit ) { fibonacci = current + previous; previous = current; current = fibonacci; count ++; } cout << "The " << limit << "thfibonacci number is " << fibonacci << "." << endl; Input: 5 (limit) previous current Fibonacci count

  37. More on formatting output • #include <iostream> • showpoint • #include <iomanip> • setprecision() • setw() • fixed • left • right

  38. showpoint: show the decimal point • showpoint is a flag set to always show the decimal point for float values inserted into the stream. • The flag can be unset using noshowpoint manipulator. • Need to include <iostream> #include <iostream> using namespace std; int main () { double a, b, pi; a=30; b=10000; pi=3.14156; cout << showpoint<< a << '\t' << b << '\t' << pi << endl; cout << noshowpoint<< a << '\t' << b << '\t' << pi << endl; return 0; } The output is: 30.0000 10000.0 3.14156 30 10000 3.14156 tab

  39. setprecision(n) • ndetermines the maximum number of digits that shall be output • The flag fixed fixes the number of decimal places to n. • Need to include <iomanip> #include <iostream> #include <iomanip> using namespace std; int main() { double num1 = 0.12345678; int num2 = 1; cout << num1 << endl; cout << setprecision(2) << num1 << endl; cout << setprecision(4) << num1 << endl; cout << num1 << endl; cout << fixed << num2 << endl; cout << float(num2) << endl; return 0; } The output is: 0.123457 0.12 0.1235 0.1235 1 1.0000

  40. setw(n): set field width • n determines the minimum number of characters written in the output. If the natural length is shorter than n, it will fill with spaces. • flag left and right determine the position of the output in the field; if not specified, the default is right. • Need to include <iomanip> The output is: 77 6655 77 66 55 1.23 #include <iostream> #include <iomanip> using namespace std; int main () { cout << setw(5); cout << 77 << setw(5) << 66 << 55 << endl; cout << left << setw (5); cout << 77 << setw(5) << 66 << 55 << endl; cout << setw(5) << right << 1.23 << endl; return 0; } Unlike setprecision(n), setw(n) only affects the next output field!

  41. Summary • Four parts of a loop: initialize, test, loop body, update LCV • three types of loop • sentinel-controlled loop • count-controlled loop • eof-controlled loop • nested loop • trace your execution • manipulate your output • showpoint • setprecision(n) • setw(n)

  42. Style Your submission as of the above date using HiC, v3.1.8. If this is a programming assignment, please review the assignment writeup and programming ground rules to make sure you didn't miss anything. File: J:\CS143\Programs\Program 1\prog1.cpp: 25: 26: #include <iostream> 27: #include <string> 28: using namespace std; 29: 30: int main() 31: { 32: ... Miss Comment Block! Could lose 3 points!

  43. Style Your submission as of the above date using HiC, v3.1.8. If this is a programming assignment, please review the assignment writeup and programming ground rules to make sure you didn't miss anything. File: J:\CS143\Programs\Program 1\prog1.cpp: 1: //--------------------------------------------------------------------- 2: // Name: John Smith 3: // 4: // Course: CS 143, Section 3, Fall 2011 5: // 6: // Purpose: This program converts between kilometers and 7: // miles or between Fahrenheit temperature and Celsius. 8: // 9: // Input : This program accepts the following prompted input 10: // from the keyboard: 13: // 14: // Output: This program provides the following output prompts to 15: // standard output (the monitor): 16: // "Input a type: kilometers, miles, fahrenheit, or celsius; 17: // followed by a space and then an amount: " 24: //--------------------------------------------------------------------- 25: 26: #include <iostream> 27: #include <string> 28: using namespace std;

  44. Style 36: 37: int main() 38: { 30: const float KM_PER_MILE = 1.61; 31: const float FREEZING_F = 32.0; 32: const float FAHR_PER_CELSIUS = 9.0 / 5.0; 39: string units; 40: float amount, conversion; 41: 42: cout << "Input a type: kilometers, miles, fahrenheit, or celsius;" 43: << endl << "followed by a space and then an amount: " << endl; 44: cin >> units >> amount; Constants should be before main() 30: const float KM_PER_MILE = 1.61; 31: const float FREEZING_F = 32.0; 32: const float FAHR_PER_CELSIUS = 9.0 / 5.0; 36: 37: int main() 38: { 39: string units; 40: float amount, conversion; 41:

  45. Style 30: const float KM_PER_MILE = 1.61; 31: const float FREEZING_F = 32.0; 32: const float FAHR_PER_CELSIUS = 9.0 / 5.0; 36: 37: int main() 38: { 39: string units; 40: float amount, conversion; 41: 42: cout << "Input a type: kilometers, miles, fahrenheit, or celsius;" 43: << endl << "followed by a space and then an amount: " << endl; 44: cin >> units >> amount; Do not indent constants! 30: const float KM_PER_MILE = 1.61; 31: const float FREEZING_F = 32.0; 32: const float FAHR_PER_CELSIUS = 9.0 / 5.0; 36: 37: int main() 38: { 39: string units; 40: float amount, conversion; 41: 42: cout << "Input a type: kilometers, miles, fahrenheit, or celsius;" 43: << endl << "followed by a space and then an amount: " << endl; 44: cin >> units >> amount;

  46. Style 76: if (amount > 120) 77: { 78: conversion = (amount – 32.0) / FAHR_PER_CELSIUS; 79: cout << endl << "Temperature " << amount << " degrees in " 80: << "Fahrenheit is " << conversion 81: << " degrees in Celsius."; 82: } 83: else Magic Number! 76: if (amount > MAX_FAHR_TEMP) 77: { 78: conversion = (amount - FREEZING_F) / FAHR_PER_CELSIUS; 79: cout << endl << "Temperature " << amount << " degrees in " 80: << "Fahrenheit is " << conversion 81: << " degrees in Celsius."; 82: } 83: else

  47. Style 76: if (amount > MAX_FAHR_TEMP) 77: { 78: conversion = (amount - FREEZING_F) / FAHR_PER_CELSIUS; 79: cout << endl << "Temperature " << amount << " degrees in " 80: << "Fahrenheit is " << conversion 81: << " degrees in Celsius."; 82: } 83: else Brace Alignment! 76: if (amount > MAX_FAHR_TEMP) 77: { 78: conversion = (amount - FREEZING_F) / FAHR_PER_CELSIUS; 79: cout << endl << "Temperature " << amount << " degrees in " 80: << "Fahrenheit is " << conversion 81: << " degrees in Celsius."; 82: } 83: else

  48. Style 76: if (amount > MAX_FAHR_TEMP) 77: { 78: conversion = (amount - FREEZING_F) / FAHR_PER_CELSIUS; 79: cout << endl << "Temperature " << amount << " degrees in “ << "Fahrenheit is " << conversion << " degrees in Celsius."; 80: } 81: else Line too long! Each line can have at most 74 columns! 76: if (amount > MAX_FAHR_TEMP) 77: { 78: conversion = (amount - FREEZING_F) / FAHR_PER_CELSIUS; 79: cout << endl << "Temperature " << amount << " degrees in " 80: << "Fahrenheit is " << conversion 81: << " degrees in Celsius."; 82: } 83: else

  49. Style 76: if (amount > MAX_FAHR_TEMP) 77: { 78: conversion = (amount - FREEZING_F) / FAHR_PER_CELSIUS; 79: cout << endl << "Temperature " << amount << " degrees in “ 80: << "Fahrenheit is " << conversion 81: << " degrees in Celsius."; 82: } 83: else Alignment! 76: if (amount > MAX_FAHR_TEMP) 77: { 78: conversion = (amount - FREEZING_F) / FAHR_PER_CELSIUS; 79: cout << endl << "Temperature " << amount << " degrees in " 80: << "Fahrenheit is " << conversion 81: << " degrees in Celsius."; 82: } 83: else

  50. Style 76: if (amount > MAX_FAHR_TEMP) 77: { 78: conversion = (amount - FREEZING_F) / FAHR_PER_CELSIUS; 79: cout << endl << "Temperature " << amount << " degrees in “ 80: << "Fahrenheit is " << conversion 81: << " degrees in Celsius."; 82: } 83: else 84: cout << “Invalid unit!!”; Indentation! 76: if (amount > MAX_FAHR_TEMP) 77: { 78: conversion = (amount - FREEZING_F) / FAHR_PER_CELSIUS; 79: cout << endl << "Temperature " << amount << " degrees in " 80: << "Fahrenheit is " << conversion 81: << " degrees in Celsius."; 82: } 83: else 84: cout << “Invalid unit!!”;

More Related