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 same.int i = 20;while (i > 0){cout << i << “\t”;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 = 0;    while(i!=15){      cout << i << " ";      i = i + 5;    }

What will be the output of the following program?while i < 20: print(i) i += 1

What will be the output of the following code?int num = 2;int count=0;while(num!= 0){if ( num & 01)count ++;num >>=1;}cout<< count;return 0;

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

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

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.