Question
using c++ 1. Read the source code, paying special attention to how each loop is controlled. Then complete the Expected Output column, writing down the
using c++
1. Read the source code, paying special attention to how each loop is controlled. Then complete the Expected Output column, writing down the output you think each cout statement will produce. Run the program and complete the observed output column.
#include
using namespace std;
8 int main()
9 {
10 int i, // Loop control variable
11 sum; // Accumulator
12
13 i = 1;
14 while (i < 10)
15 { cout << i << ' ';
16 i +=2;
17 }
18 cout << " After loop i = " << i
19 << endl << endl;
20
21 i = 5;
22 while (i > 0)
23 cout << i--<< ' ';
24 cout << " After loop i = " << i
25 << endl << endl;
return 0;
}
Expected Output and Observed Output
after loop i (line 18) _______ ________
after loop i (line 24) _______ ________
Counting and Looping
The program in lab8.cpp prints
"I love Computer Science!!" 10 times.
Once the program is compiling and running, modify it as follows:
Instead of using constant LIMIT, ask the user how many times the message should be printed. You will need to declare a variable (e.g.int numTimes) to store the user's response and use that variable to control the loop. (Remember that all caps is used only for constants!)
Number each line in the output, and add a message at the end of the loop that says how
many times the message was printed.
// ****************************************************************
//lab8.cpp
//
// Use a while loop to print many messages declaring your
// passion for computer science
// ****************************************************************
#include
using namespace std;
int main{
// *** Step 2: Create an int called numTimes
// *** Step 2: Get rid of this, prompt the user for numTimes instead const
int LIMIT = 10;
int count = 1;
// *** Step 2: Change this to check if count is <= numTimes
while(count <= LIMIT)
{
// *** Step 2: Change this line to output count before the phrase
cout<
;
// *** Step 1: Increment count (hint: use the ++ operator)
}
// *** Step 2: Output the "Printed this message..." line
}
}
Here's an example of how the program should look when it's all finished. Bold, bracketed text stands for user input.
How many times should I print? [3]
1 I love Computer Science!!
2 I love Computer Science!!
3 I love Computer Science!!
Printed this message 3 times.
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started