I l@ve RuBoard |
![]() ![]() |
Exercise 2.1main() [in Section 2.1] allows the user to enter only one position value and then terminates. If a user wishes to ask for two or more positions, he must execute the program two or more times. Modify main() [in Section 2.1] to allow the user to keep entering positions until he indicates he wishes to stop. We use a while loop to execute the "solicit position, return value" code sequence. After each iteration, we ask the user whether he wishes to continue. The loop terminates when he answers no. We'll jump-start the first iteration by setting the bool object more to true. #include <iostream> using namespace std; extern bool fibon_elem( int, int& ); int main() { int pos, elem; char ch; bool more = true; while ( more ) { cout << "Please enter a position: "; cin >> pos; if ( fibon_elem( pos, elem )) cout << "element # " << pos << " is " << elem << endl; else cout << "Sorry. Could not calculate element # " << pos << endl; cout << "would you like to try again? (y/n) "; cin >> ch; if ( ch != 'y' || ch != 'Y' ) more = false; } } When compiled and executed, the program generates the following output (my input is highlighted in bold): Please enter a position: 4 element # 4 is 3 would you like to try again? (y/n) y Please enter a position: 8 element # 8 is 21 would you like to try again? (y/n) y Please enter a position: 12 element # 12 is 144 would you like to try again? (y/n) n ![]() |
I l@ve RuBoard |
![]() ![]() |