Welcome to the Java Programming Forums

The professional, friendly Java community. 21,500 members and growing!

The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.

>> REGISTER NOW TO START POSTING

# Thread: Help me to understand MultiDimensional Array

1. ## Help me to understand MultiDimensional Array

Hi,

i am learning multi dimensional array and struggling to understand the output which i am getting from one of the program which i have written by seeing an example from a book. The program goes like this,

```// Demonstration of Two Dimensional Array

class TwoDArray {

public static void main(String args[]) {

int twoD[] [] = new int[4] [5];

int i, j, k = 0;

for(i=0; i<4; i++)
for(j=0; j<5; j++) {
twoD[i][j] = k;
k++;
}

for(i=0; i<4; i++) {
for(j=0; j<5; j++)
System.out.print(twoD[i][j] + " ");
System.out.println();
}
}
}```

The out put, which i am getting is,

```0 1 2 3 4
5 6 7 8 9
10 11 12 13 14
15 16 17 18 19```

i am confused that, why first two rows should contain only 5 digits and the las two rows should contain 6 digits. Also, how the numbers are incremental.

Please help me to understand in a simple manner, as the explaination given in the book is not convincing me...

--- Update ---

My bad! My apologies that i have overlooked into the result. Infact all the rows contain 5 digits.So my only doubt is now, how the numbers are incremental and what is this got something to do with for loop.

2. ## Re: Help me to understand MultiDimensional Array

Go through the code line by line and pay attention to the values of i, j, and k, which is being stored where, and which is being printed.

3. ## Re: Help me to understand MultiDimensional Array

When a two-dimensional array is created, it looks like this:

Array_Name[][] = new int[number of rows ][number of columns]

When each iteration of the nested for loop happens, the first loop will
increment the number of rows, and the bottom loop will increment the
number of columns by one with each iteration. Remember that array
counting begins at Zero not 1

4. ## Re: Help me to understand MultiDimensional Array

Okay...Thanks for your hint. Let me tell you what this mean for me and correct me if i am wrong.
Per you say, the following piece of code does the action of creating the rows and columns,
```for(i=0; i<4; i++)
for(j=0; j<5; j++)```
Here i represents row, and the array element starts with Zero, the number of rows created would be = 4(bcz <4)
Here j represents column, and the array element starts with Zero, the number of columns created would be = 5(bcz <5)

My another understanding is that, the below piece of code is going to assign a number to each element of an array and which will be represented by k,
The code used for this is,
```twoD[i][j] = k;
k++;```
The rows printed are,
0 1 2 3 4
5 6 7 8 9

Also, i have a understanding of the another set of for loop as follows,
The for loop is,
```for(i=0; i<4; i++) {
for(j=0; j<5; j++)
System.out.print(twoD[i][j] + " ");```
The rows printed are,
10 11 12 13 14
15 16 17 18 19
I think, this loop will take care of printing the array elements from the 3rd row and up-till 4th. Hence i have a question here that, what is the significance of using

the
`System.out.print(twoD[i][j]+" ");`
syntax here...does this really take care of increment the last array element of the second row?

5. ## Re: Help me to understand MultiDimensional Array

the following piece of code does the action of creating the rows and columns
Not create but iterate. The memory space for the array is reserved by this:

int twoD[] [] = new int[4] [5];

BTW, while both are acceptable to the compiler, the preferred notation is:

int[][] twoD = new int[4][5];
the below piece of code is going to assign a number to each element of an array
Absolutely!

Pretty good up to this point, but I think you're confused about the printing. The first nested for() loops assign the value k to each element of the array, incrementing k after each assignment. That's all that bit of code does.

The second set of nested for() loops iterate the array again, printing each element in 4 rows of 5 columns. I don't understand your final comment and accompanying uncertainty, so I'll say that the statement inside the nested for loops,

System.out.print(twoD[i][j]+" ");

prints each array element followed by a space so that the element values are not all scrunched together and indistinguishable from each other.

Good job! I hope I've added some understanding to the tiny bit of confusion you had. If not, ask more.

