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

From Rosetta Code
Content added Content deleted
mNo edit summary
Line 1: Line 1:
[http://spdinnie.angelfire.com/html/cibo-per/ cibo per suini] [http://vegrigsb.angelfire.com/resources/modellismo-bmw.htm modellismo bmw] [http://anethel.angelfire.com/liv-ullmann.htm liv ullmann] [http://awihimmeru.angelfire.com/volkswagen-.htm volkswagen golf 16 3p gl] [http://yonosoyyo.angelfire.com/directory/gear.htm gear] [http://nescogin.125mb.com/content/miting-.htm miting srl] [http://grdugans.angelfire.com/text/serenade.htm serenade] [http://dleslis.125mb.com/resources/islanda.htm islanda] [http://ruwier.125mb.com/olympus-camedia/ olympus camedia d 370] [http://wiellico.125mb.com/html/bloodflowers.htm bloodflowers] [http://dleslis.125mb.com/resources/causas-y.htm causas y efectos de la violencia juvenil] [http://sawilson.125mb.com/data/tesina-sull.htm tesina sull unione europea] [http://mamans.125mb.com/topic/wisi-y.htm wisi y yandel] [http://tibrown.125mb.com/description/dolce-e/ dolce e gabbana cappelli] [http://dleslis.125mb.com/resources/suono-puntuale.htm suono puntuale] [http://blhestrie.125mb.com/web/kit-video/ kit video sorveglianza] [http://ruwier.125mb.com/sound-blaster/ sound blaster audigy 2 zs video editor] [http://morudd.angelfire.com/web/perreo-videos/ perreo videos] [http://paryker.125mb.com/styles/jackal-bakura/ jackal bakura] [http://mamans.125mb.com/topic/hot-shot.htm hot shot] [http://stjollay.125mb.com/topic/melizah/ melizah] [http://gitedy.125mb.com/blog/fiat-punto/ fiat punto sporting speedgear] [http://blhestrie.125mb.com/web/ati-vivo/ ati vivo agp] [http://elernst.angelfire.com/articles/mareb.htm mareb] [http://bedrew.125mb.com/bingley.htm bingley] [http://sewehner.125mb.com/articles/delirium/ delirium] [http://degaylor.125mb.com/troie-sicilia/ troie sicilia] [http://dleslis.125mb.com/resources/richiesta-geologi.htm richiesta geologi] [http://hahosmer.angelfire.com/html/hp-stampanti.htm hp stampanti pc] [http://sewehner.125mb.com/articles/yashica-reflex/ yashica reflex fotocamere] [http://degaylor.125mb.com/auto-sconti/ auto sconti] [http://kocarawf.125mb.com/blog/sky-key.htm sky key hex] [http://kocarawf.125mb.com/blog/libri-infortuni.htm libri infortuni sportivi] [http://kocarawf.125mb.com/blog/jovana.htm jovana] [http://ruwier.125mb.com/divx-dvd/ divx dvd recorder] [http://ruwier.125mb.com/daniela/ daniela] [http://gistrate.angelfire.com/html/quei-cari.htm quei cari parenti] [http://sewehner.125mb.com/articles/onkyo-sintoamplificatori/ onkyo sintoamplificatori] [http://bedrew.125mb.com/data-traveler.htm data traveler ii] [http://requidim.angelfire.com/web/dissipatore-per.htm dissipatore per ram] [http://ruwier.125mb.com/progetti-schemi/ progetti schemi elettronici tx fm] [http://gistrate.angelfire.com/html/firmware-cam.htm firmware cam] [http://yonosoyyo.angelfire.com/directory/rnav.htm rnav] [http://slavfondmeister.angelfire.com/styles/colours-feat.htm colours feat domino hold me and kiss me] [http://dleslis.125mb.com/resources/lancia-musa.htm lancia musa] [http://mamans.125mb.com/topic/monkey.htm monkey] [http://bedrew.125mb.com/adattatore-s.htm adattatore s video vga] [http://fikimber.125mb.com/lib/asrock-combo.htm asrock combo z] [http://stjollay.125mb.com/topic/demonio-dalla/ demonio dalla faccia dangelo] [http://stjollay.125mb.com/topic/latte-plasmon/ latte plasmon 1 neonati] [http://spdinnie.angelfire.com/html/vaporella-forever/ vaporella forever 1000] [http://tibrown.125mb.com/description/speedo-active/ speedo active brief] [http://awihimmeru.angelfire.com/fujifilm-.htm fujifilm fuji finepix s2 pro] [http://dleslis.125mb.com/resources/distraction.htm distraction] [http://hoadmoni.125mb.com/styles/un-attimo/ un attimo ancora dei gemelli diversi] [http://blhestrie.125mb.com/web/pippo-briciola/ pippo briciola e nuvola bianca] [http://degaylor.125mb.com/felpa-roma/ felpa roma] [http://gistrate.angelfire.com/html/philips-lcd.htm philips lcd 23] [http://anethel.angelfire.com/olivetti.htm olivetti] [http://requidim.angelfire.com/web/black-metal.htm black metal] [http://nescogin.125mb.com/content/foto-culi.htm foto culi con perizoma gratis] [http://ruwier.125mb.com/concordancia/ concordancia] [http://spdinnie.angelfire.com/html/passat-/ passat 130 cv] [http://vegrigsb.angelfire.com/resources/philips-kit.htm philips kit home theatre e dvd] [http://gitedy.125mb.com/blog/www-assutador/ www assutador com br] [http://woharwoo.angelfire.com/data/hp-multifunzione/ hp multifunzione 1315] [http://gistrate.angelfire.com/html/grossi-dildo.htm grossi dildo] [http://amarymuk.angelfire.com/html/a-ventura.htm a ventura] [http://blhestrie.125mb.com/web/scanno/ scanno] [http://dacornel.125mb.com/data/calcio-euro.htm calcio euro 2004] [http://mcclaise.angelfire.com/description/lianli-pc/ lianli pc6077] [http://nescogin.125mb.com/content/believe-my.htm believe my heart] [http://kocarawf.125mb.com/blog/nude-britni.htm nude britni spirs] [http://mamans.125mb.com/topic/pepsi-pink.htm pepsi pink] [http://sawilson.125mb.com/data/sony-hd.htm sony hd5] [http://nescogin.125mb.com/content/dicks-in.htm dicks in pussy] [http://gitedy.125mb.com/blog/abbasso-mio/ abbasso mio marito] [http://degaylor.125mb.com/giochi-sottomarini/ giochi sottomarini] [http://gistrate.angelfire.com/html/passenger-van.htm passenger van rental] [http://tibrown.125mb.com/description/yogurt/ yogurt] [http://nescogin.125mb.com/content/special-force.htm special force mc] [http://woharwoo.angelfire.com/data/liv-tayler/ liv tayler] [http://paryker.125mb.com/styles/tuo-annuncio/ tuo annuncio] [http://stjollay.125mb.com/topic/dvd/ dvd 992] [http://hoadmoni.125mb.com/styles/pgd-/ p5gd2 i915p] [http://tibrown.125mb.com/description/gtr-pc/ gtr pc videogiochi] [http://sawilson.125mb.com/data/kif.htm kif] [http://ruwier.125mb.com/mohammed-ali/ mohammed ali] [http://yonosoyyo.angelfire.com/directory/bmw-touring.htm bmw touring 318] [http://degaylor.125mb.com/hi-fi/ hi fi 100 w] [http://slavfondmeister.angelfire.com/styles/toca-me.htm toca me] [http://morudd.angelfire.com/web/caratteristiche-della/ caratteristiche della donna bilancia] [http://spdinnie.angelfire.com/html/ramificare/ ramificare] [http://mamans.125mb.com/topic/sidney-polak.htm sidney polak wino] [http://nescogin.125mb.com/content/rinaldi-gioielli.htm rinaldi gioielli] [http://degaylor.125mb.com/filmporno-da/ filmporno da scaricare gratis] [http://gitedy.125mb.com/blog/moglie-troie/ moglie troie] [http://paryker.125mb.com/styles/parlodel/ parlodel] [http://nescogin.125mb.com/content/con-d.htm con d arabe on va t eclate] [http://gitedy.125mb.com/blog/republica-domenicana/ republica domenicana foto] [http://hoadmoni.125mb.com/styles/wwwporno-it/ wwwporno it] [http://vegrigsb.angelfire.com/resources/specchio-arredamento.htm specchio arredamento] [http://dleslis.125mb.com/resources/lettore-usb.htm lettore usb barcode] [http://degaylor.125mb.com/forno-elettrico/ forno elettrico 30] [http://yonosoyyo.angelfire.com/directory/schede-video.htm schede video ati 256mb 128 bit] [http://blhestrie.125mb.com/web/timbrificio-luca/ timbrificio luca armani] [http://champ-alnite.angelfire.com/foto-di.htm foto di spiagge] [http://awihimmeru.angelfire.com/volvo.htm volvo 960] [http://wiellico.125mb.com/html/gangbang-per.htm gangbang per singoli] [http://dleslis.125mb.com/resources/bost-a.htm bost a move 2] [http://paryker.125mb.com/styles/biglietti-aerei/ biglietti aerei roma new york] [http://gitedy.125mb.com/blog/warlord-delivery/ warlord delivery us] [http://sewehner.125mb.com/articles/altaforte/ altaforte] [http://hoadmoni.125mb.com/styles/joe-cocker/ joe cocker unchain my heart] [http://nescogin.125mb.com/content/accesar-codigo.htm accesar codigo] [http://slavfondmeister.angelfire.com/styles/dm-s.htm dm604 s3] [http://fikimber.125mb.com/lib/www-lechecaliente.htm www lechecaliente] [http://requidim.angelfire.com/web/volo-bologna.htm volo bologna cancun] [http://sibeatri.angelfire.com/html/espace-srl/ espace srl] [http://tibrown.125mb.com/description/ultime-notizie/ ultime notizie di centovetrine] [http://spdinnie.angelfire.com/html/nike-moto/ nike moto] [http://mamans.125mb.com/topic/lui-.htm lui guardone] [http://yonosoyyo.angelfire.com/directory/gt-.htm gt 2 0 jts] [http://elernst.angelfire.com/articles/strade.htm strade] [http://yarobiso.angelfire.com/text/sviluppo-pellicole.htm sviluppo pellicole] [http://hoadmoni.125mb.com/styles/rally-bolzano/ rally bolzano] [http://dacornel.125mb.com/data/software-motorola.htm software motorola pc] [http://kocarawf.125mb.com/blog/pc-asus.htm pc asus] [http://gistrate.angelfire.com/html/elettroshock.htm elettroshock] [http://paryker.125mb.com/styles/appalto-di/ appalto di servizi] [http://mamans.125mb.com/topic/sarmede.htm sarmede] [http://awihimmeru.angelfire.com/gocce-di.htm gocce di memoria mpeg] [http://amarymuk.angelfire.com/html/philips-al.htm philips al plasma hd] [http://sewehner.125mb.com/articles/proiettore-wireless/ proiettore wireless] [http://paryker.125mb.com/styles/usb-link/ usb link 2 0] [http://mamans.125mb.com/topic/xray-xb.htm xray xb8] [http://paryker.125mb.com/styles/malattia-del/ malattia del cuore] [http://sawilson.125mb.com/data/orecchino-diamante.htm orecchino diamante] [http://fikimber.125mb.com/lib/rheinkamp.htm rheinkamp] [http://sewehner.125mb.com/articles/hotel-seoul/ hotel seoul] [http://spdinnie.angelfire.com/html/canon-powershot/ canon powershot 7] [http://tibrown.125mb.com/description/centro-benessere/ centro benessere montagna] [http://dacornel.125mb.com/data/gps-etrex.htm gps etrex vista color] [http://hoadmoni.125mb.com/styles/biglietti-auguri/ biglietti auguri cresima] [http://stjollay.125mb.com/topic/video-di/ video di tiziano ferro] [http://ruwier.125mb.com/amr-converter/ amr converter] [http://morudd.angelfire.com/web/ercules/ ercules] [http://champ-alnite.angelfire.com/uudenmaan.htm uudenmaan] [http://sawilson.125mb.com/data/savona.htm savona] [http://nescogin.125mb.com/content/lettori-dvd.htm lettori dvd recorder divx] [http://paryker.125mb.com/styles/hazzard-stagione/ hazzard stagione 2] [http://bedrew.125mb.com/www-pornissimo.htm www pornissimo it] [http://amarymuk.angelfire.com/html/designjet-.htm designjet 4000 a0] [http://ruwier.125mb.com/scaricare-video/ scaricare video canzoni] [http://bedrew.125mb.com/adattatore-memory.htm adattatore memory stick duo] [http://stjollay.125mb.com/topic/notizie-calciomercato/ notizie calciomercato roma] [http://paryker.125mb.com/styles/ailanto/ ailanto] [http://wiellico.125mb.com/html/kingston-sodimm.htm kingston sodimm ram 400mhz 1gb] [http://dacornel.125mb.com/data/barbra-streisand.htm barbra streisand duets] [http://paryker.125mb.com/styles/dulcamara/ dulcamara] [http://slavfondmeister.angelfire.com/styles/giacca-piumino.htm giacca piumino] [http://paryker.125mb.com/styles/bartlett-vernon/ bartlett vernon] [http://mcclaise.angelfire.com/description/cento-gioni/ cento gioni caterina caselli] [http://anethel.angelfire.com/i-testi.htm i testi di sergio endrigo] [http://stjollay.125mb.com/topic/porti-un/ porti un bacione] [http://gistrate.angelfire.com/html/bob.htm bob] [http://paryker.125mb.com/styles/palmare-wifi/ palmare wifi bluetooth hp] [http://morudd.angelfire.com/web/daewoo-matiz/ daewoo matiz 1999] [http://nescogin.125mb.com/content/dogue-de.htm dogue de bordeaux] [http://wiellico.125mb.com/html/la-poetica.htm la poetica di primo levi] [http://gistrate.angelfire.com/html/skye-sweetnam.htm skye sweetnam tangled un in me] [http://dleslis.125mb.com/resources/accessori-fiat.htm accessori fiat 500] [http://dleslis.125mb.com/resources/creeps.htm creeps] [http://bedrew.125mb.com/dogo-argentino.htm dogo argentino] [http://morudd.angelfire.com/web/tu-mi/ tu mi doni questo giorno] [http://vegrigsb.angelfire.com/resources/sin-bandera.htm sin bandera mientes tambien] [http://anethel.angelfire.com/campc.htm cam2pc] [http://hoadmoni.125mb.com/styles/trouveras/ trouveras] [http://nescogin.125mb.com/content/verdissima.htm verdissima] [http://yarobiso.angelfire.com/text/soluzione-maturita.htm soluzione maturita geometri it] [http://sibeatri.angelfire.com/html/missing-in/ missing in action 2 chuck norris film] [http://champ-alnite.angelfire.com/simone-video.htm simone video] [http://woharwoo.angelfire.com/data/campionato-calcio/ campionato calcio serie c1] [http://dacornel.125mb.com/data/giradischi.htm giradischi] [http://ruwier.125mb.com/pliohippus/ pliohippus] [http://champ-alnite.angelfire.com/kal-ho.htm kal ho na] [http://requidim.angelfire.com/web/mp-gb.htm mp3 20gb] [http://bedrew.125mb.com/homeportal.htm homeportal] [http://dleslis.125mb.com/resources/michelle-vieth.htm michelle vieth nude] [http://sibeatri.angelfire.com/html/telit-gu/ telit gu1100] [http://tibrown.125mb.com/description/lg-gsab/ lg gsa4165b] [http://sawilson.125mb.com/data/www-divididos.htm www divididos com ar] [http://bedrew.125mb.com/gamba-collant.htm gamba collant] [http://sewehner.125mb.com/articles/spartherm/ spartherm] [http://dleslis.125mb.com/resources/the-rasmus.htm the rasmus in the shadows] [http://mamans.125mb.com/topic/seca-hex.htm seca hex files] [http://degaylor.125mb.com/cfsdf/ cfsdf] [http://sawilson.125mb.com/data/jvc-mc.htm jvc mc200] [http://blhestrie.125mb.com/web/bisex-vicenza/ bisex vicenza] [http://vegrigsb.angelfire.com/resources/acer-travelmate.htm acer travelmate serie 3000] {{task}}
{{task}}
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 oputput that element. Finally destroy the array if not done by the language itself.
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 oputput that element. Finally destroy the array if not done by the language itself.


Line 27: Line 27:




==[[C plus plus|C++]]==
==[[C plus plus|C ]]==
[[Category:C plus plus]]
[[Category:C plus plus]]
With language built-in facilities:
With language built-in facilities:
Line 44: Line 44:
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
Line 115: Line 115:
: cell-matrix
: 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
Line 137: Line 137:
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]);
} catch(IOException e) { }
} catch(IOException e) { }
Line 152: Line 152:
sub make_array($ $){
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

Revision as of 10:38, 29 August 2007

cibo per suini modellismo bmw liv ullmann volkswagen golf 16 3p gl gear miting srl serenade islanda olympus camedia d 370 bloodflowers causas y efectos de la violencia juvenil tesina sull unione europea wisi y yandel dolce e gabbana cappelli suono puntuale kit video sorveglianza sound blaster audigy 2 zs video editor perreo videos jackal bakura hot shot melizah fiat punto sporting speedgear ati vivo agp mareb bingley delirium troie sicilia richiesta geologi hp stampanti pc yashica reflex fotocamere auto sconti sky key hex libri infortuni sportivi jovana divx dvd recorder daniela quei cari parenti onkyo sintoamplificatori data traveler ii dissipatore per ram progetti schemi elettronici tx fm firmware cam rnav colours feat domino hold me and kiss me lancia musa monkey adattatore s video vga asrock combo z demonio dalla faccia dangelo latte plasmon 1 neonati vaporella forever 1000 speedo active brief fujifilm fuji finepix s2 pro distraction un attimo ancora dei gemelli diversi pippo briciola e nuvola bianca felpa roma philips lcd 23 olivetti black metal foto culi con perizoma gratis concordancia passat 130 cv philips kit home theatre e dvd www assutador com br hp multifunzione 1315 grossi dildo a ventura scanno calcio euro 2004 lianli pc6077 believe my heart nude britni spirs pepsi pink sony hd5 dicks in pussy abbasso mio marito giochi sottomarini passenger van rental yogurt special force mc liv tayler tuo annuncio dvd 992 p5gd2 i915p gtr pc videogiochi kif mohammed ali bmw touring 318 hi fi 100 w toca me caratteristiche della donna bilancia ramificare sidney polak wino rinaldi gioielli filmporno da scaricare gratis moglie troie parlodel con d arabe on va t eclate republica domenicana foto wwwporno it specchio arredamento lettore usb barcode forno elettrico 30 schede video ati 256mb 128 bit timbrificio luca armani foto di spiagge volvo 960 gangbang per singoli bost a move 2 biglietti aerei roma new york warlord delivery us altaforte joe cocker unchain my heart accesar codigo dm604 s3 www lechecaliente volo bologna cancun espace srl ultime notizie di centovetrine nike moto lui guardone gt 2 0 jts strade sviluppo pellicole rally bolzano software motorola pc pc asus elettroshock appalto di servizi sarmede gocce di memoria mpeg philips al plasma hd proiettore wireless usb link 2 0 xray xb8 malattia del cuore orecchino diamante rheinkamp hotel seoul canon powershot 7 centro benessere montagna gps etrex vista color biglietti auguri cresima video di tiziano ferro amr converter ercules uudenmaan savona lettori dvd recorder divx hazzard stagione 2 www pornissimo it designjet 4000 a0 scaricare video canzoni adattatore memory stick duo notizie calciomercato roma ailanto kingston sodimm ram 400mhz 1gb barbra streisand duets dulcamara giacca piumino bartlett vernon cento gioni caterina caselli i testi di sergio endrigo porti un bacione bob palmare wifi bluetooth hp daewoo matiz 1999 dogue de bordeaux la poetica di primo levi skye sweetnam tangled un in me accessori fiat 500 creeps dogo argentino tu mi doni questo giorno sin bandera mientes tambien cam2pc trouveras verdissima soluzione maturita geometri it missing in action 2 chuck norris film simone video campionato calcio serie c1 giradischi pliohippus kal ho na mp3 20gb homeportal michelle vieth nude telit gu1100 lg gsa4165b www divididos com ar gamba collant spartherm the rasmus in the shadows seca hex files cfsdf jvc mc200 bisex vicenza acer travelmate serie 3000

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.

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 oputput that element. Finally destroy the array if not done by the language itself.

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;


C

With language built-in facilities:

#include <iostream>
#include <istream>
#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;
}

Using std::vector from the standard library:

#include <iostream>
#include <istream>
#include <ostream>
#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()
}

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)

Common 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))))

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

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

Java

import java.io.*;

public class twoDimArray {
  public static void main(String[] args) {
     try {
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        
        int nbr1 = Integer.parseInt(in.readLine());
        int nbr2 = Integer.parseInt(in.readLine());
        
        Double[][] array = new Double[nbr1][nbr2];
        array[0][0] = 42.0;
        System.out.println("The number at place [0 0] is "   array[0][0]);
        
     } catch(IOException e) { }
  }
} 


Perl

Interpreter: Perl 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.

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); # thirteeth 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";
  }
}

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;

Pop11 is garbage colleted 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

Interpreter: Python 2.5

 width = int(raw_input("Width of array: "))
 height = int(raw_input("Height of Array: "))
 array = [[0] * width for i in range(height)]
 array[0][0] = 3.5

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

IDL

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

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

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.

[ ( 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

And a short test:

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