; link with PIOxxx.OBJ

        sectionbss

crctable.d:     resd 256

        sectiondata

havetable.b:    db 0
string:         db "The quick brown fox jumps over the lazy dog"
stringend:
                db 13,10,0        ; carriage return and null terminator

        sectioncode

start!
        gosub initplatform

        beginfunc
        localvar crc.d

        callex ,printnt,"input = ".a
        callex ,printnt,string

        callex ,printnt,"The CRC-32 checksum = ".a
        callex crc,crc32,string,stringend
        callex ,printhexr,crc

        endfunc
        end

crc32:
        beginfunc bufend.d,buf.d
        localvar i.d,j.d,k.d,k2.d,crc.d

        ifunequal havetable,0,tabledone
        i=0
        whileless i,256

        k=i > j=8
        countdown j
        k2=k > k=_ shr 1
        ifequal k2 and 1,0,noxor > k=_ xor $EDB88320
noxor:
        nextcount

        crctable(i shl 2)=k
        i=_+1
        wend

        havetable=1
tabledone:

        crc=-1

        whileless buf,bufend
        crc=_ shr 8 xor crctable(crc and $FF xor [buf].b shl 2)
        buf=_+1
        wend

        crc=_ xor -1
        endfunc crc
        returnex 8                        ; clean off 2 parameters from the stack


MODULE CRC32;
IMPORT
  NPCT:Zlib,
  Strings,
  Out;
VAR
  s: ARRAY 128 OF CHAR;
BEGIN
  COPY("The quick brown fox jumps over the lazy dog",s);
  Out.Hex(Zlib.CRC32(0,s,0,Strings.Length(s)),0);Out.Ln
END CRC32.


class CRC32 {
  function : Main(args : String[]) ~ Nil {
    "The quick brown fox jumps over the lazy dog"->ToByteArray()->CRC32()->PrintLine();
  }
}


let () =
  let s = "The quick brown fox jumps over the lazy dog" in
  let crc = Zlib.update_crc 0l s 0 (String.length s) in
  Printf.printf "crc: %lX\n" crc


