0

I'm trying to do a two dimensional for loop that with print this:

7 5 3 1

2 4 6 8

Here is my array:

int [][] secondArray = {{7, 5, 3, 1}, {2, 4, 6, 8}};

The for loop below will only print it one number after the other. Not all on one straight line. I have tried playing around with it. Like making two print statements. On for i and j. Or doing a "\t". I'm just learning arrays and this for loop was the closest example I got online.

 for(int i = 0; i < secondArray.length ; i++)
     {

            for(int j = 0; j < secondArray[i].length; j++)
            {

                System.out.println(secondArray[i][j]);

            }

     }

Edit: I guess I should put that I understand how for loops work. It goes through each number and prints it. I guess my question is, how else would I do this?

4
  • Use System.out.print instead of System.out.println, also loop is not two dimensional, the array is two dimensional, and to iterate that array you are using two nested loops. Commented Nov 19, 2017 at 3:12
  • Ah thanks... An obvious beginner mistake that I wasn't even thinking about. I thought my problem lied much deeper! Commented Nov 19, 2017 at 3:15
  • 1
    It should look something like this: pastebin.com/wiKPCJTW Commented Nov 19, 2017 at 3:17
  • The for loop below will only print it one number after the other. Not all on one straight line then it should be System.out.print(secondArray[i][j] + " "); Commented Nov 19, 2017 at 3:59

3 Answers 3

2

Use a foreach loop and print a line everytime you jump from one inner array to another:

for(int[] a : secondArray) {
      for(int b : a) {
        System.out.print(b);
        System.out.print(' ');
      }
      System.out.println();
}
Sign up to request clarification or add additional context in comments.

Comments

1

Use System.out.print() instead of System.out.println() if you don't want to the next output to be from next line.

Code

for(int i = 0; i < secondArray.length ; i++) {
    for(int j = 0; j < secondArray[i].length; j++) {
         System.out.print(secondArray[i][j] + " ");
    }
    System.out.println();
}

Comments

0

this also works..

  int [][] secondArray = {{7, 5, 3, 1}, {2, 4, 6, 8}};

     for (int i = 0; i < secondArray.length ; i++)
     {

         for(int j = 0; j < secondArray[i].length; j++)
         {
             System.out.print(secondArray[i][j]);
             System.out.print(' ');

       }

         System.out.println();
     }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.