Given the following while loop, rewrite it as a for loop.
int x = 0;
while(x < 10)
{
printf("%d\n", x);
x++;
}
The following while can be written as a for loop as:-
int x;
for(x = 0; x < 10; x++){
printf("%d\n",x);
}
Both for loop and a while loop is an entry control loop, that is, in both these loop, loop condition is tested before the execution of the loop statements.
for loop takes three arguments first is the initialization of the loop variable, then loop condition, and then increment or decrement of the loop variable.
Everything written inside {} is the for loop body.
I am also including the executable code for your reference. The code will provide the same output as the while loop provided in the question.
#include<stdio.h>
void main(){
int x;
for(x = 0; x < 10; x++){
printf("%d\n",x);
}
}
Note:- Please comment down if you face any problem. :)
Get Answers For Free
Most questions answered within 1 hours.