Create a two-dimensional array at runtime: Difference between revisions

From Rosetta Code
Content added Content deleted
m (→‎{{header|JavaScript}}: spidermonkey's javascript implementation has print/readline)
m (Fixed lang tags.)
Line 4: Line 4:


=={{header|Ada}}==
=={{header|Ada}}==
<lang ada>
<lang ada>with Ada.Text_Io; use Ada.Text_Io;
with Ada.Text_Io; use Ada.Text_Io;
with Ada.Float_Text_Io; use Ada.Float_Text_Io;
with Ada.Float_Text_Io; use Ada.Float_Text_Io;
with Ada.Integer_Text_Io; use Ada.Integer_Text_Io;

with Ada.Integer_Text_Io; use Ada.Integer_Text_Io;
procedure Two_Dimensional_Arrays is
type Matrix_Type is array(Positive range <>, Positive range <>) of Float;
procedure Two_Dimensional_Arrays is
Dim_1 : Positive;
type Matrix_Type is array(Positive range <>, Positive range <>) of Float;
Dim_1 : Positive;
Dim_2 : Positive;
begin
Dim_2 : Positive;
Get(Item => Dim_1);
begin
Get(Item => Dim_1);
Get(Item => Dim_2);
-- Create an inner block with the correctly sized array
Get(Item => Dim_2);
declare
-- Create an inner block with the correctly sized array
Matrix : Matrix_Type(1..Dim_1, 1..Dim_2);
declare
begin
Matrix : Matrix_Type(1..Dim_1, 1..Dim_2);
Matrix(1, Dim_2) := 3.14159;
begin
Matrix(1, Dim_2) := 3.14159;
Put(Item => Matrix(1, Dim_2), Fore => 1, Aft => 5, Exp => 0);
New_Line;
Put(Item => Matrix(1, Dim_2), Fore => 1, Aft => 5, Exp => 0);
New_Line;
end;
-- The variable Matrix is popped off the stack automatically
end;
end Two_Dimensional_Arrays;</lang>
-- The variable Matrix is popped off the stack automatically
end Two_Dimensional_Arrays;
</lang>


=={{header|ALGOL 68}}==
=={{header|ALGOL 68}}==
main:(
<lang algol68>main:(
print("Input two positive whole numbers separated by space and press newline:");
print("Input two positive whole numbers separated by space and press newline:");
[read int,read int] INT array;
[read int,read int] INT array;
array[1,1]:=42;
array[1,1]:=42;
print (array[1,1])
print (array[1,1])
)</lang>
)


=={{header|AWK}}==
=={{header|AWK}}==
Line 64: Line 62:


=={{header|C}}==
=={{header|C}}==
<lang c>
<lang c>#include <stdio.h>
#include <stdio.h>


int main(int argc, char **argv) {
int main(int argc, char **argv) {
Line 77: Line 74:


return 0;
return 0;
}</lang>
}
</lang>


=={{header|C++}}==
=={{header|C++}}==
With language built-in facilities:
With language built-in facilities:


<lang cpp> #include <iostream>
<lang cpp>#include <iostream>
#include <istream>
#include <istream>
#include <ostream>
#include <ostream>

int main()
int main()
{
{
// read values
// read values
int dim1, dim2;
int dim1, dim2;
std::cin >> dim1 >> dim2;
std::cin >> dim1 >> dim2;

// create array
// create array
double* array_data = new double[dim1*dim2];
double* array_data = new double[dim1*dim2];
double** array = new double*[dim1];
double** array = new double*[dim1];
for (int i = 0; i < dim1; ++i)
for (int i = 0; i < dim1; ++i)
array[i] = array_data + dim2*i;
array[i] = array_data + dim2*i;

// write element
// write element
array[0][0] = 3.5;
array[0][0] = 3.5;

// output element
// output element
std::cout << array[0][0] << std::endl;
std::cout << array[0][0] << std::endl;

// get rid of array
// get rid of array
delete[] array;
delete[] array;
delete[] array_data;
delete[] array_data;
}</lang>
}</lang>


Using std::vector from the standard library:
Using std::vector from the standard library:


<lang cpp> #include <iostream>
<lang cpp>#include <iostream>
#include <istream>
#include <istream>
#include <ostream>
#include <ostream>
#include <vector>
#include <vector>

int main()
int main()
{
{
// read values
// read values
int dim1, dim2;
int dim1, dim2;
std::cin >> dim1 >> dim2;
std::cin >> dim1 >> dim2;

// create array
// create array
std::vector<std::vector<double> > array(dim1, std::vector<double>(dim2));
std::vector<std::vector<double> > array(dim1, std::vector<double>(dim2));

// write element
// write element
array[0][0] = 3.5;
array[0][0] = 3.5;

// output element
// output element
std::cout << array[0][0] << std::endl;
std::cout << array[0][0] << std::endl;

// the array is automatically freed at the end of main()
// the array is automatically freed at the end of main()
}</lang>
}</lang>


=={{header|D}}==
=={{header|D}}==
<lang d>import std.stdio: writef, writefln, readln;
<lang d>
import std.stdio: writef, writefln, readln;
import std.conv: toInt;
import std.conv: toInt;
import std.string: strip;
import std.string: strip;
Line 151: Line 146:
array[0][0] = 3.5;
array[0][0] = 3.5;
writefln("The number at place [0 0] is ", array[0][0]);
writefln("The number at place [0 0] is ", array[0][0]);
}</lang>
}
</lang>


