/* lab05.cpp CIS 150 6/9/2005 David Klick This program demonstrates the use of repetition structures in C++. */ #include #include #include #include using std::cin; using std::cout; using std::ifstream; using std::ofstream; int main(void) { int i; // loop counter int sum; // accumulator for steps #4 and #5 int num; // holds random numbers (steps #7 and #8) // seed random number generator (for step #7) srand(time(NULL)); // step 1 of lab exercise for (i=0; i<100; i+=7) { cout << i << " "; } cout << '\n'; // step 2 of lab exercise i = 0; do { cout << i << " "; i += 7; } while (i <= 100); cout << '\n'; // step 3 of lab exercise i = 0; while (i <= 100) { cout << i << " "; i += 7; } cout << '\n'; // step 4 of lab exercise sum = 0; for (i=0; i<100; i+=7) { sum += i; } cout << "The sum of all multiples of 7 between 0 and 100 is " << sum << '\n'; // step 5 of lab exercise sum = 0; do { cout << "Enter an integer (-999 to exit): "; cin >> num; if (num != -999) sum += num; } while (num != -999); cout << "The sum is " << sum << '\n'; // step 6 of lab exercise for (i=1; i<=10; i++) { if (i%4==0) continue; cout << i << " "; } cout << '\n'; // step 7 of lab exercise ofstream ofile("lab04.data"); if (!ofile) { cout << "Error: Couldn't open output file!\n"; return 1; } for (i=1; i<=10; i++) { num = rand() % 26 + 50; ofile << num << '\n'; } ofile.close(); // step 8 of lab exercise ifstream ifile("lab04.data"); if (!ifile) { cout << "Error: Couldn't open input file!\n"; return 2; } ifile >> num; // priming read from file while (ifile) { // continue if read worked cout << num << " "; ifile >> num; } ifile.close(); return 0; } /* Sample output: 0 7 14 21 28 35 42 49 56 63 70 77 84 91 98 0 7 14 21 28 35 42 49 56 63 70 77 84 91 98 0 7 14 21 28 35 42 49 56 63 70 77 84 91 98 The sum of all multiples of 7 between 0 and 100 is 735 Enter an integer (-999 to exit): 27 Enter an integer (-999 to exit): 13 Enter an integer (-999 to exit): -10 Enter an integer (-999 to exit): -999 The sum is 30 1 2 3 5 6 7 9 10 55 69 66 61 69 73 66 75 67 70 */