Looping over a Grid
Let's say we are given a grid of numbers like below.
3
8
9
4
3
6
1
7
5
Finding the sum
We want to create a function that will print the sum of all these numbers. Now how do we accomplish this? We would have to loop over the array, but what type of loop would we use? To access a number in the grid, we would need two variables that point to the row and the column. Thus, the best way to accomplish this task is to use two nested for-loops, one for the row and one for the column.
The loop structure we would want to use is as follows:
Thus, all we would have to do is create a variable to hold our sum and fill out the body of the for-loop. First, let's create a variable to hold our sum.
Next, we need to add a line that will access the elements in the grid. As shown in the previous section, we can use the row and the column to pinpoint an element in the grid using get(). We can then add the element to our sum. Thus, the body of the for loop will contain:
Of course we still need to print out our sum to the console. We can just use a simple print statement:
When put together, our finished function should look something like this:
This will print out the sum, 46, to the console.
Now let's try another example.
Finding Waldo!
Let's say that we are given a grid of random objects, and we have to figure out which row and which column waldo is in. For example,
Table
Bob
Door
John
Apple
Waldo
Karel
Pencil
Book
Like above, we will be using the nested for-loop structure.
When approaching this problem, there are two questions that we need to ask. First, "How will we find Waldo?" and secondly, "What should it do once we find Waldo?".
We already know that we can access elements in the grid using get(), so we can compare the elements to "Waldo" using "==".
After we find Waldo, we can print out the row and column that we found Waldo in using println()
. Just remember that since rows and columns start from 0, we have to add 1 to both the column and the row before printing out the values.
Once we put everything together, our function should end up as:
Using our example grid, our function prints out
Last updated
Was this helpful?