Jump to content


Check out our Community Blogs

Register and join over 40,000 other developers!


Recent Status Updates

View All Updates

Photo
- - - - -

Multidimensional Arrays

align array

  • Please log in to reply
22 replies to this topic

#1 chili5

chili5

    CC Mentor

  • Expert Member
  • PipPipPipPipPipPipPipPip
  • 3038 posts
  • Programming Language:Java, C#, PHP, JavaScript, Ruby, Transact-SQL
  • Learning:C, Java, C++, C#, PHP, JavaScript, Ruby, Transact-SQL, Assembly, Scheme, Haskell, Others

Posted 17 March 2009 - 06:06 AM

Multi-dimensional Arrays

This is a tutorial about multi-dimensional arrays, however a quick review of 1-dimensional arrays. The understanding of a 1-dimensional array is crucial to understanding 2 and 3-dimensional arrays.

When you first learn about arrays in a programming language, you think of a bunch of blocks. That are containers for similar variables. This is a 1 dimensional array.

Posted Image

That is a representation of a 1-dimensional array that can hold 6 elements. With arrays you can access items by position not content. Thus the array is the basic data structure that is used in the implementation of more complicated data structures like linked structures and hash tables.

In Java and other languages this array is declared like this:

int[] arnNums = new int[6]; // an array that can hold 6 elements

If you are used to C++ you might see this written as:

int arnNums[] = new int[6];

Both of these forms are acceptable, use whichever you would like.

Populating the array

int[] arnNums = {0,1,2,3,4,5}; // declaring and initializing an array to hold 6 elements

You can also use a loop to populate the array.

Example:

for (int i=0;i<6;i++) {
	arnNums[i] = i;
}

You can access how many elements are in the array by using the length property.

arnNums.length; // returns 6 since there are 6 elements in the array.

Before you continue try this problem to make sure you have this concept down.


1. Have the user input 10 numbers. Positive and negative numbers are allowed. The numbers will all be real numbers. With this set of 10 numbers you want to calculate:
a) Integer Mean (Don't use reals)
B) Median
c) Largest number
d) Smallest number
e) Number of even numbers
f) Number of odd numbers


Two-dimensional Array

A two dimensional array is really just an array of an array. So each element in the array is an 1-dimensional array. Think of a 2-dimensional array as a grid like a chessboard.

Example:

Posted Image

This diagram is showing how each element has 2 indexes not 1. This is what makes it a 2-dimensional array.

Remember that is really just an array of arrays. The first number says what sub array the element is in, and the second index tells the exact number in the array.

You can populate a 2d array using the brace bracket notation in the same manner as a 1 dimensional array.

Posted Image

This diagram shows what value is located at each position in the array. So there is a 5 at [0,0], [0,1], [0,2], etc.

The above array can be constructed like this:

int[][] arnGrid = { 
{5,5,5,5,5,5},
{5,5,5,5,5,5},
{4,3,3,2,1,-5},
{2,2,2,5,2,3}
};

Since each element of the array is really just another array. We can get the number of elements in each individual sub array by using:
arnGrid[0].length

We can also get the number of sub arrays by using:

arnGrid.length

This allows us to perform a loop through the entire array printing the grid.

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

So the outer loop executes once for each sub array in the 2-dimensional array. Then the inner loop executes once for each element in the sub array. The output is:

5 5 5 5 5 5
5 5 5 5 5 5
4 3 3 2 1 -5
2 2 2 5 2 3


So can you get the user to input numbers and store them in the array?


Note that you can also declare a 2-dimensional array like this:

int[][] arnNums = new int[5][6];

This means that there will be 5 subarrays which will each hold 6 elements.

This can also be written in C++ style as:

int arnNums[][] = new int[5][6];

Before we move on any farther let's try a few challenges:

1. Create a multiplication table. Have the user enter two numbers 5 <= x <= 7 and 7 <= y <= 9
The program will create a multiplication table from 0*x-1 to x-1*y-1. Make sure you get the alignments correct.

