Homework 6 UCR CS10: Introduction to Computer Science Winter Quarter 2004, Lecturer: Kris Miller Due Wednesday, February 18 before 8:00pm by web turnin. YOU MUST TURN THIS IN AS A .CPP, .CC, OR .C FILE. The turnin system will no longer accept other types of files. Your file names should not have spaces or non-alphanumeric characters. A good file name to use is hw4.cpp. ------------------------------------------------------------------------------- Note: Collaboration policy for this homework assignment Collaboration on this homework is strongly ENCOURAGED. The homework is intended for practice, not assessment -- most people who turn in decent work should get most if not all points for this assignment. Forming study groups is strongly encouraged. You shouldn't simply copy answers from any source -- each other, the book, the web, other books, previous solutions, etc. But you can certainly discuss how to solve the problems, look over each others solutions and help "debug" them, compare answers and redo problems if you determine your answer is wrong, and most importantly, explain concepts related to the problems and solutions. ------------------------------------------------------------------------------- 1. Self-test Exercise #5-1 (Chapter 5, #1) 2. Self-test Exercise #5-2 3. Self-test Exercise #5-3 4. Self-test Exercise #5-4 5. Self-test Exercise #5-5 6. Self-test Exercise #5-7 7. Self-test Exercise #5-10 Self-test answers in back of chapter 5. 8. Write a program that takes 5 integer numbers from a file called in.txt and outputs the largest and smallest of those numbers to an output file called out.txt. If your input file had the numbers 1 3 8 5 2 inside, the output file should look like this: Largest number is 8 Smallest number is 1 #include #include #include using namespace std; const int NUM_VALUES = 5; void largeAndSmall(ifstream& fin, ofstream& fout); //preconditions: fin and fout have been been declared and opened. // fin is attached to a file that has 5 integers. //postconditions: The largest value and the smallest value in the input file // have been output to the output file. int main() { ifstream fin; ofstream fout; fin.open("in.txt"); if (fin.fail()) { cout << "Error opening input file\n"; exit(1); } fout.open("out.txt"); if (fout.fail()) { cout << "Error opening output file\n"; exit(1); } largeAndSmall(fin, fout); fin.close(); fout.close(); return 0; } void largeAndSmall(ifstream& fin, ofstream& fout) { int next, smallest, largest, cnt = 1; // bring in first number from file fin >> next; // make smallest AND largest equal to that first number smallest = next; largest = next; // bring in rest of values in file while (cnt < NUM_VALUES) { fin >> next; if (next > largest) { largest = next; } if (next < smallest) { smallest = next; } cnt++; } fout << "Largest: " << largest << endl << "Smallest: " << smallest << endl; }