Subjects

Subjects

More

Traversing 2D Arrays

Learn with content from all year groups and subjects, created by the best students.

Traversing 2D Arrays: AP Computer Science A Study Guide



Introduction

Hello, my code warriors! Are you ready to dive into the world of 2D arrays? Think of them like a spreadsheet where you can adventure through rows and columns, except instead of boring data entry, you get to flex your coding muscles. 💪 Let's jump in and turn those tabular labyrinths into a piece of cake! 🍰 🍪



General Form of 2D Array Traversal

When it comes to traversing 2D arrays, think of it like walking through a giant library. Each row is an aisle filled with books, and each column is a specific shelf. To explore everything, you need nested for loops: one to roam the rows, and another to stroll down the columns. Here’s the grand plan:

for (int i = 0; i < rows; i++) { // Row-major traversal
    for (int j = 0; j < cols; j++) { // Column traversal within each row
        System.out.print(array[i][j] + " ");
    }
    System.out.println(); // Move to the next row
}

Swap the outer and inner loops for Column-major traversal, and abracadabra, you’re walking down columns first. Magic, huh? ✨



Row-Major vs. Column-Major

Imagine navigating a mall 🏬. Row-major traversal is like shopping one store at a time, going through all items in each store before you mosey to the next store. Column-major traversal, on the other hand, is like speed-walking through each first item of all stores before heading to the second items, and so forth.

Row-wise traversal:

public static void rowWiseTraversal(int[][] array) {
    for (int i = 0; i < array.length; i++) { // Loop through rows
        for (int j = 0; j < array[0].length; j++) { // Loop through columns of each row
            System.out.print(array[i][j] + " ");
        }
        System.out.println();
    }
}

Column-wise traversal:

public static void columnWiseTraversal(int[][] array) {
    for (int i = 0; i < array[0].length; i++) { // Loop through columns
        for (int j = 0; j < array.length; j++) { // Loop through rows of each column
            System.out.print(array[j][i] + " ");
        }
        System.out.println();
    }
}

One small step for loops, one giant leap for array traversal!



Going in Reverse

Sometimes you need to break bad like Walter White and go backwards. When traversing arrays in reverse, simply modify your loop headers:

  • Traverse rows backward:

    for (int i = array.length - 1; i >= 0; i--) {
        // Inner loop for columns
    }
    
  • Traverse columns backward:

    for (int i = array[0].length - 1; i >= 0; i--) {
        // Inner loop for rows
    }
    

It's like moonwalking through your array! 🕺👟



Challenge Example: Snaking Around 🐍

Everything is more fun if you add some twists, like a good Snickers bar 🥜🍫. Let’s traverse our 2D array ‘snakily’:

public static void snakeTraversal(int[][] array) {
    for (int i = 0; i < array.length; i++) {
        if (i % 2 == 0) { // Even rows: left-to-right
            for (int j = 0; j < array[0].length; j++) {
                System.out.print(array[i][j] + " ");
            }
        } else { // Odd rows: right-to-left
            for (int j = array[0].length - 1; j >= 0; j--) {
                System.out.print(array[i][j] + " ");
            }
        }
        System.out.println();
    }
}

Slither through your data and bask in the glory of alternating traversal!



Standard Algorithms Using Traversals

Let’s flex those standard algorithm muscles like we’re at a coding gym! 🏋️‍♂️

Sequential/Linear Search:

public static boolean searchElement(int[][] array, int element) {
    for (int i = 0; i < array.length; i++) {
        for (int j = 0; j < array[0].length; j++) {
            if (array[i][j] == element) {
                System.out.println("Found at: Row " + i + ", Column " + j);
                return true;
            }
        }
    }
    return false;
}

Modifying Array Values:

Double all elements like pumping them up with steroids 💪:

public static void doubleElements(int[][] array) {
    for (int i = 0; i < array.length; i++) {
        for (int j = 0; j < array[0].length; j++) {
            array[i][j] *= 2;
        }
    }
}

Enhanced for loops won’t work here because they only copy the values. Remember, a copycat array is not our friend!

Finding Maximum and Minimum:

Just like in school, let’s find the biggest and smallest kids in our data playground 🏫:

public static int findMax(int[][] array) {
    int maxValue = array[0][0];
    for (int[] row : array) {
        for (int num : row) {
            if (num > maxValue) {
                maxValue = num;
            }
        }
    }
    return maxValue;
}

public static int findMin(int[][] array) {
    int minValue = array[0][0];
    for (int[] row : array) {
        for (int num : row) {
            if (num < minValue) {
                minValue = num;
            }
        }
    }
    return minValue;
}

Don't initialize maxValue or minValue with 0, because 0 can be an imposter! 🤫

Summing and Finding the Mean:

No, I’m not calling you mean 👍:

public static int sumArray(int[][] array) {
    int sum = 0;
    for (int[] row : array) {
        for (int num : row) {
            sum += num;
        }
    }
    return sum;
}

public static double findMean(int[][] array) {
    int totalSum = sumArray(array);
    return (double) totalSum / (array.length * array[0].length);
}

Finding Mode:

Revisit that mode you loved in elementary school (No, not fashion mode!) 👗:

public static int findMode(int[][] array) {
    int[] newArray = putInto1DArray(array);
    int mostCommon = newArray[0];
    int maxCount = 1;

    for (int i = 0; i < newArray.length; i++) {
        int count = 0;
        for (int j = 0; j < newArray.length; j++) {
            if (newArray[i] == newArray[j]) {
                count++;
            }
        }
        if (count > maxCount) {
            maxCount = count;
            mostCommon = newArray[i];
        }
    }
    return mostCommon;
}


Fun Fact

Did you know that arrays can be like party invitations? They allow you to bring your friends (values) together in a grid, but remember, you must keep them organized—no sneaking in! 😜

So, conquer that 2D array like a boss, and remember, each loop is a step closer to mastering the grid! 🕹️💡 Happy coding, everyone! 🚀

Knowunity is the # 1 ranked education app in five European countries

Knowunity was a featured story by Apple and has consistently topped the app store charts within the education category in Germany, Italy, Poland, Switzerland and United Kingdom. Join Knowunity today and help millions of students around the world.

Ranked #1 Education App

Download in

Google Play

Download in

App Store

Knowunity is the # 1 ranked education app in five European countries

4.9+

Average App Rating

13 M

Students use Knowunity

#1

In Education App Charts in 12 Countries

950 K+

Students uploaded study notes

Still not sure? Look at what your fellow peers are saying...

iOS User

I love this app so much [...] I recommend Knowunity to everyone!!! I went from a C to an A with it :D

Stefan S, iOS User

The application is very simple and well designed. So far I have found what I was looking for :D

SuSSan, iOS User

Love this App ❤️, I use it basically all the time whenever I'm studying

Can't find what you're looking for? Explore other subjects.