For example:

x = 3
y = 5

I want to create a table from 0*3 to 2*4:

0 0 0 0 0
0 1 2 3 4
0 2 4 6 8

Assume that you are required to store the multiplication table for later use.

2. Have the user enter a 2-dimensional array of numbers and determine if it's a magic square. The user will enter 2 numbers x and y which can be at maximum 50,000. A magic square is a grid where all the rows, columns and diagonals add to the same number.


Navigating 2-Dimensional Arrays

I like to keep two arrays one array that holds information on how I can move left or right in the grid, and another array that holds information on how to move up or down. These are two integer arrays that can only hold 1, 0, or -1. 0 means that I am not moving in that direction. 1 means that I am moving either left or up. -1 means that I am moving down or right.

Example:

int[] x = {0,1,0,-1};
int[] y = {1,0,-1,0};

This covers the four main directions: "north", "east", "south" and "west". To move north 1 in the array I add 1to the "y" coordinate and x doesn't change. To move east I add 1 to the x coordinate and y does not change. This covers moving in the four main directions. Now I can easily move in north-east and other directions similar to that.

A for loop allows me to loop around a current square in all directions.

for (nDir=0;nDir<4;nDir++) {
	dx = x; // current x coordinate
	dy = y; // current y coordinate
	dx += x[nDir]; // changing x coordinate to one of the squares around [dx][dy]
	dy += y[nDir]; // changing y coordinate to one of the squares around [dx][dy]

	// now it is very important to make sure we have not gone out of bounds
	if (dx < 0 || dx > 5 || dy < 0 || dy > 6) {
		// this is out of bounds so we don't go any further
		continue;
	}
	// in bounds so continue processing here
}

Note that it is very important to reset the coordinates of where you are every time. Also bounds checking is important. We don't want to check if a square is a mine if it is not in the grid.

A quick note in Java, a string is an array of characters so an array of strings is a 2d array.

The 2-Dimensional Array comes in handy when implementing graphs.

Now have some fun with 2-dimensional array problems:

http://dwite.ca/old/...lem2Jan2005.pdf
http://dwite.ca/old/...lem3Nov2002.pdf
http://dwite.ca/old/...lem4Oct2002.pdf
http://dwite.ca/old/...lem4Oct2005.pdf

It might be fun to talk about my various challenges and the DWITE questions. :)

James

Some resources:

Arrays (Java 2 Platform SE v1.4.2)
Multi-Dimensional Arrays
Javanotes 5.0, Section 7.5 -- Multi-dimensional Arrays
  • 5

#2 WingedPanther73

WingedPanther73

    A spammer's worst nightmare

  • Moderator
  • 17757 posts
  • Location:Upstate, South Carolina
  • Programming Language:C, C++, PL/SQL, Delphi/Object Pascal, Pascal, Transact-SQL, Others
  • Learning:Java, C#, PHP, JavaScript, Lisp, Fortran, Haskell, Others

Posted 17 March 2009 - 08:08 AM

+rep for you! Come back, one day!
  • 0

Programming is a branch of mathematics.
My CodeCall Blog | My Personal Blog

My MineCraft server site: http://banishedwings.enjin.com/


#3 Guest_Jordan_*

Guest_Jordan_*
  • Guest

Posted 17 March 2009 - 08:12 AM

Very informative tutorial! +rep.
  • 0

#4 fread

fread

    Programming God

  • Senior Member
  • PipPipPipPipPipPip
  • 897 posts
  • Location:Trinidad and Tobago
  • Learning:C, Java, C++, C#, PHP, Python, PL/SQL

Posted 17 March 2009 - 08:13 AM

Sweet :cool:
  • 0

#5 chili5

chili5

    CC Mentor

  • Expert Member
  • PipPipPipPipPipPipPipPip
  • 3038 posts
  • Programming Language:Java, C#, PHP, JavaScript, Ruby, Transact-SQL
  • Learning:C, Java, C++, C#, PHP, JavaScript, Ruby, Transact-SQL, Assembly, Scheme, Haskell, Others

