Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

8. How many times will each of the following loops execute? What is the output i

ID: 3834132 • Letter: 8

Question

8. How many times will each of the following loops execute? What is the output in each case?

a. x = 5; y = 40;

do

x = x + 10;

while (x < y);

cout << x << " " << y << endl;

b. x = 5; y = 80;

do

x = x * 2;

while (x < y);

cout << x << " " << y << endl;

c. x = 5; y = 20;

do

x = x + 2;

while (x >= y);

cout << x << " " << y << endl;

d. x = 5; y = 35;

while (x < y)

x = x + 10;

cout << x << " " << y << endl

9. Given the following program segment:

int limit = 4;

int first = 5;

int j;

for(j = 1; j <= limit; j++)

{

cout << first * j << endl;

first = first + (j - 1);

}

cout << endl;

write a while loop and a do...while loop that have the same output.

Explanation / Answer

8-
a. x = 5; y = 40;
do
x = x + 10;
while (x < y);
cout << x << " " << y << endl;
the loop will execute 4 times first the value becomes 15 then second it becomes 25 then it becomes 35 then also it is less than 40 so it will rum one more time then value becomes 45 then loop will terminate.

b- x = 5; y = 80;
do
x = x * 2;
while (x < y);
cout << x << " " << y << endl;
it will execute 4 times as in first iteration it becomes 10 then it becomes 20 then it becomes 40 3 iterations completed still the value is less than 80 then in next iteration the value becomes 80 which is not less than 80 so here loop terminates so it executes 4 times.

c- x = 5; y = 20;
do
x = x + 2;
while (x >= y);
cout << x << " " << y << endl;
it will execute only one time as it enters do the value of x becomes 7 and the condition in while becomes false so the loop terminates there only so it executes only one time.

d. x = 5; y = 35;
while (x < y)
x = x + 10;
cout << x << " " << y << endl
it will execute 3 times as in first time it checks 5<35 true it runs the loop value becomes 15 then it again checks 15<35 then value becomes 25 again checks the value is less than 35 again checks now condition fails so it exits the loop.

9-using while loop
int limit = 4;
int first = 5;
int j=1;
while( j <= limit)
{
cout << first * j << endl;
first = first + (j - 1);
j++;
}
cout << endl;

using do while loop
   int limit = 4;
int first = 5;
int j=1;
do
{
cout << first * j << endl;
first = first + (j - 1);
j++;
}while( j <= limit);
cout << endl;

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote