LSP- Nested For Statements Lesson
Nested For Statements
A for loop can contain any kind of statement in its body, including another for loop. When a loop is used within another loop it is called a nested loop. A nested loop is controlled by two for statements. The first loop is called the outer loop. The second loop is called the inner loop. The outer loop controls how many times the inner loop will execute. The outer loop and the inner loop control variables cannot be the same name.
The program shown below creates a grid of squares.
The outer for loop will determine how many times the inner for loop will execute. It controls the number of rows drawn. The outer loop will execute and move control to the inner loop. The outer loop will execute 10 times in the above example.
height = 300
row = row + 30
300 / 30 = 10 times to loop
for(row=0; row<height; row=row+30)
The inner loop will iterate until it becomes false. It will control the number of columns. At each row, the column (x) is increased 30 pixels and will draw a rectangle 30 pixels for width and height at each interval starting at 0 until it is < width. When the inner loop becomes false, the outer loop is incremented again. Then control goes back to the inner loop. The inner loop will execute 10 times.
width = 300
column = column +30
300/30 = 10 times to loop
for(column = 0; column < width; column = column = column+30);
Since the rectangle has the coordinates (row, column, 30, 30), It draws a rectangle 30x30 pixels at the row, column location producing a 10 x 10 grid.
Nested For Loops Video
Watch the nested for loops video below.
Pixels
Pixels are arranged in a 2D array of rows and columns. They are accessed by looping through each row and column in the frame. The program below creates a point at every pixel location in the frame and changes it to a random color.
[CC BY 4.0] UNLESS OTHERWISE NOTED | IMAGES: LICENSED AND USED ACCORDING TO TERMS OF SUBSCRIPTION