6. ## Re: Help me to understand MultiDimensional Array

Certainly you have helped me to clarify my doubts. I have understood most of the part and i have a small doubt on one of the usage of curly braces in the nested for loop, which does the action of iterating the array again and printing each element in 4 rows of 5 columns.
The curly brace in the first nested for loop starts at the end of the second row and at 4th row here.
```for(i=0; i<4; i++)
for(j=0; j<5; j++) {
twoD[i][j] = k;
k++;}```
Simillarly when i look into second nested for loop, the curly brace starts at end of the first row and ends at the fourth row.
```for(i=0; i<4; i++) {
for(j=0; j<5; j++)
System.out.print(twoD[i][j] + " ");
System.out.println();}```

I am really confused on this part. But i have this understanding.
1) In the first loop, since it has to continuosly assign a new value(k) for each element of an array from both rows and columns, the curly brace will start from end of the second row, and in the third row is again a new process of incrementing the number for each array element.
2) In the second loop, since it has to print each array element, first it will take care of printing the all the four rows and it will take care of printing the 5 coulmns as curly brace starts from end of the second row.
This is what my understanding on how the assigning of the value and printing is taken place in nested for loop. Please correct me if i am wrong by providing your valuable suggestions.
By the way i really appreciate the way you teaches. Because, readymade answers will never teach someone, rather make them lazy

7. ## Re: Help me to understand MultiDimensional Array

The way your code is indented is not correct and the lack of braces around each clause add to your confusion. I've pasted below commented nested for() loops indented differently (correctly) with each clause offset in braces. It's not mandatory to do it as I've shown, but it is easier to read, and enclosing separate clauses in braces is recommended. I hope putting the code in this form eliminates your confusion.
```// nested for() loops to iterate a 4-row by 5-column array
// myArray[][]

// the outer loop controls which row is being processed
for ( int i = 0 ; i < myArray.length ; i++ )
{
// the inner loop controls which column is being processed
for ( int j = 0 ; j < myArray.length ; j++ )
{
// print each column element followed by a space
System.out.print( myArray[i][j] + " " );
}

// print a linefeed after the last column element
// of each row
System.out.println();
}```

8. ## Re: Help me to understand MultiDimensional Array

Thank you very much. This clears all my doubt.

9. ## Re: Help me to print a pattern by using nested for loop and if condition

Hi,

i would like to print a following pattern to learn 'for loop' and 'if' statements. The pattern i am looking is,(its actually box like structure. I dont think i can show it like a box here)

* * * *
* *
* *
* * * *

I have written the following code for that by referring to the book. But i am encountered with an error.

```// Demonstration of Pattern Printing

class Pattern {

public static void main(String args[]) {
int i,j = 0;
for(i=0; i<4; i++)
{
for (j =0; j<4; j++)
{
if(i==1||i==4||j==1||j==4);
{
System.out.print('*'+" ");
else
System.out.print(" ");
}
System.out.println();
}
}
}
}```

The error which i am getting,

```Pattern.java:14: error: 'else' without 'if'
else
^
1 error```

But as per my knowldge, i have clearly defined the if and else as shown.
Please let me know, where am doing wrong.

Thanks,

10. ## Re: Help me to understand MultiDimensional Array

The semicolon at the end of the if() statement ends it, so the else that follows has no 'if' to belong to. Also, your bracing is wrong. The if and else clauses are separate clauses and should both be offset by their own bracing.

11. ## Help Required to Understand Printing Different Patterns

per you suggestion, i have modified the code as follows.

```// Demonstration of Two Dimensional Array

class MyTwoDArray2 {

public static void main(String args[]) {
int i,j = 0;
for(i=0; i<4; i++)
{
for (j =0; j<4; j++)
{
if(i==1||i==4||j==1||j==4) {
System.out.print('*'+" ");}

else {
System.out.print(" ");
}
System.out.println();
}
}
}
}```

But i am not getting expected output. The output generated is as follows,..i donno why. I am actually expecting a box like pattern.
HTML Code:
```*

*
*
*
*

*

*```

12. ## Re: Help me to understand MultiDimensional Array

