91.9k views
5 votes
How I to turn this ''loop while'' in ''loop for''? var i = 0; while (i < 20) { var lineY = 20 + (i * 20); line(0, lineY, 400, lineY); i++; }

User Fortilan
by
5.3k points

1 Answer

0 votes

Answer:

for(i = 0; i<20;i++){

lineY = 20 + (i * 20);

line(0, lineY, 400, lineY) }

Step-by-step explanation:

First declare and initialize the variable i. You have not specified the data type of i so if the data type of i is integer i.e. int then you should declare i variable in the for loop as for(int i = 0; i<20;i++)

So the given while loop has a variable i which is initialized to 0. Then while(i<20) means that while loop executes until the value of i exceeds 20. If this while condition is true then the two statements inside its body will execute. The two statements are: lineY = 20 + (i * 20);

line(0, lineY, 400, lineY);

The value of i ins incremented after each iteration i.e. i++

So while loop has the following syntax"

1) initialization; ----> i = 0

2) while(condition) { ----> i<20

3) loop body -----> lineY = 20 + (i * 20); line(0, lineY, 400, lineY);

4) increment or decrement loop variable } ----> i++

For loop has the following syntax:

for( initialization of loop variable ; condition; decrement/increment loop variable) {

loop body }

Here:

initialization ----> i = 0

condition ----> i<20

loop body -----> lineY = 20 + (i * 20); line(0, lineY, 400, lineY);

increment or decrement loop variable ----> i++

User Karlx Swanovski
by
4.9k points