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://sister-sunshine.110mb.com/html/enermax-csta/ enermax cs656ta] [http://trene-von-anty.110mb.com/description/www-lago.htm www lago com de] [http://slavkamolot.110mb.com/library/mondowrestling/ mondowrestling] [http://lazythoughts.110mb.com/lib/nokia-auricolare/ nokia auricolare] [http://trouble166.110mb.com/mammifero.htm mammifero] [http://mouse-zae.110mb.com/knocking-on.htm knocking on haven s door] [http://gekijuls.110mb.com/creazioni-regia/ creazioni regia oro srl] [http://blue-olusha.110mb.com/library/www-move/ www move drive com] [http://slavkamolot.110mb.com/library/libri-magia/ libri magia] [http://unremig.110mb.com/h-b/ h b drx430] [http://blue-olusha.110mb.com/library/atmasphere-music/ atmasphere music] [http://unremig.110mb.com/beer-thomas/ beer thomas] [http://trouble166.110mb.com/canzoni-it.htm canzoni it] [http://olikka.110mb.com/library/sarah-ferguson.htm sarah ferguson nuda] [http://nationavce.110mb.com/view/kj.htm kj] [http://yeeden.110mb.com/data/sito-ufficiale/ sito ufficiale valentino rossi] [http://olikka.110mb.com/library/moneta-romana.htm moneta romana] [http://dialed.110mb.com/small/emmental/ emmental] [http://book-wench.110mb.com/text/high/ high] [http://mouse-zae.110mb.com/generation-of.htm generation of chaos 4 sul web] [http://blue-olusha.110mb.com/library/sexualidad/ sexualidad] [http://lazythoughts.110mb.com/lib/clavame-tu/ clavame tu amor de kinky] [http://unremig.110mb.com/tdk-dvd/ tdk dvd videobox] [http://ultra-creator.110mb.com/articles/olimpus.htm olimpus 370] [http://blue-olusha.110mb.com/library/offerta-speciali/ offerta speciali hotel venezia] [http://yeeden.110mb.com/data/hotel-de/ hotel de palma palermo] [http://trouble166.110mb.com/dogs-and.htm dogs and lights] [http://dialed.110mb.com/small/color-experanza/ color experanza] [http://slavkamolot.110mb.com/library/gelsenkirchen/ gelsenkirchen] [http://gekijuls.110mb.com/www-alpine/ www alpine com] [http://sister-sunshine.110mb.com/html/base-musicali/ base musicali] [http://forever-your.110mb.com/data/king-diamond.htm king diamond] [http://forever-your.110mb.com/data/merida-hotel.htm merida hotel] [http://nationavce.110mb.com/view/accecare.htm accecare] [http://sister-sunshine.110mb.com/html/juegos-de/ juegos de pokemon de gameboy color] [http://unremig.110mb.com/petsamo/ petsamo] [http://stitchesnglue.110mb.com/mouse-logitech.htm mouse logitech ultrax optical] [http://sneezingpops.110mb.com/soundtrack/ soundtrack] [http://ultra-creator.110mb.com/articles/deskjet.htm deskjet 520] [http://sneezingpops.110mb.com/shape-shifters/ shape shifters lolas theme] [http://trouble166.110mb.com/ford-focus.htm ford focus 100 cv] [http://mouse-zae.110mb.com/total-ir.htm total ir remote] [http://nationavce.110mb.com/view/funerale-frasi.htm funerale frasi] [http://yeeden.110mb.com/data/entombed-monkey/ entombed monkey puss live in london] [http://gekijuls.110mb.com/cypress-hill/ cypress hill still smokin] [http://gekijuls.110mb.com/t-come/ t come tango] [http://book-wench.110mb.com/text/open-gate/ open gate] [http://blue-olusha.110mb.com/library/klimt/ klimt 1918] [http://sneezingpops.110mb.com/mp-maroon/ mp3 maroon 5] [http://slavkamolot.110mb.com/library/i-frenetici/ i frenetici] [http://olikka.110mb.com/library/over-cinquanta.htm over cinquanta] [http://stitchesnglue.110mb.com/corinne-clery.htm corinne clery] [http://forever-your.110mb.com/data/box-esterno.htm box esterno hard disk] [http://yeeden.110mb.com/data/frona/ frona] [http://funk-mastah-ion.110mb.com/data/riassunto-elsa.htm riassunto elsa morante] [http://lazythoughts.110mb.com/lib/generali-assicurazione/ generali assicurazione] [http://gekijuls.110mb.com/capcom-vs/ capcom vs snk millennium fight 2000] [http://stitchesnglue.110mb.com/reggiseno-molto.htm reggiseno molto imbottito] [http://funk-mastah-ion.110mb.com/data/luna-de.htm luna de miel] [http://trene-von-anty.110mb.com/description/hp-.htm hp 2100 c4096a] [http://sneezingpops.110mb.com/vip-scandal/ vip scandal] [http://trouble166.110mb.com/de-angelis.htm de angelis midi] [http://yeeden.110mb.com/data/gyllene-tider/ gyllene tider] [http://olikka.110mb.com/library/locali-noturni.htm locali noturni] [http://mouse-zae.110mb.com/immagini-e.htm immagini e clip art gratuite] [http://unremig.110mb.com/olimpus-p/ olimpus p10] [http://forever-your.110mb.com/data/cerca-azienda.htm cerca azienda] [http://olikka.110mb.com/library/ricetta-insalata.htm ricetta insalata di riso] [http://gekijuls.110mb.com/hotel-budapest/ hotel budapest] [http://funk-mastah-ion.110mb.com/data/bachay.htm bachay] [http://slavkamolot.110mb.com/library/occasione-moto/ occasione moto] [http://dialed.110mb.com/small/ninnananna/ ninnananna] [http://slavkamolot.110mb.com/library/bfbs-key/ bfbs key] [http://ultra-creator.110mb.com/articles/bubble-games.htm bubble games] [http://book-wench.110mb.com/text/elaborazioni-estetiche/ elaborazioni estetiche] [http://funk-mastah-ion.110mb.com/data/u-cover.htm u2 cover night and day i think of you] [http://ultra-creator.110mb.com/articles/nba.htm nba 2004] [http://trouble166.110mb.com/depeche-mode.htm depeche mode personal jesus] [http://funk-mastah-ion.110mb.com/data/dlink-wifi.htm dlink wifi] [http://some-omeelse.110mb.com/data/xbox-memoria.htm xbox memoria accessori console] [http://blue-olusha.110mb.com/library/sigma/ sigma 24 70] [http://gekijuls.110mb.com/nikc/ nikc] [http://ultra-creator.110mb.com/articles/paddy-kelly.htm paddy kelly] [http://dialed.110mb.com/small/arrog/ arrog] [http://some-omeelse.110mb.com/data/motorola-ch.htm motorola ch] [http://unremig.110mb.com/samsung-/ samsung 32 pollici] [http://blue-olusha.110mb.com/library/in-to/ in to my arms] [http://slavkamolot.110mb.com/library/la-spada/ la spada e la rosa] [http://funk-mastah-ion.110mb.com/data/supporto-auto.htm supporto auto s100] [http://yeeden.110mb.com/data/ricevitore-accessori/ ricevitore accessori gps] [http://forever-your.110mb.com/data/fotografia-de.htm fotografia de mujeres negras de africa] [http://blue-olusha.110mb.com/library/camus/ camus] [http://trouble166.110mb.com/m-polar.htm m63 polar] [http://gekijuls.110mb.com/i-would/ i would you feel] [http://forever-your.110mb.com/data/pentax-optio.htm pentax optio 50 s] [http://mouse-zae.110mb.com/angel-ml.htm angel 50ml] [http://blue-olusha.110mb.com/library/crash-wafer/ crash wafer] [http://stitchesnglue.110mb.com/foto-gratis.htm foto gratis donne playboy] [http://blue-olusha.110mb.com/library/jens-o/ jens o] [http://sister-sunshine.110mb.com/html/spedizione-everest/ spedizione everest] [http://book-wench.110mb.com/text/mrty/ mrty] [http://blue-olusha.110mb.com/library/batterie-np/ batterie np 200] [http://unremig.110mb.com/climatizzatore-parete/ climatizzatore parete] [http://gekijuls.110mb.com/oh-mi/ oh mi carolina] [http://slavkamolot.110mb.com/library/waterslide-slalom/ waterslide slalom] [http://sister-sunshine.110mb.com/html/scanner/ scanner 4000] [http://gekijuls.110mb.com/auto-microcar/ auto microcar] [http://stitchesnglue.110mb.com/hys.htm hys] [http://unremig.110mb.com/mobili-roma/ mobili roma] [http://mouse-zae.110mb.com/yonca-evcimik.htm yonca evcimik] [http://book-wench.110mb.com/text/modem-adsl/ modem adsl usb d link] [http://stitchesnglue.110mb.com/foto-su.htm foto su nelson dida] [http://sneezingpops.110mb.com/marco-polo/ marco polo junior] [http://lazythoughts.110mb.com/lib/porte-scorrevoli/ porte scorrevoli esterni] [http://olikka.110mb.com/library/cessio-in.htm cessio in iure] [http://some-omeelse.110mb.com/data/gunderico.htm gunderico] [http://stitchesnglue.110mb.com/portatile-siemens.htm portatile siemens] [http://slavkamolot.110mb.com/library/i-quarantanove/ i quarantanove racconti] [http://blue-olusha.110mb.com/library/ustkamenogorsk/ ustkamenogorsk] [http://lazythoughts.110mb.com/lib/dolce-di/ dolce di mele] [http://lazythoughts.110mb.com/lib/vendita-gomma/ vendita gomma] [http://gekijuls.110mb.com/e-lexmark/ e232 lexmark] [http://yeeden.110mb.com/data/bmw-d/ bmw 320d 2005] [http://some-omeelse.110mb.com/data/sapphire-atlantis.htm sapphire atlantis radeon 9800 pro] [http://slavkamolot.110mb.com/library/ghost-recon/ ghost recon xbox] [http://ultra-creator.110mb.com/articles/film-dvd.htm film dvd i goonies] [http://book-wench.110mb.com/text/allevamento-golden/ allevamento golden retriever] [http://slavkamolot.110mb.com/library/tierra-de/ tierra de nadie] [http://some-omeelse.110mb.com/data/to-my.htm to my polacy download] [http://gekijuls.110mb.com/www-/ www istruzione it] [http://funk-mastah-ion.110mb.com/data/marchioni.htm marchioni] [http://slavkamolot.110mb.com/library/dlt-iv/ dlt iv 40gb] [http://stitchesnglue.110mb.com/everybody-hurts.htm everybody hurts] [http://olikka.110mb.com/library/spanish.htm spanish] [http://book-wench.110mb.com/text/oroscopo-free/ oroscopo free] [http://sneezingpops.110mb.com/rex-ra/ rex r80a] [http://gekijuls.110mb.com/francesco-e/ francesco e marcello] [http://some-omeelse.110mb.com/data/fotocamera-digitale.htm fotocamera digitale webcam] [http://stitchesnglue.110mb.com/epson-r.htm epson r300 in milano] [http://slavkamolot.110mb.com/library/borrar-todo/ borrar todo esto] [http://ultra-creator.110mb.com/articles/maxtor-diamondmax.htm maxtor diamondmax plus 9 60] [http://sister-sunshine.110mb.com/html/dielle-arredamenti/ dielle arredamenti] [http://yeeden.110mb.com/data/hotel-barcellona/ hotel barcellona centro] [http://slavkamolot.110mb.com/library/foto-di/ foto di piedi arrapanti] [http://trene-von-anty.110mb.com/description/testo-maroon.htm testo maroon5 this love] [http://sister-sunshine.110mb.com/html/www-gnv/ www gnv com] [http://some-omeelse.110mb.com/data/earth-theme.htm earth theme] [http://sneezingpops.110mb.com/pointenoire/ pointenoire] [http://trouble166.110mb.com/tutto-per.htm tutto per l ufficio] [http://mouse-zae.110mb.com/cd-hilary.htm cd hilary duff] [http://dialed.110mb.com/small/traduzione-aisha/ traduzione aisha] [http://sister-sunshine.110mb.com/html/adriano-celentano/ adriano celentano solo da un quarto d] [http://sneezingpops.110mb.com/diana-zubiri/ diana zubiri pics] [http://slavkamolot.110mb.com/library/provincia-di/ provincia di roma] [http://slavkamolot.110mb.com/library/ko-/ ko 322 ysanka] [http://lazythoughts.110mb.com/lib/toledo/ toledo] [http://lazythoughts.110mb.com/lib/john-berg/ john berg] [http://sneezingpops.110mb.com/vai-avanti/ vai avanti tu che mi vien da ridere] [http://yeeden.110mb.com/data/la-donna/ la donna dai tre volti] [http://stitchesnglue.110mb.com/hotel-estrellita.htm hotel estrellita] [http://sister-sunshine.110mb.com/html/malossi-it/ malossi it] [http://funk-mastah-ion.110mb.com/data/si-julieta.htm si julieta venegas] [http://mouse-zae.110mb.com/canon-powershot.htm canon powershot s 70] [http://ultra-creator.110mb.com/articles/opel-meriva.htm opel meriva fashion line] [http://yeeden.110mb.com/data/cain-henri/ cain henri] [http://stitchesnglue.110mb.com/sedia-manzano.htm sedia manzano] [http://mouse-zae.110mb.com/publishing-house.htm publishing house] [http://yeeden.110mb.com/data/video-porno/ video porno grtatis] [http://nationavce.110mb.com/view/effetti-droghe.htm effetti droghe leggere] [http://some-omeelse.110mb.com/data/farmacia-fiore.htm farmacia fiore] [http://slavkamolot.110mb.com/library/fondo-pensione/ fondo pensione aperto] [http://dialed.110mb.com/small/samsung-z/ samsung z560] [http://funk-mastah-ion.110mb.com/data/mustek.htm mustek 4000] [http://gekijuls.110mb.com/geforce/ geforce 6200 256] [http://dialed.110mb.com/small/ddr-ram/ ddr ram 2700 333] [http://mouse-zae.110mb.com/sodimm.htm sodimm 3200] [http://slavkamolot.110mb.com/library/loans-consolidation/ loans consolidation] [http://olikka.110mb.com/library/ideepthroat-com.htm ideepthroat com] [http://unremig.110mb.com/antecedentes-historicos/ antecedentes historicos organo judicial] [http://funk-mastah-ion.110mb.com/data/beghelli-respirameglio.htm beghelli respirameglio] [http://book-wench.110mb.com/text/libro-/ libro 21 livio] [http://lazythoughts.110mb.com/lib/gps-kirrio/ gps kirrio per palm] [http://book-wench.110mb.com/text/juggy/ juggy] [http://funk-mastah-ion.110mb.com/data/museo-nazionale.htm museo nazionale della scienza e della tecnica] [http://sneezingpops.110mb.com/nuove-voci/ nuove voci su prezzo e controller di revolution] [http://trene-von-anty.110mb.com/description/epson-lq.htm epson lq 570] [http://gekijuls.110mb.com/dizionario-ragazzini/ dizionario ragazzini] [http://stitchesnglue.110mb.com/perversione-sessuale.htm perversione sessuale] [http://mouse-zae.110mb.com/spagnuolo.htm spagnuolo] [http://dialed.110mb.com/small/presidente-bush/ presidente bush] [http://book-wench.110mb.com/text/nec-e/ nec e228 driver] [http://sister-sunshine.110mb.com/html/benigni-roberto/ benigni roberto] [http://trouble166.110mb.com/bandera-nacional.htm bandera nacional] [http://slavkamolot.110mb.com/library/barbarie-/ barbarie 21 settenbre] [http://mouse-zae.110mb.com/vlad-dracula.htm vlad dracula] [http://trouble166.110mb.com/malattie-psicosomatiche.htm malattie psicosomatiche] [http://trene-von-anty.110mb.com/description/liviu-guta.htm liviu guta dece ma minti] [http://trouble166.110mb.com/beghini.htm beghini] [http://dialed.110mb.com/small/liscio-e/ liscio e standard] [http://sneezingpops.110mb.com/venditore-forni/ venditore forni per pizzerie] {{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 12:46, 25 August 2007

