// CS116 - Summer 1998 // HW1 Problem 1 Solution #include main() { int first, second, smaller; // prompt user for two integers and read them in cout << "Please enter two integers: "; cin >> first >> second; // display the smaller one if (first < second) { smaller = first; } else { smaller = second; } // display smaller integer cout << "The smaller integer is " << smaller << "." << endl; } // CS116 - Summer 1998 // HW1 Problem 2 Solution #include main() { int low, high; // prompt user for low and high and read them in cout << "Please enter two integers, the first not larger than the second: "; cin >> low >> high; if (low <= high) { // input is good, sum up all integers from low to high int current, sum = 0; for (current = low; current <= high; current++) { sum = sum + current; } // display sum cout << "The sum of all integers from " << low << " to " << high << " is " << sum << "." << endl; } else { // bad input, report error and finish cout << "sum: ** error: first number larger than second. Exiting." << endl; } } // CS116 - Summer 1998 // HW1 Problem 3 Solution #include main() { int input, posCount = 0, negCount = 0; bool quit = false; while (!quit) { // prompt user for input and read it in cout << "Please enter an integer (0 to quit): "; cin >> input; if (input == 0) { // quitting quit = true; } else { // increment appropriate count if (input < 0) posCount++; else negCount++; } } // display summary cout << "Summary:" << endl << posCount << " of the numbers were positive," << endl << negCount << " of the numbers were negative." << endl; } // CS116 - Summer 1998 // HW1 Problem 4 Solution #include main() { // search range is 1 to 1024, user answers y/n int low = 1, high = 1024, mid; char answer; // ask user to choose a number in the range cout << "Please choose an integer between 1 and 1024..." << endl; // do binary search until range has one element only while (low != high) { // compute *integer* midpoint and ask question // (mid is immediately left of the "true" middle mid = (low + high - 1) / 2; cout << "Is your number bigger than " << mid << " ? (y/n) "; cin >> answer; // divide range in half by adjustment of proper boundary if (answer == 'y') { low = mid + 1; } else { high = mid; } } // display found answer cout << "Your number is " << low << "." << endl; }