=={{header|Clean}}==
=={{header|Clean}}==
<lang clean> import StdEnv
<lang clean>import StdEnv

Start :: *World -> { {Real} }
Start :: *World -> { {Real} }
Start world
Start world
# (console, world) = stdio world
# (console, world) = stdio world
(_, dim1, console) = freadi console
(_, dim1, console) = freadi console
(_, dim2, console) = freadi console
(_, dim2, console) = freadi console
= createArray dim1 (createArray dim2 1.0)</lang>
= createArray dim1 (createArray dim2 1.0)</lang>


=={{header|Common Lisp}}==
=={{header|Common Lisp}}==
<lang lisp> (let ((d1 (read))
<lang lisp>(let ((d1 (read))
(d2 (read)))
(d2 (read)))
(assert (and (typep d1 '(integer 1))
(assert (and (typep d1 '(integer 1))
(typep d2 '(integer 1)))
(typep d2 '(integer 1)))
(d1 d2))
(d1 d2))
(let ((array (make-array (list d1 d2) :initial-element nil))
(let ((array (make-array (list d1 d2) :initial-element nil))
(p1 0)
(p1 0)
(p2 (floor d2 2)))
(p2 (floor d2 2)))
(setf (aref array p1 p2) t)
(setf (aref array p1 p2) t)
(print (aref array p1 p2))))</lang>
(print (aref array p1 p2))))</lang>


The <tt>[http://www.lispworks.com/documentation/HyperSpec/Body/m_assert.htm assert]</tt> will allow the user to reenter the dimensions if they are not positive integers.
The <tt>[http://www.lispworks.com/documentation/HyperSpec/Body/m_assert.htm assert]</tt> will allow the user to reenter the dimensions if they are not positive integers.


=={{header|Forth}}==
=={{header|Forth}}==
<lang forth> : cell-matrix
<lang forth>: cell-matrix
create ( width height "name" ) over , * cells allot
create ( width height "name" ) over , * cells allot
does> ( x y -- addr ) dup cell+ >r @ * + cells r> + ;
does> ( x y -- addr ) dup cell+ >r @ * + cells r> + ;

5 5 cell-matrix test
5 5 cell-matrix test

36 0 0 test !
36 0 0 test !
0 0 test @ . \ 36</lang>
0 0 test @ . \ 36</lang>


{{libheader|Forth Scientific Library}}
{{libheader|Forth Scientific Library}}
<lang forth>
<lang forth>INTEGER DMATRIX my-matrix{{
INTEGER DMATRIX my-matrix{{
& my-matrix{{ 8 9 }}malloc

& my-matrix{{ 8 9 }}malloc
8 my-matrix{{ 3 4 }} !
8 my-matrix{{ 3 4 }} !
my-matrix{{ 3 4 }} @ .

my-matrix{{ 3 4 }} @ .
& my-matrix{{ }}free</lang>
& my-matrix{{ }}free
</lang>


=={{header|Fortran}}==
=={{header|Fortran}}==
In Fortran 90 and later
In Fortran 90 and later
<lang fortran> PROGRAM Example
<lang fortran>PROGRAM Example

IMPLICIT NONE
INTEGER :: rows, columns, errcheck
INTEGER, ALLOCATABLE :: array(:,:)

WRITE(*,*) "Enter number of rows"
READ(*,*) rows
WRITE(*,*) "Enter number of columns"
READ(*,*) columns
ALLOCATE (array(rows,columns), STAT=errcheck) ! STAT is optional and is used for error checking
IMPLICIT NONE
INTEGER :: rows, columns, errcheck
INTEGER, ALLOCATABLE :: array(:,:)
array(1,1) = 42
WRITE(*,*) "Enter number of rows"
READ(*,*) rows
WRITE(*,*) "Enter number of columns"
READ(*,*) columns
ALLOCATE (array(rows,columns), STAT=errcheck) ! STAT is optional and is used for error checking
array(1,1) = 42
WRITE(*,*) array(1,1)
DEALLOCATE (array, STAT=errcheck)
WRITE(*,*) array(1,1)
END PROGRAM Example</lang>
DEALLOCATE (array, STAT=errcheck)

END PROGRAM Example</lang>


=={{header|Haskell}}==
=={{header|Haskell}}==
Line 229: Line 221:
The following is only for demonstration. No real program should just assume that the user input is valid, integer, large enough etc.
The following is only for demonstration. No real program should just assume that the user input is valid, integer, large enough etc.
<lang idl> read, x, prompt='Enter x size:'
<lang idl>read, x, prompt='Enter x size:'
read, y, prompt='Enter y size:'
read, y, prompt='Enter y size:'
d = fltarr(x,y)
d = fltarr(x,y)

d[3,4] = 5.6
d[3,4] = 5.6
print,d[3,4]
print,d[3,4]
;==> outputs 5.6
;==> outputs 5.6

delvar, d</lang>
delvar, d</lang>


=={{header|J}}==
=={{header|J}}==


In J, all aspects of arrays are resolved through evaluation. Everything counts as being given at run time.
In J, all aspects of arrays are resolved through evaluation. Everything counts as being given at run time.
<lang j> task=: 3 : 0
<lang j>task=: 3 : 0
'init new' =. 0;1 NB. values for initialization and alteration
'init new' =. 0;1 NB. values for initialization and alteration
array =. y $ init NB. create array of shape y
array =. y $ init NB. create array of shape y
element =. < ? $ array NB. pick an atom of the array at random
element =. < ? $ array NB. pick an atom of the array at random
array =. new element } array NB. amend that element to new value
array =. new element } array NB. amend that element to new value
element { array NB. return value of changed element
element { array NB. return value of changed element
)</lang>
)</lang>
Passing two integers to <tt>task</tt> (as a list) satisfies the specifications for a two-dimensional array, but providing a longer list of integers accomplishes the same task on an array of as many dimensions as the count of integers given.
Passing two integers to <tt>task</tt> (as a list) satisfies the specifications for a two-dimensional array, but providing a longer list of integers accomplishes the same task on an array of as many dimensions as the count of integers given.


The type of the array is determined by the type of the values used in filling the array. E.g., alternate data types are obtained by substituting any of the following lines:
The type of the array is determined by the type of the values used in filling the array. E.g., alternate data types are obtained by substituting any of the following lines:
<lang j> 'init new' =. ' ';'x' NB. literals
<lang j>'init new' =. ' ';'x' NB. literals
'init new' =. 1r2;2r3 NB. fractions
'init new' =. 1r2;2r3 NB. fractions
'init new' =. a: ; <<'Rosetta' NB. boxes</lang>
'init new' =. a: ; <<'Rosetta' NB. boxes</lang>


=={{header|Java}}==
=={{header|Java}}==


<lang java> import java.util.Scanner;
<lang java>import java.util.Scanner;

public class twoDimArray {
public class twoDimArray {
public static void main(String[] args) {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Scanner in = new Scanner(System.in);
int nbr1 = in.nextInt();
int nbr1 = in.nextInt();
int nbr2 = in.nextInt();
int nbr2 = in.nextInt();
double[][] array = new double[nbr1][nbr2];
double[][] array = new double[nbr1][nbr2];
array[0][0] = 42.0;
array[0][0] = 42.0;
System.out.println("The number at place [0 0] is " + array[0][0]);
System.out.println("The number at place [0 0] is " + array[0][0]);
}
}
}</lang>
}</lang>


=={{header|JavaScript}}==
=={{header|JavaScript}}==
Line 302: Line 294:
return print(prompt);
return print(prompt);
}
}
}</lang>
}
</lang>


=={{header|Logo}}==
=={{header|Logo}}==
{{works with|UCB Logo}}
{{works with|UCB Logo}}
<lang logo> make "a2 mdarray [5 5]
<lang logo>make "a2 mdarray [5 5]
mdsetitem [1 1] :a2 0 ; by default, arrays are indexed starting at 1
mdsetitem [1 1] :a2 0 ; by default, arrays are indexed starting at 1
print mditem [1 1] :a2 ; 0</lang>
print mditem [1 1] :a2 ; 0</lang>


=={{header|MAXScript}}==
=={{header|MAXScript}}==
a = getKBValue prompt:"Enter first dimension:"
<lang maxscript>a = getKBValue prompt:"Enter first dimension:"
b = getKBValue prompt:"Enter second dimension:"
b = getKBValue prompt:"Enter second dimension:"
arr1 = #()
arr1 = #()
arr2 = #()
arr2 = #()
arr2[b] = undefined
arr2[b] = undefined
for i in 1 to a do
for i in 1 to a do
(
(
append arr1 (deepCopy arr2)
append arr1 (deepCopy arr2)
)
)
arr1[a][b] = 1
arr1[a][b] = 1
print arr1[a][b]
print arr1[a][b]</lang>


=={{header|Objective-C}}==
=={{header|Objective-C}}==
Line 363: Line 354:
=={{header|OCaml}}==
=={{header|OCaml}}==


<lang ocaml> let nbr1 = read_int ();;
<lang ocaml>let nbr1 = read_int ();;
let nbr2 = read_int ();;
let nbr2 = read_int ();;
let array = Array.make_matrix nbr1 nbr2 0.0;;
let array = Array.make_matrix nbr1 nbr2 0.0;;
array.(0).(0) <- 3.5;;
array.(0).(0) <- 3.5;;
print_float array.(0).(0); print_newline ();;</lang>
print_float array.(0).(0); print_newline ();;</lang>


=={{header|Pascal}}==
=={{header|Pascal}}==
Line 374: Line 365:
The following code is standard Extended Pascal (tested with <tt>gpc --extended-pascal</tt>):
The following code is standard Extended Pascal (tested with <tt>gpc --extended-pascal</tt>):


<lang pascal> program array2d(input, output);
<lang pascal>program array2d(input, output);

type
type
tArray2d(dim1, dim2: integer) = array[1 .. dim1, 1 .. dim2] of real;
tArray2d(dim1, dim2: integer) = array[1 .. dim1, 1 .. dim2] of real;
pArray2D = ^tArray2D;
pArray2D = ^tArray2D;

var
var
d1, d2: integer;
d1, d2: integer;
data: pArray2D;
data: pArray2D;

begin
begin
{ read values }
{ read values }
readln(d1, d2);
readln(d1, d2);

{ create array }
{ create array }
new(data, d1, d2);
new(data, d1, d2);

{ write element }
{ write element }
data^[1,1] := 3.5;
data^[1,1] := 3.5;

{ output element }
{ output element }
writeln(data^[1,1]);
writeln(data^[1,1]);

{ get rid of array }
{ get rid of array }
dispose(data);
dispose(data);
end.</lang>
end.</lang>




Line 407: Line 398:
Predefining an array (or multi-dimension array) size is unnecessary, Perl dynamically resizes the array to meet the requirements. Of course I'm assuming that the user is entering array size 0 based.
Predefining an array (or multi-dimension array) size is unnecessary, Perl dynamically resizes the array to meet the requirements. Of course I'm assuming that the user is entering array size 0 based.


<lang perl> sub make_array($ $){
<lang perl>sub make_array($ $){
# get array sizes from provided params, but force numeric value
# get array sizes from provided params, but force numeric value
my $x = ($_[0] =~ /^\d+$/) ? shift : 0;
my $x = ($_[0] =~ /^\d+$/) ? shift : 0;
my $y = ($_[0] =~ /^\d+$/) ? shift : 0;
my $y = ($_[0] =~ /^\d+$/) ? shift : 0;
# define array, then add multi-dimensional elements
# define array, then add multi-dimensional elements
my @array;
my @array;
$array[0][0] = 'X '; # first by first element
$array[0][0] = 'X '; # first by first element
$array[5][7] = 'X ' if (5 <= $y and 7 <= $x); # sixth by eighth element, if the max size is big enough
$array[5][7] = 'X ' if (5 <= $y and 7 <= $x); # sixth by eighth element, if the max size is big enough
$array[12][15] = 'X ' if (12 <= $y and 15 <= $x); # thirteenth by sixteenth element, if the max size is big enough
$array[12][15] = 'X ' if (12 <= $y and 15 <= $x); # thirteenth by sixteenth element, if the max size is big enough
# loop through the elements expected to exist base on input, and display the elements contents in a grid
# loop through the elements expected to exist base on input, and display the elements contents in a grid
foreach my $dy (0 .. $y){
foreach my $dy (0 .. $y){
foreach my $dx (0 .. $x){
foreach my $dx (0 .. $x){
(defined $array[$dy][$dx]) ? (print $array[$dy][$dx]) : (print '. ');
(defined $array[$dy][$dx]) ? (print $array[$dy][$dx]) : (print '. ');
}
}
print "\n";
print "\n";
}
}
}</lang>
}</lang>


The above is a bit verbose, here is a simpler implementation:
The above is a bit verbose, here is a simpler implementation:
Line 450: Line 441:


=={{header|Pop11}}==
=={{header|Pop11}}==
<lang pop11> vars itemrep;
<lang pop11>vars itemrep;
incharitem(charin) -> itemrep;
incharitem(charin) -> itemrep;
;;; Read sizes
;;; Read sizes
vars n1 = itemrep(), n2= itemrep();
vars n1 = itemrep(), n2= itemrep();
;;; Create 0 based array
;;; Create 0 based array
vars ar = newarray([0 ^(n1 - 1) 0 ^(n2 - 1)], 0);
vars ar = newarray([0 ^(n1 - 1) 0 ^(n2 - 1)], 0);
;;; Set element value
;;; Set element value
15 -> ar(0, 0);
15 -> ar(0, 0);
;;; Print element value
;;; Print element value
ar(0,0) =>
ar(0,0) =>
;;; Make sure array is unreferenced
;;; Make sure array is unreferenced
0 -> ar;</lang>
0 -> ar;</lang>


Pop11 is garbage collected so there is no need to destroy array. However, the array is live as long as variable ar references it. The last assignment makes sure that we loose all our references to the array turning it into garbage.
Pop11 is garbage collected so there is no need to destroy array. However, the array is live as long as variable ar references it. The last assignment makes sure that we loose all our references to the array turning it into garbage.
Line 487: Line 478:
=={{header|R}}==
=={{header|R}}==
{{trans|C}}
{{trans|C}}
<lang r>input <- readline("Enter two integers. Space delimited, please: ")
<lang r>
input <- readline("Enter two integers. Space delimited, please: ")
dims <- as.numeric(strsplit(input, " ")[[1]])
dims <- as.numeric(strsplit(input, " ")[[1]])
arr <- array(dim=dims)
arr <- array(dim=dims)
Line 494: Line 484:
jj <- ceiling(dims[2]/2)
jj <- ceiling(dims[2]/2)
arr[ii, jj] <- sum(dims)
arr[ii, jj] <- sum(dims)
cat("array[", ii, ",", jj, "] is ", arr[ii, jj], "\n", sep="")
cat("array[", ii, ",", jj, "] is ", arr[ii, jj], "\n", sep="")</lang>
</lang>


=={{header|Ruby}}==
=={{header|Ruby}}==
<lang ruby> puts 'Enter width and height: '
<lang ruby>puts 'Enter width and height: '
w=gets.to_i
w=gets.to_i
arr = Array.new(gets.to_i){Array.new(w)}
arr = Array.new(gets.to_i){Array.new(w)}
arr[1][3] = 5
arr[1][3] = 5
p arr[1][3]</lang>
p arr[1][3]</lang>


=={{header|Smalltalk}}==
=={{header|Smalltalk}}==
Line 609: Line 598:
Toka has no direct support for 2D arrays, but they can be created and operated on in a manner similar to normal arrays using the following functions.
Toka has no direct support for 2D arrays, but they can be created and operated on in a manner similar to normal arrays using the following functions.


<lang toka> [ ( x y -- address )
<lang toka>[ ( x y -- address )
cells malloc >r
cells malloc >r
dup cells >r
dup cells >r
[ r> r> r> 2dup >r >r swap malloc swap i swap array.put >r ] iterate
[ r> r> r> 2dup >r >r swap malloc swap i swap array.put >r ] iterate
r> r> nip
r> r> nip
] is 2D-array
] is 2D-array

[ ( a b address -- value )
[ ( a b address -- value )
array.get array.get
array.get array.get
] is 2D-get-element
] is 2D-get-element

[ ( value a b address -- )
[ ( value a b address -- )
array.get array.put
array.get array.put
] is 2D-put-element</lang>
] is 2D-put-element</lang>


And a short test:
And a short test:
<lang toka> 5 5 2D-array >r #! Create an array and save the pointer to it
<lang toka>5 5 2D-array >r #! Create an array and save the pointer to it
10 2 3 r@ 2D-put-element #! Set element 2,3 to 10
10 2 3 r@ 2D-put-element #! Set element 2,3 to 10
2 3 r@ 2D-get-element #! Get the element at 2,3
2 3 r@ 2D-get-element #! Get the element at 2,3
r> drop #! Discard the pointer to the array</lang>
r> drop #! Discard the pointer to the array</lang>

Revision as of 15:52, 22 November 2009

Task
Create a two-dimensional array at runtime
You are encouraged to solve this task according to the task description, using any language you may know.

Data Structure
This illustrates a data structure, a means of storing data within a program.

You may see other such structures in the Data Structures category.

Get two integers from the user, then create a two-dimensional array where the two dimensions have the sizes given by those numbers, and which can be accessed in the most natural way possible. Write some element of that array, and then output that element. Finally destroy the array if not done by the language itself.

Ada

<lang ada>with Ada.Text_Io; use Ada.Text_Io; with Ada.Float_Text_Io; use Ada.Float_Text_Io; with Ada.Integer_Text_Io; use Ada.Integer_Text_Io;

procedure Two_Dimensional_Arrays is

  type Matrix_Type is array(Positive range <>, Positive range <>) of Float;
  Dim_1 : Positive;
  Dim_2 : Positive;

begin

  Get(Item => Dim_1);
  Get(Item => Dim_2);
  -- Create an inner block with the correctly sized array
  declare
     Matrix : Matrix_Type(1..Dim_1, 1..Dim_2);
  begin
     Matrix(1, Dim_2) := 3.14159;
     Put(Item => Matrix(1, Dim_2), Fore => 1, Aft => 5, Exp => 0);
     New_Line;
  end;
  -- The variable Matrix is popped off the stack automatically

end Two_Dimensional_Arrays;</lang>

ALGOL 68

<lang algol68>main:(

 print("Input two positive whole numbers separated by space and press newline:");
 [read int,read int] INT array;
 array[1,1]:=42;
 print (array[1,1])

)</lang>

AWK

AWK has no multidimensional array; but AWK arrays (which are Associative array indeed) can be used also in a multidimensional fashion. Since AWK arrays are associative arrays, there's no issue in their dimensions: they grow while adding new key-value pair.

<lang awk>/[0-9]+ [0-9]+/ {

 for(i=0; i < $1; i++) {
   for(j=0; j < $2; j++) {
     arr[i, j] = i*j
   }
 }
 # how to scan "multidim" array as explained in the GNU AWK manual
 for (comb in arr) {
   split(comb, idx, SUBSEP)
   print idx[1] "," idx[2] "->" arr[idx[1], idx[2]]
 }

}</lang>


BASIC

Works with: QuickBasic version 4.5
CLS
INPUT a, b 'inputs need to be separated by commas
DIM array (1 TO a, 1 TO b)
array(1,1) = 42
PRINT array(1,1)
ERASE array

C

<lang c>#include <stdio.h>

int main(int argc, char **argv) {

  int user1 = 0, user2 = 0;
  printf("Enter two integers.  Space delimited, please:  ");
  scanf("%d %d",&user1, &user2);
  int array[user1][user2];
  array[user1/2][user2/2] = user1 + user2;
  printf("array[%d][%d] is %d\n",user1/2,user2/2,array[user1/2][user2/2]);
  return 0;

}</lang>

C++

With language built-in facilities:

<lang cpp>#include <iostream>

  1. include <istream>
  2. include <ostream>

int main() {

 // read values
 int dim1, dim2;
 std::cin >> dim1 >> dim2;
 // create array
 double* array_data = new double[dim1*dim2];
 double** array = new double*[dim1];
 for (int i = 0; i < dim1; ++i)
   array[i] = array_data + dim2*i;
 // write element
 array[0][0] = 3.5;
 // output element
 std::cout << array[0][0] << std::endl;
 // get rid of array
 delete[] array;
 delete[] array_data;

}</lang>

Using std::vector from the standard library:

<lang cpp>#include <iostream>

  1. include <istream>
  2. include <ostream>
  3. include <vector>

int main() {

 // read values
 int dim1, dim2;
 std::cin >> dim1 >> dim2;
 // create array
 std::vector<std::vector<double> > array(dim1, std::vector<double>(dim2));
 // write element
 array[0][0] = 3.5;
 // output element
 std::cout << array[0][0] << std::endl;
 // the array is automatically freed at the end of main()

}</lang>

D

<lang d>import std.stdio: writef, writefln, readln; import std.conv: toInt; import std.string: strip;

void main() {

   writef("Give me the numer of rows: ");
   int nrow = toInt(readln().strip());
   writef("Give me the numer of columns: ");
   int ncol = toInt(readln().strip());
   auto array = new float[][](nrow, ncol);
   array[0][0] = 3.5;
   writefln("The number at place [0 0] is ", array[0][0]);

}</lang>

Clean

<lang clean>import StdEnv

Start :: *World -> { {Real} } Start world

   # (console, world) = stdio world
     (_, dim1, console) = freadi console
     (_, dim2, console) = freadi console
   = createArray dim1 (createArray dim2 1.0)</lang>

Common Lisp

<lang lisp>(let ((d1 (read))

     (d2 (read)))
 (assert (and (typep d1 '(integer 1)) 
              (typep d2 '(integer 1))) 
         (d1 d2))
 (let ((array (make-array (list d1 d2) :initial-element nil))
       (p1 0)
       (p2 (floor d2 2)))
   (setf (aref array p1 p2) t)
   (print (aref array p1 p2))))</lang>

The assert will allow the user to reenter the dimensions if they are not positive integers.

Forth

<lang forth>: cell-matrix

 create ( width height "name" ) over ,  * cells allot
 does> ( x y -- addr ) dup cell+ >r  @ * + cells r> + ;

5 5 cell-matrix test

36 0 0 test ! 0 0 test @ . \ 36</lang>

<lang forth>INTEGER DMATRIX my-matrix{{ & my-matrixTemplate:8 9malloc

8 my-matrixTemplate:3 4 ! my-matrixTemplate:3 4 @ .

& my-matrix{{ }}free</lang>

Fortran

In Fortran 90 and later <lang fortran>PROGRAM Example

 IMPLICIT NONE
 INTEGER :: rows, columns, errcheck
 INTEGER, ALLOCATABLE :: array(:,:)
 WRITE(*,*) "Enter number of rows"
 READ(*,*) rows
 WRITE(*,*) "Enter number of columns"
 READ(*,*) columns

 ALLOCATE (array(rows,columns), STAT=errcheck) ! STAT is optional and is used for error checking

 array(1,1) = 42

 WRITE(*,*) array(1,1)

 DEALLOCATE (array, STAT=errcheck)

END PROGRAM Example</lang>

Haskell

<lang haskell> doit n m = a!(0,0) where a = array ((0,0),(n,m)) [((0,0),42)]</lang>

IDL

The following is only for demonstration. No real program should just assume that the user input is valid, integer, large enough etc.

<lang idl>read, x, prompt='Enter x size:' read, y, prompt='Enter y size:' d = fltarr(x,y)

d[3,4] = 5.6 print,d[3,4]

==> outputs 5.6

delvar, d</lang>

J

In J, all aspects of arrays are resolved through evaluation. Everything counts as being given at run time. <lang j>task=: 3 : 0 'init new' =. 0;1 NB. values for initialization and alteration array =. y $ init NB. create array of shape y element =. < ? $ array NB. pick an atom of the array at random array =. new element } array NB. amend that element to new value element { array NB. return value of changed element )</lang> Passing two integers to task (as a list) satisfies the specifications for a two-dimensional array, but providing a longer list of integers accomplishes the same task on an array of as many dimensions as the count of integers given.

The type of the array is determined by the type of the values used in filling the array. E.g., alternate data types are obtained by substituting any of the following lines: <lang j>'init new' =. ' ';'x' NB. literals 'init new' =. 1r2;2r3 NB. fractions 'init new' =. a: ; <<'Rosetta' NB. boxes</lang>

Java

<lang java>import java.util.Scanner;

public class twoDimArray {

 public static void main(String[] args) {
       Scanner in = new Scanner(System.in);
       
       int nbr1 = in.nextInt();
       int nbr2 = in.nextInt();
       
       double[][] array = new double[nbr1][nbr2];
       array[0][0] = 42.0;
       System.out.println("The number at place [0 0] is " + array[0][0]);
 }

}</lang>

JavaScript

For the user input, requires JScript. The array processing is implementation agnostic. <lang javascript>var w = parseInt( get_input("Enter a width:") ); var w = parseInt( get_input("Enter a height:") );

// create the 2-D array var a = new Array(h); for (var i = 0; i < h; i++)

 a[i] = new Array(w);

a[0][0] = 'foo'; WScript.Echo('a[0][0] = ' + a[0][0]);

a = null;

function get_input(prompt) {

   output(prompt);
   try {
       return WScript.StdIn.readLine();
   } catch(e) {
       return readline();
   }

} function output(prompt) {

   try {
       return WScript.echo(prompt);
   } catch(e) {
       return print(prompt);
   }

}</lang>

Works with: UCB Logo

<lang logo>make "a2 mdarray [5 5] mdsetitem [1 1] :a2 0  ; by default, arrays are indexed starting at 1 print mditem [1 1] :a2  ; 0</lang>

MAXScript

<lang maxscript>a = getKBValue prompt:"Enter first dimension:" b = getKBValue prompt:"Enter second dimension:" arr1 = #() arr2 = #() arr2[b] = undefined for i in 1 to a do (

    append arr1 (deepCopy arr2)

) arr1[a][b] = 1 print arr1[a][b]</lang>

Objective-C

Being Objective-C derivated from C, the C solution works fine in Objective-C too.

The "OpenStep" frameworks (GNUstep, Cocoa) does not provide a class for multidimensional array; of course it can be implemented in several way (also as a wrapper for the plain C way of handling arrays). Here I show a straightforward use of the NSMutableArray class.

Works with: GNUstep
Works with: Cocoa

<lang objc>#import <Foundation/Foundation.h>

int main() {

 int num1, num2, i, j;
 NSMutableArray *arr;
 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
 scanf("%d %d", &num1, &num2);
 NSLog(@"%d %d", num1, num2);
 
 arr = [NSMutableArray arrayWithCapacity: (num1*num2)];
 // initialize it with 0s
 for(i=0; i < (num1*num2); i++) [arr addObject: [NSNumber numberWithInt: 0]];
 // replace 0s with something more interesting
 for(i=0; i < num1; i++) {
   for(j=0; j < num2; j++) {
     [arr replaceObjectAtIndex: (j*num1+i) withObject: [NSNumber numberWithInt: (i*j)]];
   }
 }
 // access a value: I*num1+J, where I,J are the indexes for the bidimensional array
 NSLog(@"%@", [arr objectAtIndex: (1*num1+3)]);
 [pool release];
 return 0;

}</lang>

OCaml

<lang ocaml>let nbr1 = read_int ();; let nbr2 = read_int ();; let array = Array.make_matrix nbr1 nbr2 0.0;; array.(0).(0) <- 3.5;; print_float array.(0).(0); print_newline ();;</lang>

Pascal

Works with: GNU Pascal version 20060325, based on gcc-3.4.4

The following code is standard Extended Pascal (tested with gpc --extended-pascal):

<lang pascal>program array2d(input, output);

type

tArray2d(dim1, dim2: integer) = array[1 .. dim1, 1 .. dim2] of real;
pArray2D = ^tArray2D;

var

d1, d2: integer;
data: pArray2D;

begin

{ read values }
readln(d1, d2);
{ create array }
new(data, d1, d2);
{ write element }
data^[1,1] := 3.5;
{ output element }
writeln(data^[1,1]);
{ get rid of array }
dispose(data);

end.</lang>


Perl

Works with: Perl version 5.x

Predefining an array (or multi-dimension array) size is unnecessary, Perl dynamically resizes the array to meet the requirements. Of course I'm assuming that the user is entering array size 0 based.

<lang perl>sub make_array($ $){

 # get array sizes from provided params, but force numeric value
 my $x = ($_[0] =~ /^\d+$/) ? shift : 0;
 my $y = ($_[0] =~ /^\d+$/) ? shift : 0;
 
 # define array, then add multi-dimensional elements
 my @array;
 $array[0][0] = 'X '; # first by first element
 $array[5][7] = 'X ' if (5 <= $y and 7 <= $x); # sixth by eighth element, if the max size is big enough
 $array[12][15] = 'X ' if (12 <= $y and 15 <= $x); # thirteenth by sixteenth element, if the max size is big enough
 
 # loop through the elements expected to exist base on input, and display the elements contents in a grid
 foreach my $dy (0 .. $y){
   foreach my $dx (0 .. $x){
     (defined $array[$dy][$dx]) ? (print $array[$dy][$dx]) : (print '. ');
   }
   print "\n";
 }

}</lang>

The above is a bit verbose, here is a simpler implementation:

<lang perl>sub array {

   my ($x, $y) = @_;
   map {[ (0) x $x ]} 1 .. $y

}

my @square = array 3, 3;

  1. everything above this line is mostly redundant in perl,
  2. since perl would have created the array automatically when used.
  3. however, the above function initializes the array elements to 0,
  4. while perl would have used undef
  5. $cube[3][4][5] = 60 # this is valid even if @cube was previously undefined

$square[1][1] = 1; print "@$_\n" for @square; > 0 0 0 > 0 1 0 > 0 0 0</lang>

Pop11

<lang pop11>vars itemrep; incharitem(charin) -> itemrep;

Read sizes

vars n1 = itemrep(), n2= itemrep();

Create 0 based array

vars ar = newarray([0 ^(n1 - 1) 0 ^(n2 - 1)], 0);

Set element value

15 -> ar(0, 0);

Print element value

ar(0,0) =>

Make sure array is unreferenced

0 -> ar;</lang>

Pop11 is garbage collected so there is no need to destroy array. However, the array is live as long as variable ar references it. The last assignment makes sure that we loose all our references to the array turning it into garbage.

Pop11 arrays may have arbitrary lower bounds, since we are given only size we create 0 based array.

Python

Works with: Python version 2.5

<lang python>width = int(raw_input("Width of myarray: ")) height = int(raw_input("Height of Array: ")) myarray = [[0] * width for i in xrange(height)] myarray[0][0] = 3.5 print myarray[0][0]</lang>

Note: Some people may instinctively try to write myarray as [[0] * width] * height, but the * operator creates n references to [[0] * width]

You can also use a two element tuple to index a dictionary like so:

<lang python>myarray = dict(((w,h), 0) for w in range(width) for h in range(height))

  1. or, in Python 3: myarray = {(w,h): 0 for w in range(width) for h in range(height)}

myarray[(0,0)] = 3.5 print myarray[(0,0)]</lang>

R

Translation of: C

<lang r>input <- readline("Enter two integers. Space delimited, please: ") dims <- as.numeric(strsplit(input, " ")1) arr <- array(dim=dims) ii <- ceiling(dims[1]/2) jj <- ceiling(dims[2]/2) arr[ii, jj] <- sum(dims) cat("array[", ii, ",", jj, "] is ", arr[ii, jj], "\n", sep="")</lang>

Ruby

<lang ruby>puts 'Enter width and height: ' w=gets.to_i arr = Array.new(gets.to_i){Array.new(w)} arr[1][3] = 5 p arr[1][3]</lang>

Smalltalk

Works with: GNU Smalltalk

Smalltalk has no problems in creating objects at runtime. I haven't found a class for multidimensional array in the standard library, so let us suppose to have a class named MultidimensionalArray.

<lang smalltalk>|num1 num2 arr| num1 := stdin nextLine asInteger. num2 := stdin nextLine asInteger.

arr := MultidimensionalArray new: { num1. num2 }.

1 to: num1 do: [ :i |

 1 to: num2 do: [ :j |
   arr at: { i. j } put: (i*j)
 ]

].

1 to: num1 do: [ :i |

 1 to: num2 do: [ :j |
   (arr at: {i. j}) displayNl
 ]

].</lang>

A possible implementation for a BidimensionalArray class is the following (changing Multi into Bi and using this class, the previous code runs fine):

<lang smalltalk>Object subclass: BidimensionalArray [

 |biArr|
 <comment: 'bidim array'>

]. BidimensionalArray class extend [

 new: biDim [ |r|
   r := super new.
   r init: biDim.
   ^ r
 ]

]. BidimensionalArray extend [

 init: biDim [
    biArr := Array new: (biDim at: 1).
    1 to: (biDim at: 1) do: [ :i |
      biArr at: i put: (Array new: (biDim at: 2))
    ].
    ^ self
 ]
 at: biDim [
    ^ (biArr at: (biDim at: 1)) at: (biDim at: 2)
 ]
 at: biDim put: val [
    ^ (biArr at: (biDim at: 1)) at: (biDim at: 2) put: val
 ]

].</lang>

Instead of implementing such a class (or the MultidimensionalArray one), we can use a LookupTable class, using Array objects as keys (each element of the array will be an index for a specific dimension of the "array"). The final effect is the same as using an array (almost in the AWK sense) and the approach has some advantages.

<lang smalltalk>|num1 num2 pseudoArr| num1 := stdin nextLine asInteger. num2 := stdin nextLine asInteger.

"we can 'suggest' an initial value for the number

of slot the table can hold; anyway, if we use
more than these, the table automatically grows"

pseudoArr := LookupTable new: (num1 * num2).

1 to: num1 do: [ :i |

 1 to: num2 do: [ :j |
    pseudoArr at: {i. j} put: (i * j).
 ]

].

1 to: num1 do: [ :i |

 1 to: num2 do: [ :j |
    (pseudoArr at: {i. j}) displayNl.
 ]

].</lang>

Standard ML

<lang sml>val nbr1 = valOf (TextIO.scanStream (Int.scan StringCvt.DEC) TextIO.stdIn); val nbr2 = valOf (TextIO.scanStream (Int.scan StringCvt.DEC) TextIO.stdIn); val array = Array2.array (nbr1, nbr2, 0.0); Array2.update (array, 0, 0, 3.5); print (Real.toString (Array2.sub (array, 0, 0)) ^ "\n");</lang>

Tcl

Works with: Tcl version 8.5

<lang tcl>package require Tcl 8.5

puts "enter X dimension:" set dim2 [gets stdin] puts "enter Y dimension:" set dim1 [gets stdin]

  1. Make the "array"; we'll keep it in row-major form

set l [lrepeat $dim1 [lrepeat $dim2 {}]]

  1. Select a point at around the middle of the "array"

set y [expr {$dim1>>1}] set x [expr {$dim2>>1}]

  1. Set the value at that point

lset l $y $x aValue

  1. Read the value at that point

puts [lindex $l $y $x]

  1. Delete the "array"

unset l</lang>

Toka

Toka has no direct support for 2D arrays, but they can be created and operated on in a manner similar to normal arrays using the following functions.

<lang toka>[ ( x y -- address )

 cells malloc >r
 dup cells >r
 [ r> r> r> 2dup >r >r swap malloc swap i swap array.put >r ] iterate

r> r> nip ] is 2D-array

[ ( a b address -- value )

 array.get array.get

] is 2D-get-element

[ ( value a b address -- )

 array.get array.put

] is 2D-put-element</lang>

And a short test:

<lang toka>5 5 2D-array >r #! Create an array and save the pointer to it 10 2 3 r@ 2D-put-element #! Set element 2,3 to 10 2 3 r@ 2D-get-element #! Get the element at 2,3 r> drop #! Discard the pointer to the array</lang>