Posted 17 March 2009 - 08:19 AM

Great thanks everyone!

What do you mean "Come back, one day!"?
  • 0

#6 WingedPanther73

WingedPanther73

    A spammer's worst nightmare

  • Moderator
  • 17757 posts
  • Location:Upstate, South Carolina
  • Programming Language:C, C++, PL/SQL, Delphi/Object Pascal, Pascal, Transact-SQL, Others
  • Learning:Java, C#, PHP, JavaScript, Lisp, Fortran, Haskell, Others

Posted 17 March 2009 - 10:44 AM

It's a reference to the "Soup **" Seinfield episode. Basically: I expect a new tutorial tomorrow.
  • 0

Programming is a branch of mathematics.
My CodeCall Blog | My Personal Blog

My MineCraft server site: http://banishedwings.enjin.com/


#7 chili5

chili5

    CC Mentor

  • Expert Member
  • PipPipPipPipPipPipPipPip
  • 3038 posts
  • Programming Language:Java, C#, PHP, JavaScript, Ruby, Transact-SQL
  • Learning:C, Java, C++, C#, PHP, JavaScript, Ruby, Transact-SQL, Assembly, Scheme, Haskell, Others

Posted 17 March 2009 - 12:06 PM

Okay sure! :) Any ideas for a topic?
  • 0

#8 WingedPanther73

WingedPanther73

    A spammer's worst nightmare

  • Moderator
  • 17757 posts
  • Location:Upstate, South Carolina
  • Programming Language:C, C++, PL/SQL, Delphi/Object Pascal, Pascal, Transact-SQL, Others
  • Learning:Java, C#, PHP, JavaScript, Lisp, Fortran, Haskell, Others

Posted 17 March 2009 - 12:15 PM

Not off hand... 4 dimensional arrays?
  • 0

Programming is a branch of mathematics.
My CodeCall Blog | My Personal Blog

My MineCraft server site: http://banishedwings.enjin.com/


#9 chili5

chili5

    CC Mentor

  • Expert Member
  • PipPipPipPipPipPipPipPip
  • 3038 posts
  • Programming Language:Java, C#, PHP, JavaScript, Ruby, Transact-SQL
  • Learning:C, Java, C++, C#, PHP, JavaScript, Ruby, Transact-SQL, Assembly, Scheme, Haskell, Others

Posted 17 March 2009 - 12:23 PM

Sure sounds good. :D It would be good to write about something I don't already know about. :)
  • 0

#10 Brandon W

Brandon W

    CC Mentor

  • Expert Member
  • PipPipPipPipPipPipPipPip
  • 2092 posts
  • Location:Ipswich, Australia
  • Programming Language:C, Java
  • Learning:Java, C++, JavaScript

Posted 18 March 2009 - 04:40 AM

Yet another excellent tutorial of yours mate. They are always so highly detailed and understandable even thought I don't know Java.

Thank-you. +rep
  • 0
I've returned...

#11 Termana

Termana

    CC Devotee

  • Just Joined
  • PipPipPipPipPipPip
  • 971 posts

Posted 18 March 2009 - 05:06 AM

Great tutorial Chili - +rep
  • 0

Interested in participating in community events?
Want to harness your programming skill and turn it into absolute prowess?
Come join our programming events!


#12 chili5

chili5

    CC Mentor

  • Expert Member
  • PipPipPipPipPipPipPipPip
  • 3038 posts
  • Programming Language:Java, C#, PHP, JavaScript, Ruby, Transact-SQL
  • Learning:C, Java, C++, C#, PHP, JavaScript, Ruby, Transact-SQL, Assembly, Scheme, Haskell, Others

Posted 18 March 2009 - 05:11 AM

Excellent! Hope it helps.

Thanks guys! :D
  • 0





Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download