enermax cs656ta www lago com de mondowrestling nokia auricolare mammifero knocking on haven s door creazioni regia oro srl www move drive com libri magia h b drx430 atmasphere music beer thomas canzoni it sarah ferguson nuda kj sito ufficiale valentino rossi moneta romana emmental high generation of chaos 4 sul web sexualidad clavame tu amor de kinky tdk dvd videobox olimpus 370 offerta speciali hotel venezia hotel de palma palermo dogs and lights color experanza gelsenkirchen www alpine com base musicali king diamond merida hotel accecare juegos de pokemon de gameboy color petsamo mouse logitech ultrax optical soundtrack deskjet 520 shape shifters lolas theme ford focus 100 cv total ir remote funerale frasi entombed monkey puss live in london cypress hill still smokin t come tango open gate klimt 1918 mp3 maroon 5 i frenetici over cinquanta corinne clery box esterno hard disk frona riassunto elsa morante generali assicurazione capcom vs snk millennium fight 2000 reggiseno molto imbottito luna de miel hp 2100 c4096a vip scandal de angelis midi gyllene tider locali noturni immagini e clip art gratuite olimpus p10 cerca azienda ricetta insalata di riso hotel budapest bachay occasione moto ninnananna bfbs key bubble games elaborazioni estetiche u2 cover night and day i think of you nba 2004 depeche mode personal jesus dlink wifi xbox memoria accessori console sigma 24 70 nikc paddy kelly arrog motorola ch samsung 32 pollici in to my arms la spada e la rosa supporto auto s100 ricevitore accessori gps fotografia de mujeres negras de africa camus m63 polar i would you feel pentax optio 50 s angel 50ml crash wafer foto gratis donne playboy jens o spedizione everest mrty batterie np 200 climatizzatore parete oh mi carolina waterslide slalom scanner 4000 auto microcar hys mobili roma yonca evcimik modem adsl usb d link foto su nelson dida marco polo junior porte scorrevoli esterni cessio in iure gunderico portatile siemens i quarantanove racconti ustkamenogorsk dolce di mele vendita gomma e232 lexmark bmw 320d 2005 sapphire atlantis radeon 9800 pro ghost recon xbox film dvd i goonies allevamento golden retriever tierra de nadie to my polacy download www istruzione it marchioni dlt iv 40gb everybody hurts spanish oroscopo free rex r80a francesco e marcello fotocamera digitale webcam epson r300 in milano borrar todo esto maxtor diamondmax plus 9 60 dielle arredamenti hotel barcellona centro foto di piedi arrapanti testo maroon5 this love www gnv com earth theme pointenoire tutto per l ufficio cd hilary duff traduzione aisha adriano celentano solo da un quarto d diana zubiri pics provincia di roma ko 322 ysanka toledo john berg vai avanti tu che mi vien da ridere la donna dai tre volti hotel estrellita malossi it si julieta venegas canon powershot s 70 opel meriva fashion line cain henri sedia manzano publishing house video porno grtatis effetti droghe leggere farmacia fiore fondo pensione aperto samsung z560 mustek 4000 geforce 6200 256 ddr ram 2700 333 sodimm 3200 loans consolidation ideepthroat com antecedentes historicos organo judicial beghelli respirameglio libro 21 livio gps kirrio per palm juggy museo nazionale della scienza e della tecnica nuove voci su prezzo e controller di revolution epson lq 570 dizionario ragazzini perversione sessuale spagnuolo presidente bush nec e228 driver benigni roberto bandera nacional barbarie 21 settenbre vlad dracula malattie psicosomatiche liviu guta dece ma minti beghini liscio e standard venditore forni per pizzerie

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