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; max = num1; if ( num2 > max ) max = num2; if ( num3 > max ) max = num3; How about finding the MAX of n number? cout << “The max value is ” << max << endl; Example: MAX of n numbers 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? int num, max; cin >> num; if ( num == -1 ) { cout << “No input!”; return 0; } max = num; while ( num != -1 ) { if ( num > max ) max = num; cin >> num; } cout << “The max value is ” << max << endl; return 0; 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; } 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; } While Loop Initialization (LCV and others) while (LogicalExpression) (Testing LCV) false true Do Work Statement after loop Update LCV 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. 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? 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? 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)) 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; 11 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() ) 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 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; count ++; } // total = total + num; // count = count + 1; average = total / count; cout << "The average is " << average << "." << endl; return 0; } 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 ++; } How about this design? Wrong! sum 9 numbers / 10 How to fix it? average = total / count; cout << "The average is " << average << "." << endl; return 0; } 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 ++; } How about this design? Correct answer, but extra input! How to fix it? average = total / count; cout << "The average is " << average << "." << endl; return 0; } 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; How about this design? while ( count < LIMIT ) { Correct! total += num; count ++; Carefully check the final if ( count != LIMIT ) cin >> num; when designing loops! } average = total / count; cout << "The average is " << average << "." << endl; return 0; } status 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; 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 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; } 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. 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() ) 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 23 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 ) 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? 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? 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 Keep track of a previous value is sometimes important! int previous, current, fibonacci; int count, limit; cout << << << cin >> "Please input the index of “ "the fibonacci number “ (starting with 0): "; limit; previous = 0; current = 1; count = 1; while ( count < limit ) { fibonacci = current + previous; previous = current; current = fibonacci; count ++; } cout << "The " << limit << "th fibonacci number is " << fibonacci << "." << endl; Nested Loop: table calculation print 30 numbers as a 5*6 table: 10 11 12 13 14 15 20 22 24 26 28 30 30 33 36 39 42 45 40 44 48 52 56 60 50 55 60 65 70 75 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++ Nested Loop: table calculation const int ROW_LIMIT = 5; const int COLUMN_LIMIT = 6; int main() { int rowCount = 1, columnCount; int cellValue; What if rowCount and columnCount are initialized as 0? 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; } 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 $ $$$ $$$$$ $$$$$$$ $$$$$$$$$ $$$$$$$$$$$ 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 --; } Trace in HiC Window/Console View/Status Window Break Point Step Over Run/Watch Reset 32 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 ? 45 55 39 -1 ? max 55 45 1 2 3 count ? 0 Tracing 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; } Tracing Input: 48 score ? 48 54 66 53 59 max 0 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! -1 Tracing Nested Loops int xValue, yValue, zValue; xValue = 3; while (xValue > 1) { zValue = 1; yValue = xValue; while (yValue > 0) { zValue *= yValue; yValue --; } xValue ? 3 yValue ? zValue ? 1 3 3 2 6 1 6 0 2 1 cout << "What is this: " << zValue; 2 2 1 xValue --; 2 } 0 1 Tracing exercise int previous, current, fibonacci; int count, limit; cout << << << cin >> "Please input the index of “ "the fibonacci number “ (starting with 0): "; limit; previous = 0; current = 1; count = 1; while ( count < limit ) { fibonacci = current + previous; previous = current; current = fibonacci; count ++; } cout << "The " << limit << "th fibonacci number is " << fibonacci << "." << endl; Input: 5 (limit) previous current Fibonacci count More on formatting output #include <iostream> showpoint #include <iomanip> setprecision() setw() fixed left right 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; The output is: 30.0000 10000.0 3.14156 30 10000 3.14156 tab cout << showpoint << a << '\t' << b << '\t' << pi << endl; cout << noshowpoint << a << '\t' << b << '\t' << pi << endl; return 0; } setprecision(n) n determines 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 cout cout cout << << << << num1 << endl; setprecision(2) << num1 << endl; setprecision(4) << num1 << endl; 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 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: #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; } 77 6655 77 66 55 1.23 Unlike setprecision(n), setw(n) only affects the next output field! 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) 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: 27: 28: 29: 30: 31: 32: #include <iostream> #include <string> using namespace std; int main() { ... Miss Comment Block! Could lose 3 points! 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: 3: 4: 5: 6: 7: 8: 9: 10: 13: 14: 15: 16: 17: 24: 25: 26: 27: 28: //--------------------------------------------------------------------// Name: John Smith // // Course: CS 143, Section 3, Fall 2011 // // Purpose: This program converts between kilometers and // miles or between Fahrenheit temperature and Celsius. // // Input : This program accepts the following prompted input // from the keyboard: // // Output: This program provides the following output prompts to // standard output (the monitor): // "Input a type: kilometers, miles, fahrenheit, or celsius; // followed by a space and then an amount: " //--------------------------------------------------------------------#include <iostream> #include <string> using namespace std; 43 Style 36: 37: 38: 30: 31: 32: 39: 40: 41: 42: 43: 44: int main() { const float KM_PER_MILE const float FREEZING_F const float FAHR_PER_CELSIUS string units; float amount, conversion; = 1.61; = 32.0; = 9.0 / 5.0; cout << "Input a type: kilometers, miles, fahrenheit, or celsius;" << endl << "followed by a space and then an amount: " << endl; cin >> units >> amount; Constants should be before main() 30: 31: 32: 36: 37: 38: 39: 40: 41: const float KM_PER_MILE const float FREEZING_F const float FAHR_PER_CELSIUS = 1.61; = 32.0; = 9.0 / 5.0; int main() { string units; float amount, conversion; 44 Style 30: 31: 32: 36: 37: 38: 39: 40: 41: 42: 43: 44: const float KM_PER_MILE const float FREEZING_F const float FAHR_PER_CELSIUS = 1.61; = 32.0; = 9.0 / 5.0; int main() { string units; float amount, conversion; cout << "Input a type: kilometers, miles, fahrenheit, or celsius;" << endl << "followed by a space and then an amount: " << endl; cin >> units >> amount; Do not indent constants! 30: 31: 32: 36: 37: 38: 39: 40: 41: 42: 43: 44: const float KM_PER_MILE const float FREEZING_F const float FAHR_PER_CELSIUS = 1.61; = 32.0; = 9.0 / 5.0; int main() { string units; float amount, conversion; cout << "Input a type: kilometers, miles, fahrenheit, or celsius;" << endl << "followed by a space and then an amount: " << endl; cin >> units >> amount; 45 Style 76: 77: 78: 79: 80: 81: 82: 83: if (amount > 120) { conversion = (amount – 32.0) / FAHR_PER_CELSIUS; cout << endl << "Temperature " << amount << " degrees in " << "Fahrenheit is " << conversion << " degrees in Celsius."; } else Magic Number! 76: 77: 78: 79: 80: 81: 82: 83: if (amount > MAX_FAHR_TEMP) { conversion = (amount - FREEZING_F) / FAHR_PER_CELSIUS; cout << endl << "Temperature " << amount << " degrees in " << "Fahrenheit is " << conversion << " degrees in Celsius."; } else 46 Style 76: 77: 78: 79: 80: 81: 82: 83: if (amount > MAX_FAHR_TEMP) { conversion = (amount - FREEZING_F) / FAHR_PER_CELSIUS; cout << endl << "Temperature " << amount << " degrees in " << "Fahrenheit is " << conversion << " degrees in Celsius."; } else Brace Alignment! 76: 77: 78: 79: 80: 81: 82: 83: if (amount > MAX_FAHR_TEMP) { conversion = (amount - FREEZING_F) / FAHR_PER_CELSIUS; cout << endl << "Temperature " << amount << " degrees in " << "Fahrenheit is " << conversion << " degrees in Celsius."; } 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 “ << "Fahrenheit is " << conversion << " degrees in Celsius."; 80: } 81: else Line too long! Each line can have at most 74 columns! 76: 77: 78: 79: 80: 81: 82: 83: if (amount > MAX_FAHR_TEMP) { conversion = (amount - FREEZING_F) / FAHR_PER_CELSIUS; cout << endl << "Temperature " << amount << " degrees in " << "Fahrenheit is " << conversion << " degrees in Celsius."; } else 48 Style 76: 77: 78: 79: 80: 81: 82: 83: if (amount > MAX_FAHR_TEMP) { conversion = (amount - FREEZING_F) / FAHR_PER_CELSIUS; cout << endl << "Temperature " << amount << " degrees in “ << "Fahrenheit is " << conversion << " degrees in Celsius."; } else Alignment! 76: 77: 78: 79: 80: 81: 82: 83: if (amount > MAX_FAHR_TEMP) { conversion = (amount - FREEZING_F) / FAHR_PER_CELSIUS; cout << endl << "Temperature " << amount << " degrees in " << "Fahrenheit is " << conversion << " degrees in Celsius."; } else 49 Style 76: 77: 78: 79: 80: 81: 82: 83: 84: if (amount > MAX_FAHR_TEMP) { conversion = (amount - FREEZING_F) / FAHR_PER_CELSIUS; cout << endl << "Temperature " << amount << " degrees in “ << "Fahrenheit is " << conversion << " degrees in Celsius."; } else cout << “Invalid unit!!”; Indentation! 76: 77: 78: 79: 80: 81: 82: 83: 84: if (amount > MAX_FAHR_TEMP) { conversion = (amount - FREEZING_F) / FAHR_PER_CELSIUS; cout << endl << "Temperature " << amount << " degrees in " << "Fahrenheit is " << conversion << " degrees in Celsius."; } else cout << “Invalid unit!!”; 50 Style 76: 77: 78: 79: 80: 81: 82: 83: 84: if (amount > MAX_FAHR_TEMP) {cout << “Invalid unit!!”;} else { conversion = (amount - FREEZING_F) / FAHR_PER_CELSIUS; cout << “The result is good."; } Braces on separate lines! 76: 77: 78: 79: 80: 81: 82: 83: 84: if (amount > MAX_FAHR_TEMP) { cout << “Invalid unit!!”; } else { conversion = (amount - FREEZING_F) / FAHR_PER_CELSIUS; cout << “The result is good."; } 51 Style 76: 77: 78: 79: 80: 81: 82: 83: if (amount>MAX_FAHR_TEMP) { conversion = (amount - FREEZING_F)/FAHR_PER_CELSIUS; cout << endl << "Temperature " << amount<<" degrees in “ << "Fahrenheit is "<<conversion << " degrees in Celsius."; } else Space before and after operator! 76: 77: 78: 79: 80: 81: 82: 83: if ( amount > MAX_FAHR_TEMP ) { conversion = ( amount - FREEZING_F ) / FAHR_PER_CELSIUS; cout << endl << "Temperature " << amount << " degrees in " << "Fahrenheit is " << conversion << " degrees in Celsius."; } else 52 Style 76: 77: 78: 82: 83: 84: 85: 86: 87: 88: 89: 90: 91: 92: 93: 94: if (amount > MAX_FAHR_TEMP) { conversion = (amount - FREEZING_F) / FAHR_PER_CELSIUS; } else if { } else { No blank line before/after else! 76: 77: 78: 79: 80: 81: 82: 83: 84: 85: 86: if (amount > MAX_FAHR_TEMP) { conversion = (amount - FREEZING_F) / FAHR_PER_CELSIUS; . . . } else if { . . . } else { 53 Style 33: 34: 35: 36: 37: 38: 39: 40: 41: 42: 43: 44: const float FAHR_PER_CELSIUS = 9.0 / 5.0; int main() { string units; float amount, conversion; cout << "Input a type: kilometers, miles, fahrenheit, or celsius;" << endl << "followed by a space and then an amount: " << endl; cin >> units >> amount; No blank line before/after brace! 32: 36: 37: 38: 39: 40: 41: 42: 43: 44: const float FAHR_PER_CELSIUS = 9.0 / 5.0; int main() { string units; float amount, conversion; cout << "Input a type: kilometers, miles, fahrenheit, or celsius;" << endl << "followed by a space and then an amount: " << endl; cin >> units >> amount; 54 Style 35: 36: 37: 38: 39: 40: 41: const float Fahr_Per_Celsius = 9.0 / 5.0; int main() { string variable; float amount, conversion; Naming conversion! 35: 36: 37: 38: 39: 40: 41: 42: 43: 44: const float FAHR_PER_CELSIUS = 9.0 / 5.0; int main() { string units; float amount, conversion; cout << "Input a type: kilometers, miles, fahrenheit, or celsius;" << endl << "followed by a space and then an amount: " << endl; cin >> units >> amount; 55 Style 35: 36: 37: 38: 39: 40: 41: 42: const float FAHR_PER_CELSIUS = 9.0 / 5.0; int main() { string unit; string kilo = “kilometers”; float amount, conversion; Unused code! 35: 36: 37: 38: 39: 40: 41: 42: 43: 44: 45: const float FAHR_PER_CELSIUS = 9.0 / 5.0; int main() { string units; float amount, conversion; . . . cin >> units >> amount; if ( unit == “kilometers” ) { . . . 56