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;}
Solution
To convert the given while loop to a for loop, follow these steps:
- Initialize the variable
ito 20. - Set the condition for the for loop as
i > 0. - Inside the loop, print the value of
ifollowed by a tab character. - Decrement the value of
iby 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.
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
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.