The following code implements a for loop, a do while loop, and a while loop. The
ID: 668805 • Letter: T
Question
The following code implements a for loop, a do while loop, and a while loop. There are stubs for four additional loops. You are to add the code necessary to implement the missing loops as indicated by the comments. When adding code for a for loop, you must fill in all three parts in the for statement, i.e. the parts inside the parenthesis.Outputs for the three versions of Loop A should be identical. The three versions of Loop B should behave in the same way. Outputs for the three versions of Loop C should be identical.
As a comment in the code above describe the scope of the variable i in inside and outside the body of each version of each loop.
What is the minimum number of iterations for each type of loop? You can put this as a comment at the top of your code.
Explanation / Answer
#include <iostream>
using namespace std;
int main() {
cout << "Loop A (for version)" << endl;
for (int i=0;i<5;i++) {
cout << i << endl;
}
cout << "Loop A (while version)" << endl;
// Add while loop code
int i = 0;
while(i<5)
{
cout<<i<<endl;
i++;
}
cout << "Loop A (do while version)" << endl;
// Add do while loop code
i=0;
do
{
cout<<i<<endl;
i++;
}
while(i<5);
cout << "Loop B (do while version)" << endl;
do {
cout << "Enter a number less than 100 (Greater than 100 to exit):" << endl;
cin >> i;
cout << i << endl;
} while (i<100);
cout << "Loop B (for version)" << endl;
// Add for loop code
for(int i=0;i<100;)
{
cout << "Enter a number less than 100 (Greater than 100 to exit):" << endl;
cin >> i;
cout << i << endl;
}
cout << "Loop B (while version)" << endl;
// Add while loop code
i=0;
while(i<100)
{
cout << "Enter a number less than 100 (Greater than 100 to exit):" << endl;
cin >> i;
cout << i << endl;
}
cout << "Loop C (while version)" << endl;
i = 20;
while (i>10) {
cout << i*2 << " ";
i-=2;
}
cout << endl << endl;
cout << "Loop C (do while version)" << endl;
// Add do while loop code
i=20;
do
{
cout << i*2 << " ";
i-=2;
}
while(i>10);
cout << "Loop C (for version)" << endl;
// Add for loop code
for(int i=20;i>10;i-=2)
{
cout << i*2 << " ";
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.