(define (crc32 str)
   (bxor #xFFFFFFFF
      (fold (lambda (crc char)
               (let loop ((n 8) (crc crc) (bits char))
                  (if (eq? n 0)
                     crc
                     (let*((flag (band (bxor bits crc) 1))
                           (crc (>> crc 1))
                           (crc (if (eq? flag 0) crc (bxor crc #xEDB88320)))
                           (bits (>> bits 1)))
                        (loop (- n 1) crc bits)))))
         #xFFFFFFFF
         (string->list str))))

(print (number->string (crc32 "The quick brown fox jumps over the lazy dog") 16))
(print (number->string (crc32 (list->string (repeat #x00 32))) 16))
(print (number->string (crc32 (list->string (repeat #xFF 32))) 16))
(print (number->string (crc32 (list->string (iota 32))) 16))


/* ooRexx */
clzCRC32=bsf.importClass("java.util.zip.CRC32")
myCRC32 =clzCRC32~new
toBeEncoded="The quick brown fox jumps over the lazy dog"
myCRC32~update(BsfRawBytes(toBeEncoded))
numeric digits 20
say 'The CRC-32 value of "'toBeEncoded'" is:' myCRC32~getValue~d2x

::requires "BSF.CLS"    -- get Java bridge


install("crc32", "lLsL", "crc32", "libz.so");
s = "The quick brown fox jumps over the lazy dog";
printf("%0x\n", crc32(0, s, #s))


#!/usr/bin/perl
use 5.010 ;
use strict ;
use warnings ;
use Digest::CRC qw( crc32 ) ;

my $crc = Digest::CRC->new( type => "crc32" ) ;
$crc->add ( "The quick brown fox jumps over the lazy dog" )  ;
say "The checksum is " . $crc->hexdigest( ) ;


with javascript_semantics
sequence table
bool have_table = false

function crc32(string s)
    if not have_table then
        have_table = true
        table = repeat(0,256)
        for i=0 to 255 do
            atom rem = i
            for j=1 to 8 do
                if and_bits(rem,1) then
                    rem = xor_bits(floor(rem/2),#EDB88320)
                else
                    rem = floor(rem/2)
                end if
                if rem<0 then
                    rem += #100000000
                end if
            end for
            table[i+1] = rem
        end for
    end if
    atom crc = #FFFFFFFF
    for i=1 to length(s) do
        crc = xor_bits(floor(crc/#100),table[xor_bits(and_bits(crc,0xff),s[i])+1])
        if crc<0 then
            crc += #100000000
        end if
    end for
    return and_bits(not_bits(crc),#FFFFFFFF)
end function

string s = "The quick brown fox jumps over the lazy dog"
printf(1,"The CRC of %s is %08x\n",{s,crc32(s)})


printf("%x\n", crc32("The quick brown fox jumps over the lazy dog"));


(setq *Table
   (mapcar
      '((N)
         (do 8
            (setq N
               (if (bit? 1 N)
                  (x| (>> 1 N) `(hex "EDB88320"))
                  (>> 1 N) ) ) ) )
      (range 0 255) ) )

(de crc32 (Lst)
   (let Crc `(hex "FFFFFFFF")
      (for I (chop Lst)
         (setq Crc
            (x|
               (get
                  *Table
                  (inc (x| (& Crc 255) (char I))) )
               (>> 8 Crc) ) ) )
      (x| `(hex "FFFFFFFF") Crc) ) )

(let Str "The quick brown fox jumps over the lazy dog"
   (println (hex (crc32 Str)))
   (println
      (hex (native "libz.so" "crc32" 'N 0 Str (length Str))) ) )

(bye)


string foo = "The quick brown fox jumps over the lazy dog";
write("0x%x\n", Gz.crc32(foo));


#COMPILE EXE
#DIM ALL
#COMPILER PBCC 6

' ***********

FUNCTION CRC32(BYVAL p AS BYTE PTR, BYVAL NumBytes AS DWORD) AS DWORD
  STATIC LUT() AS DWORD
  LOCAL i, j, k, crc AS DWORD

  IF ARRAYATTR(LUT(), 0) = 0 THEN
    REDIM LUT(0 TO 255)
    FOR i = 0 TO 255
      k = i
      FOR j = 0 TO 7
        IF (k AND 1) THEN
          SHIFT RIGHT k, 1
          k XOR= &HEDB88320
        ELSE
          SHIFT RIGHT k, 1
        END IF
      NEXT j
      LUT(i) = k
    NEXT i
  END IF

  crc = &HFFFFFFFF

  FOR i = 0 TO NumBytes - 1
    k = (crc AND &HFF& XOR @p[i])
    SHIFT RIGHT crc, 8
    crc XOR= LUT(k)
  NEXT i

  FUNCTION = NOT crc
END FUNCTION

' ***********

FUNCTION PBMAIN () AS LONG
  LOCAL s AS STRING
  LOCAL crc AS DWORD

  s = "The quick brown fox jumps over the lazy dog"
  CON.PRINT "Text:  " & s
  crc = CRC32(STRPTR(s), LEN(s))
  CON.PRINT "CRC32: " & HEX$(crc)
END FUNCTION


a$="The quick brown fox jumps over the lazy dog"

UseCRC32Fingerprint() : b$=StringFingerprint(a$, #PB_Cipher_CRC32)

OpenConsole()
PrintN("CRC32 Cecksum [hex] = "+UCase(b$))
PrintN("CRC32 Cecksum [dec] = "+Val("$"+b$))
Input()

End


>>> s = 'The quick brown fox jumps over the lazy dog'
>>> import zlib
>>> hex(zlib.crc32(s))
'0x414fa339'

>>> import binascii
>>> hex(binascii.crc32(s))
'0x414fa339'


PRINT HEX$(crc32("The quick brown fox jumps over the lazy dog"))

FUNCTION crc32~& (buf AS STRING)
    STATIC table(255) AS _UNSIGNED LONG
    STATIC have_table AS _BYTE
    DIM crc AS _UNSIGNED LONG, k AS _UNSIGNED LONG
    DIM i AS LONG, j AS LONG

    IF have_table = 0 THEN
        FOR i = 0 TO 255
            k = i
            FOR j = 0 TO 7
                IF (k AND 1) THEN
                    k = _SHR(k, 1)
                    k = k XOR &HEDB88320
                ELSE
                    k = _SHR(k, 1)
                END IF
                table(i) = k
            NEXT
        NEXT
        have_table = -1
    END IF

    crc = NOT crc ' crc = &Hffffffff

    FOR i = 1 TO LEN(buf)
        crc = (_SHR(crc, 8)) XOR table((crc AND &HFF) XOR ASC(buf, i))
    NEXT

    crc32~& = NOT crc
END FUNCTION


  [ table ]                      is crctable ( n --> n )

  256 times
    [ i^ 8 times
      [ dup 1 >>
        swap 1 & if
          [ hex EDB88320 ^ ] ]
     ' crctable put ]

  [ hex FFFFFFFF swap
    witheach
      [ over ^ hex FF &
        crctable
        swap 8 >> ^ ]
     hex FFFFFFFF ^ ]            is crc-32   ( [ --> n )

  $ "The quick brown fox jumps over the lazy dog" crc-32
  16 base put
  echo
  base release


digest("The quick brown fox jumps over the lazy dog","crc32", serialize=F)


#lang racket
(define (bytes-crc32 data)
  (bitwise-xor
   (for/fold ([accum #xFFFFFFFF])
     ([byte  (in-bytes data)])
     (for/fold ([accum (bitwise-xor accum byte)])
       ([num (in-range 0 8)])
       (bitwise-xor (quotient accum 2)
                    (* #xEDB88320 (bitwise-and accum 1)))))
   #xFFFFFFFF))

(define (crc32 s)
  (bytes-crc32 (string->bytes/utf-8 s)))

(format "~x" (crc32 "The quick brown fox jumps over the lazy dog"))


use NativeCall;

sub crc32(int32 $crc, Buf $buf, int32 $len --> int32) is native('z') { * }

my $buf = 'The quick brown fox jumps over the lazy dog'.encode;
say crc32(0, $buf, $buf.bytes).fmt('%08x');


/*REXX program computes the  CRC─32  (32 bit Cyclic Redundancy Check)  checksum  for a  */
/*─────────────────────────────────given string  [as described in ISO 3309, ITU─T V.42].*/
call show  'The quick brown fox jumps over the lazy dog'               /*the 1st string.*/
call show  'Generate CRC32 Checksum For Byte Array Example'            /* "  2nd    "   */
exit                                             /*stick a fork in it,  we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
CRC_32: procedure; parse arg !,$; c= 'edb88320'x /*2nd arg used for repeated invocations*/
                                  f= 'ffFFffFF'x /* [↓]  build an  8─bit  indexed table,*/
          do i=0  for 256;        z= d2c(i)      /*                  one byte at a time.*/
          r= right(z, 4, '0'x)                   /*insure the  "R"   is thirty─two bits.*/
                                                 /* [↓]  handle each rightmost byte bit.*/
            do j=0  for 8;       rb= x2b(c2x(r)) /*handle each bit of rightmost 8 bits. */
            r= x2c( b2x(0 || left(rb, 31) ) )    /*shift it right (an unsigned)  1  bit.*/
            if right(rb,1)  then r= bitxor(r, c) /*this is a bin bit for XOR grunt─work.*/
            end    /*j*/
          !.z= r                                 /*assign to an eight─bit index table.  */
          end      /*i*/
        $=bitxor( word($ '0000000'x, 1), f)      /*utilize the user's CRC or a default. */
          do k=1  for length(!  )                /*start number crunching the input data*/
          ?= bitxor(right($,1),  substr(!,k,1) )
          $= bitxor('0'x || left($, 3),  !.?)
          end   /*k*/
        return $                                 /*return with cyclic redundancy check. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
show:   procedure;   parse arg Xstring;   numeric digits 12;      say;     say
        checksum= bitxor(CRC_32(Xstring), 'ffFFffFF'x) /*invoke CRC_32 to create a CRC. */
        say center(' input string [length of' length(Xstring) "bytes] ", 79, '═')
        say Xstring;      say                          /*show the string on its own line*/
        say  "hex CRC─32 checksum ="   c2x(checksum)     left('', 15),
             "dec CRC─32 checksum ="   c2d(checksum)   /*show the CRC─32 in hex and dec.*/
        return


require 'zlib'
printf "0x%08x\n", Zlib.crc32('The quick brown fox jumps over the lazy dog')
# => 0x414fa339


fn crc32_compute_table() -> [u32; 256] {
    let mut crc32_table = [0; 256];

    for n in 0..256 {
        crc32_table[n as usize] = (0..8).fold(n as u32, |acc, _| {
            match acc & 1 {
                1 => 0xedb88320 ^ (acc >> 1),
                _ => acc >> 1,
            }
        });
    }

    crc32_table
}

fn crc32(buf: &str) -> u32 {
    let crc_table = crc32_compute_table();

    !buf.bytes().fold(!0, |acc, octet| {
        (acc >> 8) ^ crc_table[((acc & 0xff) ^ octet as u32) as usize]
    })
}

fn main() {
    println!("{:x}", crc32("The quick brown fox jumps over the lazy dog"));
}


import java.util.zip.CRC32
val crc=new CRC32
crc.update("The quick brown fox jumps over the lazy dog".getBytes)
println(crc.getValue.toHexString)  //> 414fa339


$ include "seed7_05.s7i";
  include "crc32.s7i";

const proc: main is func
  begin
    writeln(ord(crc32("The quick brown fox jumps over the lazy dog")) radix 16 lpad0 8);
  end func;


#!/usr/bin/env bash
declare -i -a CRC32_LOOKUP_TABLE

__generate_crc_lookup_table() {
  local -i -r LSB_CRC32_POLY=0xEDB88320 # The CRC32 polynomal LSB order
  local -i index byte lsb
  for index in {0..255}; do
    ((byte = 255 - index))
    for _ in {0..7}; do # 8-bit lsb shift
      ((lsb = byte & 0x01, byte = ((byte >> 1) & 0x7FFFFFFF) ^ (lsb == 0 ? LSB_CRC32_POLY : 0)))
    done
    ((CRC32_LOOKUP_TABLE[index] = byte))
  done
}
__generate_crc_lookup_table
typeset -r CRC32_LOOKUP_TABLE

crc32_string() {
  [[ ${#} -eq 1 ]] || return
  local -i i byte crc=0xFFFFFFFF index
  for ((i = 0; i < ${#1}; i++)); do
    byte=$(printf '%d' "'${1:i:1}") # Get byte value of character at i
    ((index = (crc ^ byte) & 0xFF, crc = (CRC32_LOOKUP_TABLE[index] ^ (crc >> 8)) & 0xFFFFFFFF))
  done
  echo $((crc ^ 0xFFFFFFFF))
}

printf 'The CRC32 of: %s\nis: 0x%08x\n' "${1}" "$(crc32_string "${1}")"

# crc32_string "The quick brown fox jumps over the lazy dog"
# yields 414fa339


V width = 3
V height = 5
V myarray = [[0] * width] * height
print(myarray[height-1][width-1])


CRC32Stream hashValueOf:'The quick brown fox jumps over the lazy dog'


import Foundation

let strData = "The quick brown fox jumps over the lazy dog".dataUsingEncoding(NSUTF8StringEncoding,
    allowLossyConversion: false)
let crc = crc32(uLong(0), UnsafePointer<Bytef>(strData!.bytes), uInt(strData!.length))

println(NSString(format:"%2X", crc))


package require Tcl 8.6

set data "The quick brown fox jumps over the lazy dog"
puts [format "%x" [zlib crc32 $data]]


(crc32 "The quick brown fox jumps over the lazy dog")


;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; Array setup
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
Create_2D_Array:
ARRAY_2D equ $100000
ARRAY_POINTER_VARIABLE equ $200000
; input: D0 = width, D1 = height
; assume the input is byte length and unsigned, ranging from 1 to FF.

AND.L #$000000FF,D0
AND.L #$000000FF,D1 ;sanitize the input to byte length.

LEA ARRAY_2D,A0     ;get base array address.

;The array's size will be measured in bytes, as this is how memory offsetting is measured.
;For this example the elements will all be 32-bit.
;Therefore, the dimensions need to be multiplied by the byte count of each element.

LSL.W #2,D0         ;four bytes per element = multiply by 4
LSL.W #2,D1

;Next, these values are multiplied to get the array's size.
MOVE.L D0,D2
MULU D1,D2
;D2 is the array's size (measured in bytes) and will be placed at the beginning.
;This does not count as an element of the array for the purposes of row/column indexing.
;The array's base address will be offset by 4 bytes prior to any indexing.

MOVE.L D2,(A0)+     ;store D2 in A0, add 4 to A0
MOVEA.L A0,[ARRAY_POINTER_VARIABLE]

;the brackets are optional, they show that this is a memory address label.
;this is still a move to a memory address with or without the brackets.

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; Storing a value in the array
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

LEA ARRAY_POINTER_VARIABLE,A1    ;load the address where the array's base address is stored.
MOVE.L (A1),A1                   ;dereference the pointer and get ARRAY_2D+4 into A1.

; for this example the arbitrary row/column indices (2,5) will be used.

MOVE.L #2,D4
MULU D0,D4                       ;there are D0 entries per row, multiply row index by elements per row.
MOVE.L #5,D5
MOVE.L #$00112233,D7             ;determine the value we want to store in the array.

; The bytes per element was factored into D0 when the array was created. So D4 is already where it should be.
LSL.L #2,D5                      ;column index still needs to be scaled by the bytes per element.

LEA (A1,D4),A1                   ;select the desired row.

;68000 doesn't allow you to use more than 1 data register at a time to offset. So we have to offset separately.
;Despite the use of parentheses this is NOT a dereference like it would be with "MOVE.L (A1),D7". D4 is merely added to the address in A1.

MOVE.L D7,(A1,D5)                ;store #$00112233 in row 2, column 5 of the array.

;Loading a value is the same as storing it, except the operands in the last instruction are reversed, and MOVE.L #$00112233,D7
;is omitted.

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; Destroying the array
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

; The array is destroyed by storing something else in its location. If you really want to reset it to zero, you can
; do so with the following:

LEA ARRAY_POINTER_VARIABLE,A1
MOVE.L (A1),A1
MOVE.L -(A1),D7
;get the array size into D7. Remember that the array's size was stored just before its data.
This value is potentially too large for a single DBRA, but it can be split up.

SWAP D7
MOVE.W D7,D6                    ;get the top half of D7 into D6. D6 will be the outer loop's DBRA value.
SWAP D7
SUBQ.L #1,D7                    ;D7 needs to be decremented by 1. D6 is fine the way it is.

MOVE.L (A0)+,D0                 ;dummy move to increment the pointer back to the array base.
MOVEQ #0,D0                     ;faster than MOVE.L #0,D0

loop_destroyArray:
MOVE.L D0,(A0)+
DBRA D7,loop_destroyArray       ;loop using bottom 2 bytes of the array size as a loop counter
DBRA D6,loop_destroyArray       ;decrement this, D7 is $FFFF each time execution gets here so this acts as a "carry" of sorts.
                                ;if this value was 0 prior to the loop, the loop ends immediately.


using ZLib.Utility;

void main() {
  var str = (uint8[])"The quick brown fox jumps over the lazy dog".to_utf8();
  stdout.printf("%lx\n", crc32(0, str));
}


dim crctbl(255)
const crcc =&hEDB88320

sub gencrctable
for i= 0 to 255
   k=i
   for j=1 to 8
    if k and 1 then
      k=(k and &h7fffffff)\2 or (&h40000000 and ((k and &h80000000)<>0))
      k=k xor crcc
    else
      k=(k and &h7fffffff)\2 or (&h40000000 and ((k and &h80000000)<>0))
   end if
   next ' j
   crctbl(i)=k
 next
end sub

 function crc32 (buf)
  dim r,r1,i
  r=&hffffffff
  for i=1 to len(buf)
      r1=(r and &h7fffffff)\&h100 or (&h800000 and (r and &h80000000)<>0)
    r=r1 xor crctbl((asc(mid(buf,i,1))xor r) and 255)
  next
  crc32=r xor &hffffffff
end function

'414FA339
gencrctable
wscript.stdout.writeline hex(crc32("The quick brown fox jumps over the lazy dog"))


Option Explicit
Declare Function RtlComputeCrc32 Lib "ntdll.dll" _
  (ByVal dwInitial As Long, pData As Any, ByVal iLen As Long) As Long
'--------------------------------------------------------------------
Sub Main()
Dim s As String
Dim b() As Byte
Dim l As Long

  s = "The quick brown fox jumps over the lazy dog"
  b() = StrConv(s, vbFromUnicode) 'convert Unicode to ASCII
  l = RtlComputeCrc32(0&, b(0), Len(s))
  Debug.Assert l = &H414FA339

End Sub


with Ada.Text_Io;
with Ada.Float_Text_Io;
with 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
   Ada.Integer_Text_Io.Get(Item => Dim_1);
   Ada.Integer_Text_Io.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;
      Ada.Float_Text_Io.Put(Item => Matrix(1, Dim_2), Fore => 1, Aft => 5, Exp => 0);
      Ada.Text_Io.New_Line;
   end;
   -- The variable Matrix is popped off the stack automatically
end Two_Dimensional_Arrays;


 begin
    comment Create a two-dimensional array at runtime - Algol 60;
    integer n,m;
    ininteger(0,m);
    ininteger(0,n);
    begin
        integer array a[1:m,1:n];
        a[m,n] := 99;
        outinteger(1,a[m,n]);
		outstring(1,"\n")
    end;
    comment array a : out of scope;
end


Public Class Crc32

    ' Table for pre-calculated values.
    Shared table(255) As UInteger

    ' Initialize table
    Shared Sub New()
        For i As UInteger = 0 To table.Length - 1
            Dim te As UInteger = i ' table entry
            For j As Integer = 0 To 7
                If (te And 1) = 1 Then te = (te >> 1) Xor &HEDB88320UI Else te >>= 1
            Next
            table(i) = te
        Next
    End Sub

    ' Return checksum calculation for Byte Array,
    '  optionally resuming (used when breaking a large file into read-buffer-sized blocks).
    ' Call with Init = False to continue calculation.
    Public Shared Function cs(BA As Byte(), Optional Init As Boolean = True) As UInteger
        Static crc As UInteger
        If Init Then crc = UInteger.MaxValue
        For Each b In BA
            crc = (crc >> 8) Xor table((crc And &HFF) Xor b)
        Next
        Return Not crc
    End Function

End Class


import "/fmt" for Conv

class CRC32 {
    static init() {
        __table = List.filled(256, 0)
        for (i in 0..255) {
            var word = i
            for (j in 0..7) {
                if (word&1 == 1) {
                    word = (word >> 1) ^ 0xedb88320
                } else {
                    word = word >> 1
                }
            }
            __table[i] = word
         }
    }

    static compute(s) {
        var crc = ~0
        var le = s.bytes.count
        for (i in 0...le) {
            var crb = crc & 0xff
            crc = __table[crb^s[i].bytes[0]] ^ (crc >> 8)
        }
        return ~crc
    }
}

CRC32.init()
var crc = CRC32.compute("The quick brown fox jumps over the lazy dog")
System.print(Conv.hex(crc))


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


begin
    integer dimension1UpperBound, dimension2UpperBound;
    write( "upper bound for dimension 1: " );
    read( dimension1UpperBound );
    write( "upper bound for dimension 2: " );
    read( dimension2UpperBound );

    begin
        % we start a new block because declarations must precede statements %
        % and variables in array bounds must be from outside the block      %
        integer array matrix ( 1 :: dimension1UpperBound
                             , 1 :: dimension2UpperBound
                             );
        % set the first element - the program will crash if the user input  %
        % upper bounds less than 1                                          %
        matrix( 1, 1 ) := 3;
        % write it                                                          %
        write( matrix( 1, 1 ) );
        % the array is automatically deleted when the block ends            %
    end

end.


#include <flow.h>
#import   lib/input.bas.lib
#include  include/flow-input.h

DEF-MAIN
   CLR-SCR
   MSET(nRow, nCol)
   LOCATE( 2,5 ), PRN("Input size rows :")
   LOC-COL( 23 ), LET( nRow := ABS(VAL(READ-NUMBER( nRow ) )))
   LOCATE( 3,5 ), PRN("Input size cols :")
   LOC-COL( 23 ), LET( nCol := ABS(VAL(READ-NUMBER( nCol ) )))

   COND( IS-NOT-ZERO?( MUL(nRow,nCol) ) )
      DIM(nRow, nCol) AS-VOID( array )
      BLK-[1,1], {100} PUT(array)
                 PRNL("\tElement at position 1,1 : ", GET(array) )
      CLEAR(array)  /* destroy array */
   CEND
END
SUBRUTINES


code HexOut=27;         \intrinsic routine
string 0;               \use zero-terminated strings

func CRC32(Str, Len);   \Return CRC-32 for given string
char Str;  int Len;     \byte array, number of bytes
int  I, J, R, C;
[R:= -1;                \initialize with all 1's
for J:= 0 to Len-1 do
    [C:= Str(J);
    for I:= 0 to 8-1 do \for each bit in byte...
        [if (R xor C) and 1 then R:= R>>1 xor $EDB88320
        else R:= R>>1;
        C:= C>>1;
        ];
    ];
return not R;
];

HexOut(0, CRC32("The quick brown fox jumps over the lazy dog", 43))


var [const] ZLib=Import("zeelib");
ZLib.calcCRC32(Data(Void,"The quick brown fox jumps over the lazy dog"));
//-->0x414fa339


array←m n ⍴ 0 ⍝ array of zeros with shape of m by n.

array[1;1]←73 ⍝ assign a value to location 1;1.

array[1;1] ⍝ read the value back out

⎕ex 'array' ⍝ erase the array


set R to text returned of (display dialog "Enter number of rows:" default answer 2) as integer
set c to text returned of (display dialog "Enter number of columns:" default answer 2) as integer
set array to {}
repeat with i from 1 to R
	set temp to {}
	repeat with j from 1 to c
		set temp's end to 0
	end repeat
	set array's end to temp
end repeat

-- Address the first column of the first row:
set array's item 1's item 1 to -10

-- Negative index values can be used to address from the end:
set array's item -1's item -1 to 10

-- Access an item (row 2 column 1):
set x to array's item 2's item 1

return array

-- Destroy array (typically unnecessary since it'll automatically be destroyed once script ends).
set array to {}


width: to :integer input "give me the array's width: "
height: to :integer input "give me the array's height: "

arr: array.of: @[width height] 0

x: random 0 dec width
y: random 0 dec height

arr\[x]\[y]: 123

print ["item at [" x "," y "] =" arr\[x]\[y]]


Array := []
InputBox, data,, Enter two integers separated by a Space:`n(ex. 5 7)
StringSplit, i, data, %A_Space%
Array[i1,i2] := "that element"
MsgBox, % "Array[" i1 "," i2 "] = " Array[i1,i2]


; == get dimensions from user input
$sInput = InputBox('2D Array Creation', 'Input comma separated count of rows and columns, i.e. "5,3"')
$aDimension = StringSplit($sInput, ',', 2)

; == create array
Dim $a2D[ $aDimension[0] ][ $aDimension[1] ]

; == write value to last row/last column
$a2D[ UBound($a2D) -1 ][ UBound($a2D, 2) -1 ] = 'test string'

; == output this value to MsgBox
MsgBox(0, 'Output', 'row[' & UBound($a2D) -1 & '], col[' & UBound($a2D, 2) -1 & ']' & @CRLF & '= ' & $a2D[ UBound($a2D) -1 ][ UBound($a2D, 2) -1 ] )


/[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]]
  }
}


#!/usr/bin/env bqn

# Cut 𝕩 at occurrences of 𝕨, removing separators and empty segments
# (BQNcrate phrase).
Split ← (¬-˜⊢×·+`»⊸>)∘≠⊔⊢

# Natural number from base-10 digits (BQNcrate phrase).
Base10 ← 10⊸×⊸+˜´∘⌽

# Parse any number of space-separated numbers from string 𝕩.
ParseNums ← {Base10¨ -⟜'0' ' ' Split 𝕩}

# •GetLine is a nonstandard CBQN extension.
•Show ⥊⟜(↕×´) ParseNums •[email protected]


#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;
}


class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Enter two integers. Space delimited please: ");
            string s = Console.ReadLine();

            int[,] myArray=new int[(int)s[0],(int)s[2]];
            myArray[0, 0] = 2;
            Console.WriteLine(myArray[0, 0]);

            Console.ReadLine();
        }
    }


#include <iostream>

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;

  return 0;
}


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)


(let [rows (Integer/parseInt (read-line))
      cols (Integer/parseInt (read-line))
      a (to-array-2d (repeat rows (repeat cols nil)))]
  (aset a 0 0 12)
  (println "Element at 0,0:" (aget a 0 0)))


prompt = proc (s: string) returns (int)
    stream$puts(stream$primary_output(), s)
    return(int$parse(stream$getl(stream$primary_input())))
end prompt

start_up = proc ()
    po: stream := stream$primary_output()

    % Ask for width and height
    width: int := prompt("Width? ")
    height: int := prompt("Height? ")

    % Create an array of arrays.
    % In order to actually create separate arrays, rather than repeating
    % a reference to the same array over and over, fill_copy must be used.
    arr: array[array[int]] :=
        array[array[int]]$fill_copy(1, width, array[int]$fill(1, height, 0))

    % Set a value
    x: int := 1+width/2
    y: int := 1+height/2
    arr[x][y] := 123

    % Retrieve the value
    stream$putl(po, "arr[" || int$unparse(x) || "][" || int$unparse(y)
                 || "] = " || int$unparse(arr[x][y]))

    % The array will be automatically garbage-collected once there
    % are no more references to it.
end start_up


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


MODULE TestArray;
(* Implemented in BlackBox Component Builder *)

	IMPORT Out;

	(* Open array *)

	PROCEDURE DoTwoDim*;
		VAR d: POINTER TO ARRAY OF ARRAY OF INTEGER;
	BEGIN
		NEW(d, 5, 4); (* allocating array in memory *)
		d[1, 2] := 100; (* second row, third column element *)
		d[4, 3] := -100; (* fifth row, fourth column element *)
		Out.Int(d[1, 2], 0); Out.Ln;
		Out.Int(d[4, 3], 0); Out.Ln;
	END DoTwoDim;

END TestArray.


require "random"

first = gets.not_nil!.to_i32
second = gets.not_nil!.to_i32

arr = Array(Array(Int32)).new(first, Array(Int32).new second, 0)

random = Random.new

first = random.rand 0..(first - 1)
second = random.rand 0..(second - 1)

arr[first][second] = random.next_int
puts arr[first][second]


void main() {
    import std.stdio, std.conv, std.string;
    int nRow, nCol;

    write("Give me the numer of rows: ");
    try {
        nRow = readln.strip.to!int;
    } catch (StdioException) {
        nRow = 3;
        writeln;
    }

    write("Give me the numer of columns: ");
    try {
        nCol = readln.strip.to!int;
    } catch (StdioException) {
        nCol = 5;
        writeln;
    }

    auto array = new float[][](nRow, nCol);
    array[0][0] = 3.5;
    writeln("The number at place [0, 0] is ", array[0][0]);
}


program Project1;

{$APPTYPE CONSOLE}

uses
  SysUtils;
var
  matrix:array of array of Byte;
  i,j:Integer;
begin
  Randomize;
  //Finalization is not required in this case, but you have to do
  //so when reusing the variable in scope
  Finalize(matrix);
  //Init first dimension with random size from 1..10
  //Remember dynamic arrays are indexed from 0
  SetLength(matrix,Random(10) + 1);
  //Init 2nd dimension with random sizes too
  for i := Low(matrix) to High(matrix) do
    SetLength(matrix[i],Random(10) + 1);

  //End of code, the following part is just output
  Writeln(Format('Total amount of columns = %.2d',[Length(matrix)]));
  for i := Low(matrix) to High(matrix) do
    Writeln(Format('Column %.2d = %.2d rows',[i,Length(matrix[i])]));

  Readln;
end.


import extensions;

public program()
{
    var n := new Integer();
    var m := new Integer();

    console.write:"Enter two space delimited integers:";
    console.loadLine(n,m);

    var myArray := class Matrix<int>.allocate(n,m);

    myArray.setAt(0,0,2);

    console.printLine(myArray.at(0, 0))
}


defmodule TwoDimArray do

  def create(w, h) do
    List.duplicate(0, w)
      |> List.duplicate(h)
  end

  def set(arr, x, y, value) do
    List.replace_at(arr, x,
      List.replace_at(Enum.at(arr, x), y, value)
    )
  end

  def get(arr, x, y) do
    arr |> Enum.at(x) |> Enum.at(y)
  end
end

width = IO.gets "Enter Array Width: "
w = width |> String.trim() |> String.to_integer()

height = IO.gets "Enter Array Height: "
h = height |> String.trim() |> String.to_integer()

arr = TwoDimArray.create(w, h)
arr = TwoDimArray.set(arr,2,0,42)

IO.puts(TwoDimArray.get(arr,2,0))


-module( two_dimensional_array ).

-export( [create/2, get/3, set/4, task/0] ).

create( X, Y ) -> array:new( [{size, X}, {default, array:new( [{size, Y}] )}] ).

get( X, Y, Array ) -> array:get( Y, array:get(X, Array) ).

set( X, Y, Value, Array ) ->
	Y_array = array:get( X, Array ),
	New_y_array = array:set( Y, Value, Y_array ),
	array:set( X, New_y_array, Array ).

task() ->
	{ok, [X, Y]} = io:fread( "Input two integers.  Space delimited, please:  ", "~d ~d" ),
	Array = create( X, Y ),
	New_array = set( X - 1, Y - 1, X * Y, Array ),
	io:fwrite( "In position ~p ~p we have ~p~n", [X - 1, Y - 1, get( X - 1, Y - 1, New_array)] ).


PROGRAM DYNAMIC

!$DYNAMIC
DIM A%[0,0]

BEGIN
  PRINT(CHR$(12);) !CLS
  INPUT("Subscripts",R%,C%)
  !$DIM A%[R%,C%]
  A%[2,3]=6
  PRINT("Value in row";2;"and col";3;"is";A%[2,3])
END PROGRAM


include get.e

sequence array
integer height,width,i,j

height = floor(prompt_number("Enter height: ",{}))
width = floor(prompt_number("Enter width: ",{}))

array = repeat(repeat(0,width),height)

i = floor(height/2+0.5)
j = floor(width/2+0.5)
array[i][j] = height + width

printf(1,"array[%d][%d] is %d\n", {i,j,array[i][j]})


open System

let width = int( Console.ReadLine() )
let height = int( Console.ReadLine() )
let arr = Array2D.create width height 0
arr.[0,0] <- 42
printfn "%d" arr.[0,0]


USING: io kernel math.matrices math.parser prettyprint
sequences ;
IN: rosettacode.runtime2darray

: set-Mi,j ( elt {i,j} matrix -- )
[ first2 swap ] dip nth set-nth ;
: Mi,j ( {i,j} matrix -- elt )
[ first2 swap ] dip nth nth ;

: example ( -- )
readln readln [ string>number ] [email protected] zero-matrix ! create the array
[ [ 42 { 0 0 } ] dip set-Mi,j ] ! set the { 0 0 } element to 42
[ [ { 0 0 } ] dip Mi,j . ] ! read the { 0 0 } element
bi ;


?m;                    {imput the dimensions of the array}
?n;
Array a[m,n];          {generate an array of m rows and n columns}
a[m\2, n\2] := m+n-1;  {put some value in one of the cells}
!!a[m\2, n\2];         {display that entry}
@[a];                  {delete the array}


: 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


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


[rows, cols] = dims = eval[input["Enter dimensions: ", ["Rows", "Columns"]]]
a = new array[dims, 0]    // Create and initialize to 0
[email protected](rows-1)@(cols-1) = 10
println[[email protected](rows-1)@(cols-1)]


package main

import "fmt"

func main() {
    var row, col int
    fmt.Print("enter rows cols: ")
    fmt.Scan(&row, &col)

    // allocate composed 2d array
    a := make([][]int, row)
    for i := range a {
        a[i] = make([]int, col)
    }

    // array elements initialized to 0
    fmt.Println("a[0][0] =", a[0][0])

    // assign
    a[row-1][col-1] = 7

    // retrieve
    fmt.Printf("a[%d][%d] = %d\n", row-1, col-1, a[row-1][col-1])

    // remove only reference
    a = nil
    // memory allocated earlier with make can now be garbage collected.
}


def make2d = { nrows, ncols ->
    (0..<nrows).collect { [0]*ncols }
}


import Data.Array

doit n m = a!(0,0) where a = array ((0,0),(n,m)) [((0,0),42)]


REAL :: array(1)

DLG(NameEdit=rows, NameEdit=cols, Button='OK', TItle='Enter array dimensions')

ALLOCATE(array, cols, rows)
array(1,1) = 1.234
WRITE(Messagebox, Name) array(1,1)


procedure main(args)
    nr := integer(args[1]) | 3  # Default to 3x3
    nc := integer(args[2]) | 3

    A := list(nr)
    every !A := list(nc)

    x := ?nr    # Select a random element
    y := ?nc

    A[x][y] := &pi
    write("A[",x,"][",y,"] -> ",A[x][y])
end


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


   array1=:i. 3 4   NB. a 3 by 4 array with arbitrary values
   array2=: 5 6 $ 2 NB. a 5 by 6 array where every value is the number 2


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]);
  }
}


var width = Number(prompt("Enter width: "));
var height = Number(prompt("Enter height: "));

//make 2D array
var arr = new Array(height);

for (var i = 0; i < h; i++) {
  arr[i] = new Array(width);
}

//set value of element
a[0][0] = 'foo';
//print value of element
console.log('arr[0][0] = ' + arr[0][0]);

//cleanup array
arr = void(0);


function input(prompt::AbstractString)
    print(prompt)
    return readline()
end

n = input("Upper bound for dimension 1: ") |>
    x -> parse(Int, x)
m = input("Upper bound for dimension 2: ") |>
    x -> parse(Int, x)

x = rand(n, m)
display(x)
x[3, 3]         # overloads `getindex` generic function
x[3, 3] = 5.0   # overloads `setindex!` generic function
x::Matrix # `Matrix{T}` is an alias for `Array{T, 2}`
x = 0; gc() # Julia has no `del` command, rebind `x` and call the garbage collector


fun main(args: Array<String>) {
    // build
    val dim = arrayOf(10, 15)
    val array = Array(dim[0], { IntArray(dim[1]) } )

    // fill
    array.forEachIndexed { i, it ->
        it.indices.forEach { j ->
            it[j] = 1 + i + j
        }
    }

    // print
    array.forEach { println(it.asList()) }
}


L(directory) [‘/’, ‘./’]
   File(directory‘output.txt’, ‘w’) // create /output.txt, then ./output.txt
   fs:create_dir(directory‘docs’)   // create directory /docs, then ./docs


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


function multiply(n, a, b) if a <= b then return n, multiply(n, a + 1, b) end end

a, b = io.read() + 0, io.read() + 0
matrix = {multiply({multiply(1, 1, b)}, 1, a)}
matrix[a][b] = 5
print(matrix[a][b])
print(matrix[1][1])


Module CheckArray {
      Do {
            Input "A, B=", A% ,B%
      } Until A%>0 and B%>0

      \\ [email protected] is 1 Decimal
      addone=lambda [email protected] ->{=N : N++}
      Dim Base 1, Arr(A%,B%)<<addone()
      \\ pi also is decimal
      Arr(1,1)=pi
      Print Arr(1,1)
      Print Arr()
      \\ all variables/arrays/inner functions/modules erased now
}
CheckArray


echos > output.txt
mkdir docs

echos > \output.txt
mkdir \docs


/* ARM assembly AARCH64 Raspberry PI 3B */
/*  program createDirFic64.s   */

/*******************************************/
/* Constantes file                         */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"

.equ MKDIRAT, 0x22     // Linux Syscall  create directory
.equ CHGDIR,  0x31     // Linux Syscall  change directory

/*******************************************/
/* Initialized data                        */
/*******************************************/
.data
szMessCreateDirOk:   .asciz "Create directory Ok.\n"
szMessErrCreateDir:  .asciz "Unable create directory. \n"
szMessErrChangeDir:  .asciz "Unable change directory. \n"
szMessCreateFileOk:  .asciz "Create file Ok.\n"
szMessErrCreateFile: .asciz "Unable create file. \n"
szMessErrCloseFile:  .asciz "Unable close file. \n"

szNameDir:           .asciz "Dix1"
szNameFile:          .asciz "file1.txt"

/*******************************************/
/* UnInitialized data                      */
/*******************************************/
.bss
/*******************************************/
/*  code section                           */
/*******************************************/
.text
.global main
main:                           // entry of program
                                // create directory
    mov x0,AT_FDCWD
    ldr x1,qAdrszNameDir        // directory name
    mov x2,0775                 // mode (in octal zero is important !!)
    mov x8,MKDIRAT              // code call system create directory
    svc 0                       // call systeme
    cbnz x0,99f                 // error ?

                                // display  message ok directory
    ldr x0,qAdrszMessCreateDirOk
    bl affichageMess
                                // change directory
    ldr x0,qAdrszNameDir        // directory name
    mov x8, #CHGDIR             // code call system change directory
    svc #0                      // call systeme
    cbnz x0,98f                 // error ?
                                // create file
    mov x0,AT_FDCWD             // current directory
    ldr x1,qAdrszNameFile       // directory name
    mov x2,O_CREAT|O_WRONLY     //  flags
    mov x3,0644                 // this zone is Octal number (0 before)
    mov x8,OPEN                 // code call system open file
    svc #0                      // call systeme
    cmp x0,#0                   // error ?
    ble 97f
    mov x19,x0                  // save File Descriptor
                                // display  message ok file
    ldr x0,qAdrszMessCreateFileOk
    bl affichageMess

                                // close file
    mov x0,x19                  // Fd
    mov x8,CLOSE                // close file
    svc 0
    cbnz x0,96f                 // error ?
    mov x0,0                    // return code Ok
    b 100f                      // end Ok
96:                             // display error message close file
    ldr x0,qAdrszMessErrCloseFile
    bl affichageMess
    mov x0,1                    // return code error
    b 100f
97:                             // display error message create file
    ldr x0,qAdrszMessErrCreateFile
    bl affichageMess
    mov x0,1                    // return code error
    b 100f
98:                             // display error message change directory
    ldr x0,qAdrszMessErrChangeDir
    bl affichageMess
    mov x0,1                    // return code error
    b 100f
99:                             // display error message create directory
    ldr x0,qAdrszMessErrCreateDir
    bl affichageMess
    mov x0,1                    // return code error
    b 100f
100:                            // standard end of the program
    mov x8,EXIT                 // request to exit program
    svc 0                       // perform the system call
qAdrszMessCreateDirOk:     .quad szMessCreateDirOk
qAdrszMessErrCreateDir:    .quad szMessErrCreateDir
qAdrszMessErrChangeDir:    .quad szMessErrChangeDir
qAdrszMessCreateFileOk:    .quad szMessCreateFileOk
qAdrszNameFile:            .quad szNameFile
qAdrszMessErrCreateFile:   .quad szMessErrCreateFile
qAdrszMessErrCloseFile:    .quad szMessErrCloseFile
qAdrszNameDir:             .quad szNameDir
/********************************************************/
/*        File Include fonctions                        */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"


PROC Dir(CHAR ARRAY filter)
  CHAR ARRAY line(255)
  BYTE dev=[1]

  Close(dev)
  Open(dev,filter,6)
  DO
    InputSD(dev,line)
    PrintE(line)
    IF line(0)=0 THEN
      EXIT
    FI
  OD
  Close(dev)
RETURN

PROC CreateFile(CHAR ARRAY fname)
  BYTE dev=[1]

  Close(dev)
  Open(dev,fname,8)
  Close(dev)
RETURN

PROC Main()
  CHAR ARRAY filter="D:*.*", fname="D:OUTPUT.TXT"

  PrintF("Dir ""%S""%E",filter)
  Dir(filter)

  PrintF("Create file ""%S""%E%E",fname)
  CreateFile(fname)

  PrintF("Dir ""%S""%E",filter)
  Dir(filter)
RETURN


with Ada.Streams.Stream_IO, Ada.Directories;
use  Ada.Streams.Stream_IO, Ada.Directories;

procedure File_Creation is

   File_Handle : File_Type;

begin

   Create (File_Handle, Out_File, "output.txt");
   Close (File_Handle);
   Create_Directory("docs");
   Create (File_Handle, Out_File, "/output.txt");
   Close (File_Handle);
   Create_Directory("/docs");

end File_Creation;


> a := Array( 1 .. 3, 1 .. 4 ): # initialised to 0s
> a[1,1] := 1: # assign an element
> a[2,3] := 4: # assign an element
> a; # display the array
                           [1    0    0    0]
                           [                ]
                           [0    0    4    0]
                           [                ]
                           [0    0    0    0]

> a := 'a': # unassign the name
> gc(); # force a garbage collection; may or may not actually collect the array, but it will be eventually


arrayFun[m_Integer,n_Integer]:=Module[{array=ConstantArray[0,{m,n}]},
   array[[1,1]]=RandomReal[];
   array[[1,1]]
]


width = input('Array Width: ');
height = input('Array Height: ');

array  = zeros(width,height);

array(1,1) = 12;

disp(['Array element (1,1) = ' num2str(array(1,1))]);

clear array;  % de-allocate (remove) array from workspace


var sout = openout ("output.txt") // in current dir
sout.close()

var sout1 = openout ("/output.txt")   // in root dir
sout1.close()

mkdir ("docs")
mkdir ("/docs")


# Make a directory using the -mkdir- program
void
mkdir(text p)
{
    sshell ss;

    b_cast(ss_path(ss), "mkdir");

    l_append(ss_argv(ss), "mkdir");
    l_append(ss_argv(ss), p);

    ss_link(ss);
}

void
create_file(text p)
{
    file f;

    f_open(f, p, OPEN_CREATE | OPEN_TRUNCATE | OPEN_WRITEONLY, 00644);
}

void
create_pair(text prefix)
{
    create_file(cat(prefix, "output.txt"));
    mkdir(cat(prefix, "docs"));
}

integer
main(void)
{
    create_pair("");
    create_pair("/");

    return 0;
}


main:(

  INT errno;

  PROC touch = (STRING file name)INT:
  BEGIN
    FILE actual file;
    INT errno := open(actual file, file name, stand out channel);
    IF errno NE 0 THEN GO TO stop touch FI;
    close(actual file); # detach the book and keep it #
    errno
  EXIT
  stop touch:
      errno
  END;

  errno := touch("input.txt");
  errno := touch("/input.txt");

  # ALGOL 68 has no concept of directories,
    however a file can have multiple pages,
    the pages are identified by page number only #

  PROC mkpage = (STRING file name, INT page x)INT:
  BEGIN
    FILE actual file;
    INT errno := open(actual file, file name, stand out channel);
    IF errno NE 0 THEN GO TO stop mkpage FI;
    set(actual file,page x,1,1); # skip to page x, line 1, character 1 #
    close(actual file); # detach the new page and keep it #
    errno
  EXIT
  stop mkpage:
      errno
  END;

  errno := mkpage("input.txt",2);
)


printf(true, "in the following terminate every number with semicolon `;'")$
n: readonly("Input x-size: ")$
m: readonly("Input y-size: ")$
a: make_array(fixnum, n, m)$
fillarray(a, makelist(i, i, 1, m*n))$

/* indexing starts from 0 */
print(a[0,0]);
print(a[n-1,m-1]);


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]


ARA2D
 NEW X,Y,A,I,J
REARA
 WRITE !,"Please enter two positive integers"
 READ:10 !,"First: ",X
 READ:10 !,"Second: ",Y
 GOTO:(X\1'=X)!(X<0)!(Y\1'=Y)!(Y<0) REARA
 FOR I=1:1:X FOR J=1:1:Y SET A(I,J)=I+J
 WRITE !,"The corner of X and Y is ",A(X,Y)
 KILL X,Y,A,I,J
 QUIT


/* NetRexx */
options replace format comments java crossref symbols nobinary

say "give me the X and Y dimensions as two positive integers:"
parse ask xDim yDim
xPos = xDim % 2 -- integer divide to get close to the middle of the array
yPos = yDim % 2

arry = Rexx[xDim, yDim]
arry[xPos, yPos] = xDim / yDim -- make up a value...
say "arry["xPos","yPos"]:" arry[xPos, yPos]
return


      'output.txt' ⎕ncreate ¯1+⌊/0,⎕nnums
      '\output.txt' ⎕ncreate ¯1+⌊/0,⎕nnums
      ⎕mkdir 'Docs'
      ⎕mkdir '\Docs'


/* ARM assembly Raspberry PI  */
/*  program createDirFic.s   */

/* Constantes    */
.equ STDOUT, 1     @ Linux output console
.equ EXIT,   1     @ Linux syscall   exit Program
.equ WRITE,  4     @ Linux syscall  write FILE
.equ MKDIR, 0x27  @ Linux Syscal  create directory
.equ CHGDIR, 0xC  @ Linux Syscal  change directory
.equ CREATE, 0x8 @ Linux Syscal  create file
.equ CLOSE,   0x6  @ Linux Syscal  close file
/* Initialized data */
.data
szMessCreateDirOk: .asciz "Create directory Ok.\n"
szMessErrCreateDir: .asciz "Unable create directory. \n"
szMessErrChangeDir: .asciz "Unable change directory. \n"
szMessCreateFileOk: .asciz "Create file Ok.\n"
szMessErrCreateFile: .asciz "Unable create file. \n"
szMessErrCloseFile: .asciz "Unable close file. \n"

szNameDir: .asciz "Dir1"
szNameFile:  .asciz "file1.txt"

/* UnInitialized data */
.bss

/*  code section */
.text
.global main
main:                @ entry of program
    push {fp,lr}        @ saves registers
	@ create directory
    ldr r0,iAdrszNameDir   @ directory name
    mov r1,#0775                 @ mode (in octal zero is important !!)
    mov r7, #MKDIR             @ code call system create directory
    swi #0                      @ call systeme
    cmp r0,#0             @ error ?
    bne 99f

   @ display  message ok directory
    ldr r0,iAdrszMessCreateDirOk
    bl affichageMess
    @ change directory
    ldr r0,iAdrszNameDir   @ directory name
    mov r7, #CHGDIR             @ code call system change directory
    swi #0                      @ call systeme
    cmp r0,#0     @ error ?
    bne 98f
    @ create file
    ldr r0,iAdrszNameFile   @ directory name
    mov r1,#0755                 @ mode (in octal zero is important !!)
    mov r2,#0
    mov r7,#CREATE             @ code call system create file
    swi #0                      @ call systeme
    cmp r0,#0             @ error ?
    ble 97f
    mov r8,r0     @ save File Descriptor
    @ display  message ok file
    ldr r0,iAdrszMessCreateFileOk
    bl affichageMess

    @ close file
    mov r0,r8       @ Fd
    mov r7, #CLOSE @ close file
    swi 0
    cmp r0,#0
    bne 96f
    @ end Ok
    b 100f
96:
    @ display error message close file
    ldr r0,iAdrszMessErrCloseFile
    bl affichageMess
    b 100f
97:
    @ display error message create file
    ldr r0,iAdrszMessErrCreateFile
    bl affichageMess
    b 100f
98:
    @ display error message change directory
    ldr r0,iAdrszMessErrChangeDir
    bl affichageMess
    b 100f
99:
    @ display error message create directory
    ldr r0,iAdrszMessErrCreateDir
    bl affichageMess
    b 100f
100:   @ standard end of the program
    mov r0, #0                  @ return code
    pop {fp,lr}                 @restaur 2 registers
    mov r7, #EXIT              @ request to exit program
    swi 0                       @ perform the system call
iAdrszMessCreateDirOk:		.int szMessCreateDirOk
iAdrszMessErrCreateDir:	.int szMessErrCreateDir
iAdrszMessErrChangeDir:	.int szMessErrChangeDir
iAdrszMessCreateFileOk:	.int szMessCreateFileOk
iAdrszNameFile:				.int szNameFile
iAdrszMessErrCreateFile:	.int szMessErrCreateFile
iAdrszMessErrCloseFile:	.int szMessErrCloseFile

iAdrszNameDir:				.int szNameDir
/******************************************************************/
/*     display text with size calculation                         */
/******************************************************************/
/* r0 contains the address of the message */
affichageMess:
    push {fp,lr}    			/* save  registres */
    push {r0,r1,r2,r7}    		/* save others registers */
    mov r2,#0   				/* counter length */
1:      	/* loop length calculation */
    ldrb r1,[r0,r2]  			/* read octet start position + index */
    cmp r1,#0       			/* if 0 its over */
    addne r2,r2,#1   			/* else add 1 in the length */
    bne 1b          			/* and loop */
                                /* so here r2 contains the length of the message */
    mov r1,r0        			/* address message in r1 */
    mov r0,#STDOUT      		/* code to write to the standard output Linux */
    mov r7, #WRITE             /* code call system "write" */
    swi #0                      /* call systeme */
    pop {r0,r1,r2,r7}     		/* restaur others registers */
    pop {fp,lr}    				/* restaur des  2 registres */
    bx lr	        			/* return  */


import strutils, rdstdin

let
  w = readLineFromStdin("Width: ").parseInt()
  h = readLineFromStdin("Height: ").parseInt()

# Create the rows.
var s = newSeq[seq[int]](h)

# Create the columns.
for i in 0 ..< h:
  s[i].newSeq(w)

# Store a value in an element.
s[0][0] = 5

# Retrieve and print it.
echo s[0][0]

# The allocated memory is freed by the garbage collector.


use IO;

bundle Default {
  class TwoDee {
    function : Main(args : System.String[]) ~ Nil {
      DoIt();
    }

    function : native : DoIt() ~ Nil {
      Console->GetInstance()->Print("Enter x: ");
      x := Console->GetInstance()->ReadString()->ToInt();

      Console->GetInstance()->Print("Enter y: ");
      y := Console->GetInstance()->ReadString()->ToInt();

      if(x > 0 & y > 0) {
        array : Int[,] := Int->New[x, y];
        array[0, 0] := 2;
        array[0, 0]->PrintLine();
      };
    }
  }
}


output: "output.txt"
docs:   "docs"

write output ""
write.directory docs ø

write join.path ["/" output] ""
write.directory join.path ["/" docs] ø


FileAppend,,output.txt
FileCreateDir, docs
FileAppend,,c:\output.txt
FileCreateDir, c:\docs


BEGIN {
  printf "" > "output.txt"
  close("output.txt")
  printf "" > "/output.txt"
  close("/output.txt")
  system("mkdir docs")
  system("mkdir /docs")
}


#import <Foundation/Foundation.h>

int main()
{
  @autoreleasepool {
    int num1, num2;
    scanf("%d %d", &num1, &num2);

    NSLog(@"%d %d", num1, num2);

    NSMutableArray *arr = [NSMutableArray arrayWithCapacity: (num1*num2)];
    // initialize it with 0s
    for(int i=0; i < (num1*num2); i++) [arr addObject: @0];

    // replace 0s with something more interesting
    for(int i=0; i < num1; i++) {
      for(int j=0; j < num2; j++) {
        arr[i*num2+j] = @(i*j);
      }
    }

    // access a value: i*num2+j, where i,j are the indexes for the bidimensional array
    NSLog(@"%@", arr[1*num2+3]);
  }
  return 0;
}


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 ();;


OPEN "output.txt" FOR OUTPUT AS 1
CLOSE
OPEN "\output.txt" FOR OUTPUT AS 1
CLOSE


copy nul output.txt
copy nul \output.txt


      CLOSE #OPENOUT("output.txt")
      CLOSE #OPENOUT("\output.txt")
      *MKDIR docs
      *MKDIR \docs


global _start

: syscall ( num:eax -- result:eax ) syscall ;

: exit ( status:edi -- noret ) 60 syscall ;
: bye ( -- noret ) 0 exit ;
: die ( err:eax -- noret ) neg exit ;

: unwrap ( result:eax -- value:eax ) dup 0 cmp ' die xl ;
: ordie ( result -- ) unwrap drop ;

: open ( pathname:edi flags:esi mode:edx -- fd:eax ) 2 syscall unwrap ;
: close ( fd:edi -- ) 3 syscall ordie ;

: mkdir ( pathname:edi mode:esi -- ) 83 syscall ordie ;

00001 const for-writing
00100 const create
01000 const truncate

: create-file ( pathname -- )
	create for-writing or truncate or
	0640 open close ;

: make-directory ( pathname -- ) 0750 mkdir ;

: create-output-file ( -- ) s" output.txt" drop create-file ;
: make-docs-directory ( -- ) s" docs" drop make-directory ;

: _start ( -- noret )
	create-output-file
	make-docs-directory
	bye
;


Say "enter first dimension"
pull d1
say "enter the second dimension"
pull d2
a = .array~new(d1, d2)
a[1, 1] = "Abc"
say a[1, 1]
say d1 d2 a[d1,d2]
say a[10,10]
max=1000000000
b = .array~new(max,max)


declare
  %% Read width and height from stdin
  class TextFile from Open.file Open.text end
  StdIn = {New TextFile init(name:stdin)}
  Width = {String.toInt {StdIn getS($)}}
  Height = {String.toInt {StdIn getS($)}}
  %% create array
  Arr = {Array.new 1 Width unit}
in
  for X in 1..Width do
     Arr.X := {Array.new 1 Height 0}
  end
  %% set and read element
  Arr.1.1 := 42
  {Show Arr.1.1}


#include <stdio.h>

int main() {
  FILE *fh = fopen("output.txt", "w");
  fclose(fh);

  return 0;
}


using System;
using System.IO;

class Program {
    static void Main(string[] args) {
        File.Create("output.txt");
        File.Create(@"\output.txt");

        Directory.CreateDirectory("docs");
        Directory.CreateDirectory(@"\docs");
    }
}


#include <direct.h>
#include <fstream>

int main() {
    std::fstream f("output.txt", std::ios::out);
    f.close();
    f.open("/output.txt", std::ios::out);
    f.close();

    _mkdir("docs");
    _mkdir("/docs");

    return 0;
}


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.


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";
  }
}


FileIO text;
text.open("output.txt", FileIO.WRITE);


(import '(java.io File))
(.createNewFile (new File "output.txt"))
(.mkdir (new File "docs"))
(.createNewFile (File. (str (File/separator) "output.txt")))
(.mkdir (File. (str (File/separator) "docs")))


       identification division.
       program-id. create-a-file.

       data division.
       working-storage section.
       01 skip                 pic 9 value 2.
       01 file-name.
          05 value "/output.txt".
       01 dir-name.
          05 value "/docs".
       01 file-handle          usage binary-long.

       procedure division.
       files-main.

      *> create in current working directory
       perform create-file-and-dir

      *> create in root of file system, will fail without privilege
       move 1 to skip
       perform create-file-and-dir

       goback.

       create-file-and-dir.
      *> create file in current working dir, for read/write
       call "CBL_CREATE_FILE" using file-name(skip:) 3 0 0 file-handle
       if return-code not equal 0 then
           display "error: CBL_CREATE_FILE " file-name(skip:) ": "
                   file-handle ", " return-code upon syserr
       end-if

      *> create dir below current working dir, owner/group read/write
       call "CBL_CREATE_DIR" using dir-name(skip:)
       if return-code not equal 0 then
           display "error: CBL_CREATE_DIR " dir-name(skip:) ": "
                   return-code upon syserr
       end-if
       .

       end program create-a-file.


-- demo\rosetta\Create2Darray.exw
with javascript_semantics -- (layout/spacing leaves a little to be desired...)
include pGUI.e
Ihandle lab, tab, res, dlg

function valuechanged_cb(Ihandle tab)
    string s = IupGetAttribute(tab,"VALUE")
    sequence r = scanf(s,"%d %d")
    if length(r)=1 then
        integer {height,width} = r[1],
                i = floor(height/2+0.5),
                j = floor(width/2+0.5)
        if i>0 and j>0 then

            sequence array = repeat(repeat(0,width),height)

            array[i][j] = height + width

            s = sprintf("array[%d][%d] is %d\n", {i,j,array[i][j]})

            IupSetStrAttribute(res,"TITLE",s)
            IupRefresh(res)
        end if
    end if
    return IUP_DEFAULT
end function

procedure main()
    IupOpen()
    lab = IupLabel("Enter two numbers (>0) separated by a space")
    tab = IupText("VALUECHANGED_CB", Icallback("valuechanged_cb"),"EXPAND=HORIZONTAL")
    res = IupLabel("")
    dlg = IupDialog(IupVbox({IupHbox({lab,tab},"GAP=10,NORMALIZESIZE=VERTICAL"),
                             IupHbox({res})},"MARGIN=5x5"),`TITLE="Create 2D array"`)
    IupShow(dlg)
    if platform()!=JS then
        IupMainLoop()
        IupClose()
    end if
end procedure

main()


include ..\Utilitys.pmt

"Enter height: " input tonum nl
"Enter width: " input tonum nl
0 swap repeat swap repeat       /# create two dimensional array/list. All zeroes #/
-1 get 99 -1 set -1 set         /# set the last element o last dimension #/
pstack                          /# show the content of the stack #/
-1 get -1 get "Value of the last element of the last dimension: " print print drop
drop                            /# remove array/list from the stack #/


(let ((stream (open "output.txt" :direction :output)))
  (close stream))


MODULE CreateFile;
IMPORT Files, StdLog;

PROCEDURE Do*;
VAR
	f: Files.File;
	res: INTEGER;
BEGIN
	f := Files.dir.New(Files.dir.This("docs"),Files.dontAsk);
	f.Register("output","txt",TRUE,res);
	f.Close();

	f := Files.dir.New(Files.dir.This("C:\AEAT\docs"),Files.dontAsk);
	f.Register("output","txt",TRUE,res);
	f.Close()
END Do;

END CreateFile.


File.write "output.txt", ""
Dir.mkdir "docs"

File.write "/output.txt", ""
Dir.mkdir "/docs"


module fileio ;
import std.stdio ;
import std.path ;
import std.file ;
import std.stream ;

string[] genName(string name){
  string cwd  = curdir ~ sep ; // on current directory
  string root = sep ;          // on root
  name = std.path.getBaseName(name) ;
  return [cwd ~ name, root ~ name] ;
}
void Remove(string target){
  if(exists(target)){
    if (isfile(target))
      std.file.remove(target);
    else
      std.file.rmdir(target) ;
  }
}
void testCreate(string filename, string dirname){
  // files:
  foreach(fn ; genName(filename))
    try{
      writefln("file to be created : %s", fn) ;
      std.file.write(fn, cast(void[])null) ;
      writefln("\tsuccess by std.file.write") ; Remove(fn) ;
      (new std.stream.File(fn, FileMode.OutNew)).close() ;
      writefln("\tsuccess by std.stream") ; Remove(fn) ;
    } catch(Exception e) {
      writefln(e.msg) ;
    }
  // dirs:
  foreach(dn ; genName(dirname))
    try{
      writefln("dir to be created : %s", dn) ;
      std.file.mkdir(dn) ;
      writefln("\tsuccess by std.file.mkdir") ; Remove(dn) ;
    } catch(Exception e) {
      writefln(e.msg) ;
    }
}
void main(){
  writefln("== test: File & Dir Creation ==") ;
  testCreate("output.txt", "docs") ;
}


import util.

go =>
  print("Input the number of rows and columns: "),
  [Rows,Cols]=split(read_line()).map(to_int),
  X=new_array(Rows,Cols),
  X[1,1] = Rows*Cols+1,
  println(X[1,1]).


(de 2dimTest (DX DY)
   (let A (make (do DX (link (need DY))))
      (set (nth A 3 3) 999)            # Set A[3][3] to 999
      (mapc println A)                 # Print all
      (get A 3 3) ) )                  # Return A[3][3]

(2dimTest 5 5)


/* First way using a controlled variable: */

declare A(*,*) float controlled;
get list (m, n);
allocate A(m,n);
get list (A);
put skip list (A);

/* The array remains allocated until the program terminates, */
/* or until explicitly destroyed using a FREE statement.     */

free A;


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;


! for d in . / ;do > "$d/output.txt" ; mkdir "$d/docs" ;done


open/write output_file output.txt
open/write output_file [000000]output.txt
create/directory [.docs]
create/directory [000000.docs]


program createFile;

{$APPTYPE CONSOLE}

uses
  Classes,
  SysUtils;

const
  filename = 'output.txt';

var
  cwdPath,
  fsPath: string;

// Create empty file in current working directory
function CreateEmptyFile1: Boolean;
var
  f: textfile;
begin
  // Make path to the file to be created
  cwdPath := ExtractFilePath(ParamStr(0)) + '1_'+filename;

  // Create file
  AssignFile(f,cwdPath);
  {$I-}
  Rewrite(f);
  {$I+}
  Result := IOResult = 0;
  CloseFile(f);
end;

// Create empty file in filesystem root
function CreateEmptyFile2: Boolean;
var
  f: textfile;
begin
  // Make path to the file to be created
  fsPath := ExtractFileDrive(ParamStr(0)) + '\' + '2_'+filename;

  // Create file
  AssignFile(f,fsPath);
  {$I-}
  Rewrite(f);
  {$I+}
  Result := IOResult = 0;
  CloseFile(f);
end;

function CreateEmptyFile3: Boolean;
var
  fs: TFileStream;
begin
  // Make path to the file to be created
  cwdPath := ExtractFilePath(ParamStr(0)) + '3_'+filename;

  // Create file
  fs := TFileStream.Create(cwdPath,fmCreate);
  fs.Free;
  Result := FileExists(cwdPath);
end;

function CreateEmptyFile4: Boolean;
var
  fs: TFileStream;
begin
  // Make path to the file to be created
  fsPath := ExtractFileDrive(ParamStr(0)) + '\' + '4_'+filename;

  // Create file
  fs := TFileStream.Create(fsPath,fmCreate);
  fs.Free;
  Result := FileExists(fsPath);
end;

begin
  if CreateEmptyFile1 then
    Writeln('File created at '+cwdPath)
    else
    Writeln('Error creating file at '+cwdPath);

  if CreateEmptyFile2 then
    Writeln('File created at '+fsPath)
    else
    Writeln('Error creating file at '+fsPath);

  if CreateEmptyFile3 then
    Writeln('File created at '+cwdPath)
    else
    Writeln('Error creating file at '+cwdPath);

  if CreateEmptyFile4 then
    Writeln('File created at '+fsPath)
    else
    Writeln('Error creating file at '+fsPath);

  // Keep console window open
  Readln;
end.


function Read-ArrayIndex ([string]$Prompt = "Enter an integer greater than zero")
{
    [int]$inputAsInteger = 0

    while (-not [Int]::TryParse(([string]$inputString = Read-Host $Prompt), [ref]$inputAsInteger))
    {
        $inputString = Read-Host "Enter an integer greater than zero"
    }

    if ($inputAsInteger -gt 0) {return $inputAsInteger} else {return 1}
}

$x = $y = $null

do
{
    if ($x -eq $null) {$x = Read-ArrayIndex -Prompt "Enter two dimensional array index X"}
    if ($y -eq $null) {$y = Read-ArrayIndex -Prompt "Enter two dimensional array index Y"}
}
until (($x -ne $null) -and ($y -ne $null))

$array2d = New-Object -TypeName 'System.Object[,]' -ArgumentList $x, $y


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


<file:output.txt>.setBytes([])
<file:docs>.mkdir(null)
<file:///output.txt>.setBytes([])
<file:///docs>.mkdir(null)


;; The file system is the browser local storage
;; It is divided into named stores (directories)
;; "user" is the default (home) store

; before : list of stores
(local-stores) → ("system" "user" "words" "reader" "info" "root")

(local-put-value "output.txt" "") → "output.txt" ; into "user"
(local-make-store "user/docs") → "user/docs"
(local-put-value "output.txt" "" "root") → "output.txt" ; into "root"
(local-make-store 'root/docs) → "root/docs"

; after : list of stores
(local-stores 'root) → ("root" "root/docs")
(local-stores 'user) → ("user" "user/docs")


import system'io;

public program()
{
    File.assign("output.txt").textwriter().close();

    File.assign("\output.txt").textwriter().close();

    Directory.assign("docs").create();

    Directory.assign("\docs").create();
}


File.open("output.txt", [:write])
File.open("/output.txt", [:write])

File.mkdir!("docs")
File.mkdir!("/docs")


  [ witheach peek ]         is {peek}        (   { p --> x     )

  [ dip dup
      witheach [ peek dup ]
    drop ]                  is depack        (   { p --> *     )

  [ reverse
    witheach
      [ dip swap poke ] ]   is repack        (   * p --> {     )

  [ dup dip
      [ rot dip
        [ depack drop ] ]
    repack ]                is {poke}        ( x { p --> {     )

  [ 0 swap of
    nested swap of ]        is  2array       (   n n --> [     )

  $ "Array width  (at least 2): " input $->n drop
  $ "Array length (at least 5): " input $->n drop

  say "Creating " over echo say " by "
  dup echo say " array." cr

  2array

  say "Writing 12345 to element {1,4} of array." cr

  12345 swap ' [ 1 4 ] {poke}

  say "Reading element {1,4} of array: "

  ' [ 1 4 ] {peek} echo


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 racket

(printf "Enter XY dimensions: ")
(define xy (cons (read) (read)))
(define array (for/vector ([x (car xy)]) (for/vector ([y (cdr xy)]) 0)))

(printf "Enter a number for the top-left: ")
(vector-set! (vector-ref array 0) 0 (read))
(printf "Enter a number for the bottom-right: ")
(vector-set! (vector-ref array (sub1 (car xy))) (sub1 (cdr xy)) (read))

array


my ($major,$minor) = prompt("Dimensions? ").comb(/\d+/);
my @array = [ '@' xx $minor ] xx $major;
@array[ *.rand ][ *.rand ] = ' ';
.say for @array;


(make-empty-file "output.txt")
(make-directory "docs")
(make-empty-file "/output.txt")
(make-directory "/docs")


-module(new_file).
-export([main/0]).

main() ->
	ok = file:write_file( "output.txt", <<>> ),
	ok = file:make_dir( "docs" ),
	ok = file:write_file( filename:join(["/", "output.txt"]), <<>> ),
	ok = file:make_dir( filename:join(["/", "docs"]) ).


PROGRAM FILE_TEST

!$INCLUDE="PC.LIB"

BEGIN

    OPEN("O",#1,"output.txt")
    CLOSE(1)

    OS_MKDIR("C:\RC")   ! with the appropriate access rights .......
    OPEN("O",#1,"C:\RC\output.txt")
    CLOSE(1)

END PROGRAM


Red ["Create two-dimensional array at runtime"]

width: to-integer ask "What is the width of the array? "
height: to-integer ask "What is the height of the array? "

                                      ; 2D arrays are just nested blocks in Red.
matrix: copy []                       ; Make an empty block to hold our rows.
loop height [                         ; A loop for each row...
    row: append/dup copy [] 0 width   ; Create a block like [0 0 0 0] if width is 4.
    append/only matrix row            ; Append the row to our matrix as its own block.
]

a: 3
b: 2
matrix/2/4: 27      ; use path syntax to access or assign
matrix/1/1: 99      ; series are 1-indexed in Red; there is no matrix/0/0
matrix/(a)/(a): 10  ; accessing elements with words requires special care
matrix/:b/:b: 33    ; alternative
print mold matrix


/*REXX program  allocates/populates/displays  a two-dimensional array.  */
call bloat                   /*the BLOAT procedure does all allocations.*/
                             /*no more array named   @   at this point. */
exit                         /*stick a fork in it, we're all done honey.*/
/*─────────────────────────BLOAT subroutine─────────────────────────────*/
bloat: procedure;  say       /*"PROCEDURE"  makes this a ··· procedure. */
say 'Enter two positive integers (a 2-dimensional array will be created).'
pull n m .                   /*elements are allocated as they're defined*/
                             /*N and M should be verified at this point.*/
@.=' · '                     /*Initial value for all  @  array elements,*/
                             /*this ensures  every  element has a value.*/
  do j    =1  for n          /*traipse through the first  dimension  [N]*/
      do k=1  for m          /*   "       "     "  second     "      [M]*/
      if random()//7==0  then @.j.k=j'~'k    /*populate every 7th random*/
      end  /*k*/
  end        /*j*/
                             /* [↓]  display array to console:  row,col */
  do r=1  for n;    _=       /*construct one row (or line) at a time.   */
      do c=1  for m          /*construct row one column at a time.      */
      _=_ right(@.r.c,4)     /*append a nice-aligned column to the line.*/
      end   /*kk*/           /* [↑]   an nicely aligned line is built.  */
  say _                      /*display one row at a time to the terminal*/
  end         /*jj*/
/*╔════════════════════════════════════════════════════════════════════╗
  ║ When the  RETURN  is executed (from a PROCEDURE in this case), and ║
  ║ array   @  is "de─allocated", that is, it's no longer defined, and ║
  ║ the array's storage is now free for other REXX variables.   If the ║
  ║ BLOAT   subroutine didn't have a   "PROCEDURE"   on that statement,║
  ║ the array    @    would've been left intact.    The same effect is ║
  ║ performed by a   DROP   statement   (an example is shown below).   ║
  ╚════════════════════════════════════════════════════════════════════╝*/
drop @.                      /*because of the  PROCEDURE  statement, the*/
return                       /* [↑]    DROP   statement is superfluous. */


integer fn

-- In the current working directory
system("mkdir docs",2)
fn = open("output.txt","w")
close(fn)

-- In the filesystem root
system("mkdir \\docs",2)
fn = open("\\output.txt","w")
close(fn)


open System.IO

[<EntryPoint>]
let main argv =
    let fileName = "output.txt"
    let dirName = "docs"
    for path in ["."; "/"] do
        ignore (File.Create(Path.Combine(path, fileName)))
        ignore (Directory.CreateDirectory(Path.Combine(path, dirName)))
    0


USE: io.directories

"output.txt" "/output.txt" [ touch-file ] [email protected]
"docs" "/docs" [ make-directory ] [email protected]


["/", "./"] each: |dir| {
  # create '/docs', then './docs'
  Directory create: (dir ++ "docs")
  # create files /output.txt, then ./output.txt
  File open: (dir ++ "output.txt") modes: ['write] with: |f| {
    f writeln: "hello, world!"
  }
}


 s" output.txt" w/o create-file throw ( fileid) drop
s" /output.txt" w/o create-file throw ( fileid) drop


See 'Enter width : ' give width
See 'Enter height : ' give height
width=0+width   height=0+height
aList = list(height) for x in aList  x = list(width) next
aList[1][2] = 10  See aList[1][2] + nl


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]


use std::env;

fn main() {
    let mut args = env::args().skip(1).flat_map(|num| num.parse());
    let rows = args.next().expect("Expected number of rows as first argument");
    let cols = args.next().expect("Expected number of columns as second argument");

    assert_ne!(rows, 0, "rows were zero");
    assert_ne!(cols, 0, "cols were zero");

    // Creates a vector of vectors with all elements initialized to 0.
    let mut v = vec![vec![0; cols]; rows];
    v[0][0] = 1;
    println!("{}", v[0][0]);
}


object Array2D{
   def main(args: Array[String]): Unit = {
      val x = Console.readInt
      val y = Console.readInt

      val a=Array.fill(x, y)(0)
      a(0)(0)=42
      println("The number at (0, 0) is "+a(0)(0))
   }
}


PROGRAM CREATION
OPEN (UNIT=5, FILE="output.txt", STATUS="NEW")   ! Current directory
CLOSE (UNIT=5)
OPEN (UNIT=5, FILE="/output.txt", STATUS="NEW")  ! Root directory
CLOSE (UNIT=5)

!Directories (Use System from GNU Fortran Compiler)
! -- Added by Anant Dixit, November 2014
call system("mkdir docs/")
call system("mkdir ~/docs/")

END PROGRAM


' FB 1.05.0 Win64

' create empty file and sub-directory in current directory
Open "output.txt" For Output As #1
Close #1
MkDir "docs"

' create empty file and sub-directory in root directory c:\
' creating file in root requires administrative privileges in Windows 10
Open "c:\output.txt" For Output As #1
Close #1
MkDir "c:\docs"

Print "Press any key to quit"
Sleep


touch {/,}output.txt    # create both /output.txt and output.txt
mkdir {/,}docs          # create both /docs and docs


import io.File

File( 'output.txt' ).createNewFile()
File( File.separator + 'output.txt' ).createNewFile()
File( 'docs' ).mkdir()
File( File.separator + 'docs' ).mkdir()


(import (scheme base)
        (scheme read)
        (scheme write))

;; Read x/y from user
(define x (begin (display "X: ") (flush-output-port) (read)))
(define y (begin (display "Y: ") (flush-output-port) (read)))

;; Create a vector, and fill it with a vector for each row
(define arr (make-vector x))
(do ((i 0 (+ 1 i)))
  ((= i x) )
  (vector-set! arr i (make-vector y 0)))

;; set element (x/2, y/2) to 3
(vector-set! (vector-ref arr (floor (/ x 2)))
             (floor (/ y 2))
             3)

(display arr) (newline)
(display "Retrieved: ")
(display (vector-ref (vector-ref arr (floor (/ x 2)))
                     (floor (/ y 2))))
(newline)


$ include "seed7_05.s7i";

const proc: main is func
  local
    var integer: numRows is 0;
    var integer: numCols is 0;
    var array array integer: anArray is 0 times 0 times 0;
  begin
    write("Give me the numer of rows: ");
    readln(numRows);
    write("Give me the numer of columns: ");
    readln(numCols);
    anArray := numRows times numCols times 0;
    anArray[1][1] := 3;
    writeln("The number at place [1, 1] is " <& anArray[1][1]);
  end func;


Public Sub Main()
Dim byCount As Byte
Dim sToSave As String

For byCount = 0 To 50
  sToSave &= Format(Str(byCount), "00") & " - Charlie was here!" & gb.NewLine
Next

File.Save(User.Home &/ "TestFile", sToSave)
Print File.Load(User.Home &/ "TestFile")

End


package main

import (
    "fmt"
    "os"
)

func createFile(fn string) {
    f, err := os.Create(fn)
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Println("file", fn, "created!")
    f.Close()
}

func createDir(dn string) {
    err := os.Mkdir(dn, 0666)
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Println("directory", dn, "created!")
}

func main() {
    createFile("input.txt")
    createFile("/input.txt")
    createDir("docs")
    createDir("/docs")
}


new File("output.txt").createNewFile()
new File(File.separator + "output.txt").createNewFile()
new File("docs").mkdir()
new File(File.separator + "docs").mkdir()


func make_matrix(x, y) {
    y.of { x.of(0) };
}

var y = Sys.scanln("rows: ").to_i;
var x = Sys.scanln("cols: ").to_i;

var matrix = make_matrix(x, y);   # create the matrix
matrix[y/2][x/2] = 1;             # write something inside it
say matrix;                       # display the matrix


BEGIN
    INTEGER N,M;
    M := ININT;
    N := ININT;
    BEGIN
        INTEGER ARRAY A(1:M,1:N);
        A(M,N) := 99;
        OUTINT(A(M,N),0);
        OUTIMAGE;
    END;
    ! ARRAY A OUT OF SCOPE ;
END.


m := (FillInTheBlankMorph request: 'Number of rows?') asNumber.
n := (FillInTheBlankMorph request: 'Number of columns?') asNumber.
aMatrix := Matrix rows: m columns: n.
aMatrix
	at: (aMatrix rowCount // 2)
	at: (aMatrix columnCount // 2)
	put: 3.4.
e := aMatrix
	at: (aMatrix rowCount // 2)
	at: (aMatrix columnCount // 2).
Transcript show: 'Entry is', e printString.


import System.Directory

createFile name = writeFile name ""

main = do
  createFile "output.txt"
  createDirectory "docs"
  createFile "/output.txt"
  createDirectory "/docs"


SYSTEM(DIR="\docs")              ! create argument if not existent, make it current
OPEN(FILE="output.txt", "NEW")   ! in current directory

SYSTEM(DIR="C:\docs")            ! create C:\docs if not existent, make it current
OPEN(FILE="output.txt", "NEW")   ! in C:\docs


software {
	create("output.txt")
	create("docs/")
	create("/output.txt")
	create("/docs/")
}


every dir := !["./","/"] do {
   close(open(f := dir || "input.txt","w"))  |stop("failure for open ",f)
   mkdir(f := dir || "docs")                 |stop("failure for mkdir ",f)
   }


*       # Get user X,Y dimensions
        output = 'Enter X,Y:'; xy = trim(input)
        xy break(',') . x ',' rem . y

*       # Define and create array, 1-based
        arr = array(x ',' y) ;* Or arr = array(xy)

*       # Display array prototype
        output = 'Prototype: ' prototype(arr)

*       # Assign elements, angle or square brackets
*       # Same array can hold ints, strings, etc.
        arr<x,y> = 99; arr[1,1] = 'dog'

*       # Display elements
        output = 'arr[' xy '] = ' arr[x,y]
        output = 'arr[1,1] = ' arr[1,1]

*       # Release array for garbage collection
        arr =
end


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");


display "Number of rows?" _request(nr)
display "Number of columns?" _request(nc)
matrix define a=J($nr,$nc,0)
matrix a[1,2]=1.5
matrix list a
matrix drop a


import Foundation

print("Enter the dimensions of the array seperated by a space (width height): ")

let fileHandle = NSFileHandle.fileHandleWithStandardInput()
let dims = NSString(data: fileHandle.availableData, encoding: NSUTF8StringEncoding)?.componentsSeparatedByString(" ")

if let dims = dims where dims.count == 2{
	let w = dims[0].integerValue
	let h = dims[1].integerValue

	if let w = w, h = h where w > 0 && h > 0 {
		var array = Array<[Int!]>(count: h, repeatedValue: Array<Int!>(count: w, repeatedValue: nil))

		array[0][0] = 2
		println(array[0][0])
		println(array)
	}
}


puts "Enter width:"
set width [gets stdin]
puts "Enter height:"
set height [gets stdin]
# Initialize array
for {set i 0} {$i < $width} {incr i} {
	for {set j 0} {$j < $height} {incr j} {
		set arr($i,$j) ""
	}
}
# Store value
set arr(0,0) "abc"
# Print value
puts "Element (0/0): $arr(0,0)"
# Cleanup array
unset arr


'' 1!:2 <'/output.txt'   NB. write an empty file
   1!:5 <'/docs'         NB. create a directory


import java.io.*;
public class CreateFileTest {
	public static void main(String args[]) {
		try {
			new File("output.txt").createNewFile();
			new File(File.separator + "output.txt").createNewFile();
			new File("docs").mkdir();
			new File(File.separator + "docs").mkdir();
		} catch (IOException e) {
			System.err.println(e.getMessage());
		}
	}
}


const fs = require('fs');

function fct(err) {
  if (err) console.log(err);
}

fs.writeFile("output.txt", "", fct);
fs.writeFile("/output.txt", "", fct);

fs.mkdir("docs", fct);
fs.mkdir("/docs", fct);


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


decl int width height
out "width:  " console
set width (in int console)
out "height: " console
set height (in int console)

decl int<><> twodstream
for (decl int i) (< i height) (inc i)
        append (new int<>) twodstream
end for
for (set i 0) (< i height) (inc i)
        decl int j
        for (set j 0) (< j width) (inc j)
                append 0 twodstream<i>
        end for
end for

set twodstream<0><0> 5
out twodstream<0><0> endl console


Option Explicit

Sub Main_Create_Array()
Dim NbColumns As Integer, NbRows As Integer

    'Get two integers from the user,
    Do
        NbColumns = Application.InputBox("Enter number of columns : ", "Numeric only", 3, Type:=1)
        NbRows = Application.InputBox("Enter number of rows : ", "Numeric only", 5, Type:=1)
    Loop While NbColumns = 0 Or NbRows = 0
    'Create a two-dimensional array at runtime
    ReDim myArray(1 To NbRows, 1 To NbColumns)
    'Write some element of that array,
    myArray(LBound(myArray, 1), UBound(myArray, 2)) = "Toto"
    'and then output that element.
    MsgBox myArray(LBound(myArray, 1), UBound(myArray, 2))
    'destroy the array
    Erase myArray
End Sub


" Create a two-dimensional array with r rows and c columns.
" The optional third argument specifies the initial value
" (default is 0).
function MakeArray(r, c, ...)
    if a:0
        let init = a:1
    else
        let init = 0
    endif

    let temp = []
    for c in range(a:c)
        call add(temp, init)
    endfor

    let array = []
    for r in range(a:r)
        call add(array, temp[:])
    endfor
    return array
endfunction

let rows = input("Enter number of rows: ")
let cols = input("Enter number of columns: ")
echo "\n"
let array = MakeArray(rows, cols)
let array[rows - 1][cols - 1] = rows * cols
echo array[rows - 1][cols - 1]
unlet array


// EXEC PGM=IEFBR14
//* CREATE EMPTY FILE NAMED "OUTPUT.TXT" (file names upper case only)
//ANYNAME DD UNIT=SYSDA,SPACE=(0,0),DSN=OUTPUT.TXT,DISP=(,CATLG)
//* CREATE DIRECTORY (PARTITIONED DATA SET) NAMED "DOCS"
//ANYNAME DD UNIT=SYSDA,SPACE=(TRK,(1,1)),DSN=DOCS,DISP=(,CATLG)


# many I/O functions have UNIX names

touch("output.txt")
mkdir("docs")

# probably don't have permission
try
    touch("/output.txt")
    mkdir("/docs")
catch e
    warn(e)
end


   "output.txt" 1: ""
   "/output.txt" 1: ""
   \ mkdir docs
   \ mkdir /docs


/* testing on Windows 10 which needs administrative privileges
   to create files in the root */

import java.io.File

fun main(args: Array<String>) {
    val filePaths = arrayOf("output.txt", "c:\\output.txt")
    val dirPaths  = arrayOf("docs", "c:\\docs")
    var f: File
    for (path in filePaths) {
        f = File(path)
        if (f.createNewFile())
            println("$path successfully created")
        else
            println("$path already exists")
    }
    for (path in dirPaths) {
        f = File(path)
        if (f.mkdir())
            println("$path successfully created")
        else
            println("$path already exists")
    }
}


import "io" for Stdin, Stdout

var x
var y
System.print("Enter the dimensions of the array:")
while (true) {
    System.write("  First dimension  : ")
    Stdout.flush()
    x = Num.fromString(Stdin.readLine())
    if (x && (x is Num) && (x.isInteger) && (x > 0) ) {
        System.write("  Second dimension : ")
        Stdout.flush()
        y = Num.fromString(Stdin.readLine())
        if (y && (y is Num) && (y.isInteger) && (y > 0) ) break
        System.print("Dimension must be a positive integer.")
    } else {
        System.print("Dimension must be a positive integer.")
    }
}
// create the 2d array
var a = List.filled(x, null)
for (i in 0...x) a[i] = List.filled(y, 0)
// write an element
a[x - 1][y - 1] = 42
// print it
System.print("\na[%(x-1)][%(y-1)] = %(a[x-1][y-1])")
// make the array eligible for garbage collection
a = null


inc     c:\cxpl\codes;  \(command words can be abbreviated to first 3 letters)
def     IntSize=4;      \number of bytes in an integer (2 or 4 depending on version)
int     X, Y, A, I;
[X:= IntIn(0);  Y:= IntIn(0);           \get 2 dimensions from user
A:= Reserve(X*IntSize);
for I:= 0 to X-1 do A(I):= Reserve(Y*IntSize);
A(X/2, Y/2):= X+Y;
IntOut(0, A(X/2, Y/2));  CrLf(0);
]


// create file
local(f) = file
handle => { #f->close }
#f->openWriteOnly('output.txt')

// make directory, just like a file
local(d = dir('docs'))
#d->create

// create file in root file system (requires permissions at user OS level)
local(f) = file
handle => { #f->close }
#f->openWriteOnly('//output.txt')

// create directory in root file system (requires permissions at user OS level)
local(d = dir('//docs'))
#d->create


(: file write_file '"output.txt" '"Some data")
(: file make_dir '"docs")
(: file write_file '"/output.txt" '"Some data")
(: file make_dir '"/docs")


nomainwin

open "output.txt" for output as #f
close #f

result = mkdir( "F:\RC")
if result <>0 then notice "Directory not created!": end

open "F:\RC\output.txt" for output as #f
close #f

end


-- note: fileIO xtra is shipped with Director, i.e. an "internal"
fp = xtra("fileIO").new()
fp.createFile("output.txt")


rows:=ask("Rows: ").toInt();
cols:=ask("columns: ").toInt();
array:=rows.pump(List.createLong(rows),List.createLong(cols,0).copy);
array[1][2]=123;
array.println();
array[1][2].println();


module Main;
type
	Matrix = array *,* of integer;

var
	m: Matrix;
	i,j: integer;
begin
	write("first dim? ");readln(i);
	write("second dim? ");readln(j);
	m := new Matrix(i,j);
	m[0,0] := 10;
	writeln("m[0,0]:> ",m[0,0]);
	writeln("m[0,1].> ",m[0,1])
end Main.


void create_file(string path) {
    FILE f;
    unless (exists(path)) {
        unless (f = fopen(path, "w")){
            die(path);
        } else {
            puts("file ${path} created");
            fclose(f);
        }
    } else {
        puts("File ${path} already exists");
    }
}

void create_dir(string path) {
    unless (exists(path)) {
        unless(mkdir(path)) { //mkdir returns 0 on success, -1 on error
            puts("directory ${path} created");
        } else {
            puts(stderr, "Error: directory ${path} not created");
        }
    } else {
        puts("directory ${path} already exists");
    }
}

create_file("output.txt");
create_file("/tmp/output.txt");
create_dir("docs");
create_dir("/tmp/docs");


io.open("output.txt", "w"):close()
io.open("\\output.txt", "w"):close()


Module MakeDirAndFile {
      Def WorkingDir$, RootDir$
      If Drive$(Dir$)="Drive Fixed" Then WorkingDir$=Dir$
      If Drive$("C:\")="Drive Fixed" Then RootDir$="C:\"

      if WorkingDir$<>"" Then task(WorkingDir$)
      If RootDir$<>"" then task(RootDir$)
      Dir User ' return to user directory

      Sub task(WorkingDir$)
            Dir WorkingDir$
            If Not Exist.Dir("docs") then SubDir "docs" : Dir WorkingDir$
            If Exist.Dir("docs") Then Print str$(File.Stamp("docs"), "YYYY|MM|DD|hh:nn:ss")
            Open "output.txt" For Output as #F
            Close #f
            If Exist("output.txt") Then Print str$(File.Stamp("output.txt"), "YYYY|MM|DD|hh:nn:ss")
      End Sub
}
MakeDirAndFile


FileTools:-Text:-WriteFile("output.txt", "");  # make empty file in current dir
FileTools:-MakeDirectory("docs");               # make empty dir in current dir
FileTools:-Text:-WriteFile("/output.txt", ""); # make empty file in root dir
FileTools:-MakeDirectory("/docs");              # make empty dir in root dir


[email protected]ectory[];
t = OpenWrite["output.txt"]
Close[t]
s = OpenWrite[[email protected][$InstallationDirectory] <> "\\output.txt"]
Close[s]

(*In root directory*)
CreateDirectory["\\docs"]
(*In current operating directory*)
CreateDirectory[Directory[]<>"\\docs"]
(*"left<>right" is shorthand for "StringJoin[left,right]"*)


	fid = fopen('output.txt','w'); fclose(fid);
	fid = fopen('/output.txt','w'); fclose(fid);
	mkdir('docs');
	mkdir('/docs');


f: openw("/output.txt");
close(f);

f: openw("output.txt");
close(f);

/* Maxima has no function to create directories, but one can use the underlying Lisp system */

:lisp (mapcar #'ensure-directories-exist '("docs/" "/docs/"))


-- Here
f = createFile "output.txt"
close f
makeDir (sysInfo.currentDir + "\docs")
-- System root
f = createFile "\output.txt"
close f
makeDir ("c:\docs")


:- module create_file.
:- interface.

:- import_module io.
:- pred main(io::di, io::uo) is det.

:- implementation.

:- import_module dir.

main(!IO) :-
    create_file("output.txt", !IO),
    create_file("/output.txt", !IO),
    create_dir("docs", !IO),
    create_dir("/docs", !IO).

:- pred create_file(string::in, io::di, io::uo) is det.

create_file(FileName, !IO) :-
    io.open_output(FileName, Result, !IO),
    (
        Result = ok(File),
        io.close_output(File, !IO)
    ;
        Result = error(Error),
        print_io_error(Error, !IO)
    ).

:- pred create_dir(string::in, io::di, io::uo) is det.

create_dir(DirName, !IO) :-
    dir.make_single_directory(DirName, Result, !IO),
    (
        Result = ok
    ;
        Result = error(Error),
        print_io_error(Error, !IO)
    ).

:- pred print_io_error(io.error::in, io::di, io::uo) is det.

print_io_error(Error, !IO) :-
   io.stderr_stream(Stderr, !IO),
   io.write_string(Stderr, io.error_message(Error), !IO),
   io.nl(Stderr, !IO),
   io.set_exit_status(1, !IO).


import java.io.File

File.new('output.txt').createNewFile()
File.new('docs').mkdir()
File.new("docs#{File.separator}output.txt").createNewFile()


MODULE FileCreation EXPORTS Main;

IMPORT FS, File, OSError, IO, Stdio;

VAR file: File.T;

BEGIN
  TRY
    file := FS.OpenFile("output.txt");
    file.close();
    FS.CreateDirectory("docs");
    file := FS.OpenFile("/output.txt");
    file.close();
    FS.CreateDirectory("/docs");
  EXCEPT
  | OSError.E => IO.Put("Error creating file or directory.\n", Stdio.stderr);
  END;
END FileCreation.


import Nanoquery.IO

f = new(File)
f.create("output.txt")
f.createDir("docs")

// in the root directory
f.create("/output.txt")
f.createDir("/docs")


using System;
using System.IO;

module CreateFile
{
    Main() : void
    {
        unless (File.Exists("output.txt")) File.Create("output.txt");         // here
        // returns a FileStream object which we're ignoring
        try {
            unless (File.Exists(@"\output.txt")) File.Create(@"\output.txt"); // root
        }
        catch {
            |e is UnauthorizedAccessException => Console.WriteLine(
            "Cannot create file in root directory without Administrator priveleges.")
        }

        unless (Directory.Exists("docs")) Directory.CreateDirectory("docs");
        // returns a DirectoryInfo object which we're ignoring
        unless (Directory.Exists(@"\docs")) Directory.CreateDirectory(@"\docs");
        // no Exception for directory creation
    }
}


/* NetRexx */
options replace format comments java crossref symbols nobinary

fName = ''; fName[0] = 2; fName[1] = '.' || File.separator || 'output.txt'; fName[2] = File.separator || 'output.txt'
dName = ''; dName[0] = 2; dName[1] = '.' || File.separator || 'docs';       dName[2] = File.separator || 'docs'

do
  loop i_ = 1 to fName[0]
    say fName[i_]
    fc = File(fName[i_]).createNewFile()
    if fc then  say 'File' fName[i_] 'created successfully.'
    else        say 'File' fName[i_] 'aleady exists.'
    end i_

  loop i_ = 1 to dName[0]
    say dName[i_]
    dc = File(dName[i_]).mkdir()
    if dc then  say 'Directory' dName[i_] 'created successfully.'
    else        say 'Directory' dName[i_] 'aleady exists.'
    end i_
catch iox = IOException
  iox.printStackTrace
end

return


import os

open("output.txt", fmWrite).close()
createDir("docs")

open(DirSep & "output.txt", fmWrite).close()
createDir(DirSep & "docs")


use IO;

bundle Default {
  class FileExample {
    function : Main(args : String[]) ~ Nil {
      file := FileWriter->New("output.txt");
      file->Close();

      file := FileWriter->New("/output.txt");
      file->Close();

      Directory->Create("docs");
      Directory->Create("/docs");
    }
  }
}


NSFileManager *fm = [NSFileManager defaultManager];

[fm createFileAtPath:@"output.txt" contents:[NSData data] attributes:nil];
// Pre-OS X 10.5
[fm createDirectoryAtPath:@"docs" attributes:nil];
// OS X 10.5+
[fm createDirectoryAtPath:@"docs" withIntermediateDirectories:NO attributes:nil error:NULL];


# let oc = open_out "output.txt" in
  close_out oc;;
- : unit = ()

# Unix.mkdir "docs" 0o750 ;; (* rights 0o750 for rwxr-x--- *)
- : unit = ()


for Dir in ["/" "./"] do
   File = {New Open.file init(name:Dir#"output.txt" flags:[create])}
in
   {File close}
   {OS.mkDir Dir#"docs" ['S_IRUSR' 'S_IWUSR' 'S_IXUSR' 'S_IXGRP']}
end


program in out;

var

   f : textfile;

begin

   assignFile(f,'/output.txt');
   rewrite(f);
   close(f);
   makedir('/docs');
   assignFile(f,'/docs/output.txt');
   rewrite(f);
   close(f);

end;


use File::Spec::Functions qw(catfile rootdir);
{ # here
    open my $fh, '>', 'output.txt';
    mkdir 'docs';
};
{ # root dir
    open my $fh, '>', catfile rootdir, 'output.txt';
    mkdir catfile rootdir, 'docs';
};


integer fn

-- In the current working directory
system("mkdir docs",2)
fn = open("output.txt","w")
close(fn)

-- In the filesystem root
system("mkdir \\docs",2)
fn = open("\\output.txt","w")
if fn=-1 then
    puts(1,"unable to create \\output.txt\n")
else
    close(fn)
end if


<?php
touch('output.txt');
mkdir('docs');
touch('/output.txt');
mkdir('/docs');
?>


(out "output.txt")                     # Empty output
(call 'mkdir "docs")                   # Call external
(out "/output.txt")
(call 'mkdir "/docs")


import Stdio;

int main(){
   write_file("input.txt","",0100);
   write_file("/input.txt","",0100);
}


open file (output) title ('/OUTPUT.TXT,type(text),recsize(100)' );
close file (output);


New-Item output.txt -ItemType File
New-Item \output.txt -ItemType File
New-Item docs -ItemType Directory
New-Item \docs -ItemType Directory


makedirectory docs
changedirectory docs
makenewfile output.txt


import os
for directory in ['/', './']:
  open(directory + 'output.txt', 'w').close()  # create /output.txt, then ./output.txt
  os.mkdir(directory + 'docs')                 # create directory /docs, then ./docs


f <- file("output.txt", "w")
close(f)

# it may fails and the exact syntax to achieve the root
# changes according to the operating system
f <- file("/output.txt", "w")
close(f)

success <- dir.create("docs")
success <- dir.create("/docs")


#lang racket

(display-to-file "" "output.txt")
(make-directory "docs")
(display-to-file "" "/output.txt")
(make-directory "/docs")


for '.', '' -> $prefix {
    mkdir "$prefix/docs";
    open "$prefix/output.txt", :w;
}


"" as str
str 'output.txt'  write
str '/output.txt' write
'docs'  mkdir
'/docs' mkdir


; Creating in current directory:

write %output.txt ""
make-dir %docs/

; Creating in root directory:

write %/output.txt ""
make-dir %/docs/


'output.txt file:W file:open file:close
'/output.txt file:W file:open file:close


/*REXX pgm creates a new empty file and directory; in curr dir and root.*/
       do 2                            /*perform three statements twice.*/
       'COPY NUL output.txt'           /*copy a "null" (empty) file.    */
       'MKDIR DOCS'                    /*make a directory (aka: folder).*/
       'CD \'                          /*change currect dir to the root.*/
       end   /*2*/                     /*now, go and perform them again.*/
                                       /*stick a fork in it, we're done.*/


system("mkdir C:\Ring\docs")
fopen("C:\Ring\docs\output.txt", "w+")
system("mkdir docs")
fopen("output.txt", "w+")


['/', './'].each{|dir|
  Dir.mkdir(dir + 'docs')      # create '/docs', then './docs'
  File.open(dir + 'output.txt', 'w') {}  # create empty file /output.txt, then ./output.txt
}


open "output.txt" for output as #f
close #f

dirOk = mkdir( "f:\doc")
if not(dirOk) then print "Directory not created!": end

open "f:\doc\output.txt" for output as #f
close #f