Search code examples
nested-loops

Understanding nested loops


We were given a task in my computing class to manipulate images through its pixels, and I literally did not know where to start, which made me realise that I have a lack of understanding of nested loops.

I understand how normal for loops work, but I struggle to understand the functionality of a loop 'looping' another loop. I have watched through these tutorials on Youtube where they would create patterns using nested loops, but they hardly explain the process behind it.

What is the simplest way of understanding it?


Solution

  • Let's say you have a table of students and their grades on all homework assignments, for example.

            Homework Grades
    Student HW1  HW2  HW3  HW4
    A       90   80   78   64
    B       70   65   58   54
    C       96   88   98   84
    D       96   85   72   68
    

    Let's say that you want to calculate the average grade of a homework assignment for this course.

    Now, each student has a number of different grades for their homework assignments. We know that the total number of assignment grades is equivalent to the number of assignments * the number of students, so the average grade of any homework assignment is the total sum of all grades divided by the number of grades.

    We can either aggregate via Student or by Homework. In this case, we will aggregate by Student. We will assume that the data is stored in a 2D array called allgrades, indexed first by Student and then by Homework Assignment.

    This can be done with a for loop.

    for (int i = 0; i < allgrades.length; i += 1) {
    
    }
    

    Now we want to retrieve the grades for each student. If we get the array of grades for a student studentgrades, we can do the following to get the sum of a student's grades for all their assignments:

    let sumgrades = 0;
    for (int j = 0; j < studentgrades.length; j += 1) {
        sumgrades += studentgrades[j];
    }
    

    Now if we want to extend this to all students, we can nest this inside the other for loop to aggregate all of the grades.

    let sumgrades = 0;
    for (int i = 0; i < allgrades.length; i += 1) {
        let studentgrades = allgrades[i];
        for (int j = 0; j < studentgrades.length; j += 1) {
            sumgrades += studentgrades[j];
        }
    }
    

    At the end of this code, all that needs to be done to get the average grade on any assignment is to divide sumgrades - the aggregate, by the number of assignments * the number of students.

    This aggregation is an example of a nested loop.

    To give an example in regards to image manipulation, let's say that we want to take an image and halve the RGB values of each pixel.

    We can iterate over the first dimension of the image (essentially a 2D array) in one loop, and in a nested loop, iterate over the other dimension.

    for (int i = 0; i < canvasWidth; i += 1) {
      for (int j = 0; j < canvasHeight; j += 1) {
        Pixel oldpixel = pixel(i, j);
        Pixel newpixel = Pixel();
        int newred = oldpixel.r/2;
        int newgrn = oldpixel.g/2;
        int newblu = oldpixel.b/2;
    
        newpixel.r = newred;
        newpixel.g = newgrn;
        newpixel.b = newblu;
    
        outputImage.pixel(i, j) = newpixel;
      }
    }
    

    This does a nested loop over the image, getting values from the individual pixels and using that data.

    I hope this answer provided a sufficient example for understanding nested loop usage.