This is how your code should be indented:
```// Demonstration of Two Dimensional Array

class MyTwoDArray2 {

public static void main(String args[]) {
int i,j = 0;
for(i=0; i<4; i++)
{
for (j =0; j<4; j++)
{
if(i==1||i==4||j==1||j==4) {
System.out.print('*'+" ");
}
else {
System.out.print(" ");
}
System.out.println();
}
}
}
}```
Can you see why you're getting undesired returns after each column is printed?

You can fix this, but another approach is start with printing a box of all stars. Once you have that, modify it to print spaces in the desired area(s).

13. ## Help me to understand Pattern Printing

Hello, i am back. Sorry i was unable to concentrate on this, due to my other project work.

per your suggestion i tried to modify the program in order to print spaces instead of asterisk. But i am facing so many issues. Few other issues are related to Netbean IDE. These are the issues i am facing,

1) I have installed NetBeans IDE 8.0 and trying to execute the programs. While executing, i am facing below issue very frequently,
HTML Code:
```One or more projects were complied with errors
Application you are running may end unexpectedly```
By ignoring this error, if i click on Run Anyway option, the program is sort of run but failed to produce the output.
This is what the complete program,
package pattern;

```public class Pattern {

public static void main(String[] args) {
for(int i=1;i<5;i++)
{
for(int j=1;j<5;j++)
{
if(i=2||i=3||j=2||j=3)
System.out.print(" ");
else{
System.out.print("*");
}
System.out.println();
}

}

}```

The error i am getting is,

```run:
Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - incompatible types: int cannot be converted to boolean
at pattern.Pattern.main(Pattern.java:14)
Java Result: 1
BUILD SUCCESSFUL (total time: 2 minutes 15 seconds)```

please help me what am i doing wrong with NetBeans and with respect to the program code

14. ## Re: Help me to understand MultiDimensional Array

Consider the error ("int cannot be converted to boolean") and review Java Operators to catch your error in this line:

if(i=2||i=3||j=2||j=3)

Also, add some spaces in statements like that so that they are easier to read.

15. ## Re: Help me to understand MultiDimensional Array

Hi,

Thanks for your input. Per your suggestion i made few changes and the output which i got out of that is still not according to what i expect.
This is what i have tried and this is what i got out of that,

Code:

```package mypattern;

public class MyPattern {

public static void main(String[] args) {

for(int i=1;i<=4;i++)
{

for(int j=1;j<=4;j++)

if(i==2||i==3||j==2||j==3)

System.out.print(" ");

else

System.out.print("*"+" ");

System.out.println();
}

}

}```

HTML Code:
```The out put i got,

*       *

*       *```
I mean, i could able to get the stars which are at each four corners. What am i doing wrong?

HTML Code:
```I am supppose to get below,

*  *  *  *
*         *
*         *
*  *  *  *```

--- Update ---

Eureka! i found it finally...its a lot of hard work to achieve this as a beginner.

Here you go for my code...YES! finally did it......

```public class MyPattern {

public static void main(String[] args) {

for(int i=1;i<=4;i++)
{

for(int j=1;j<=4;j++)

if(i==1||i==4||j==1||j==4)

System.out.print("*"+" ");

else

System.out.print(" "+" ");

System.out.println();
}

}

}```

YEP! finally i got a box shaped structure!

--- Update ---

THANKS A BUNCH FOR YOUR ALL HINTS AND SUGGESTIONS!

16. ## Re: Help me to understand MultiDimensional Array

Congratulations!

Now I suggest you think ahead when writing code to keep the solution as general as possible so that it is scalable, able to be sized to suit the occasion. A desirable change to this program might be to accept the user's input to determines the size of the shape rather than being fixed. In that case, the loop conditions should not use 'magic numbers' or fixed boundaries but variables that can be set to fit any general case. And this condition:

if(i==1||i==4||j==1||j==4)

can be generalized to (in words)

if ( at the first row OR at the last row OR at the first column OR at the last column )

or, another way to think of it is to specify the non-boundary areas of the square when nothing is printed.