Knowee
Questions
Features
Study Tools

Convert the following while loop to a for loop such that the output remains same.int i = 20;while (i > 0){cout << i << “\t”;i = i - 2;}

Question

Convert the following while loop to a for loop such that the output remains the same.

int i = 20;
while (i &gt; 0) {
    cout &lt;&lt; i &lt;&lt; &quot;\t&quot;;
    i = i - 2;
}
🧐 Not the exact question you are looking for?Go ask a question

Solution

To convert the given while loop to a for loop, follow these steps:

  1. Initialize the variable i to 20.
  2. Set the condition for the for loop as i > 0.
  3. Inside the loop, print the value of i followed by a tab character.
  4. Decrement the value of i by 2 in each iteration.

Here is the converted for loop:

for (int i = 20; i > 0; i -= 2) {
    cout << i << "\t";
}

This for loop will produce the same output as the original while loop.

This problem has been solved

Similar Questions

What will be the output of the following code?          int i = 1;while(i<10){  if (i / 2 == 2)     cout << i << “ ”;i++;}

What will be the result?1. int i = 10;2. while(i++ <= 10){3. i++;4. }5. System.out.print(i);10111213

What is the output of the following piece of code?int i;i = 10;while (i < 20){ printf("%d", i % 2); i++;}

How does a WHILE loop start?{$a->questionintifier} Yanıta.while (i <= 10; i++)b.while (i <= 10)c.while i = 1 to 10d.while (i=0; i <= 10; i++)

. Find the output of the following program.main(){ int i = (1, 2, 3); cout << i << endl;}

1/3

Upgrade your grade with Knowee

Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.