Arithmetic:	PHA			;push accumulator and X register onto stack
		TXA
		PHA
		JSR GetUserInput	;routine not implemented
		;two integers now in memory locations A and B
		;addition
		LDA A
		CLC
		ADC B
		JSR DisplayAddition	;routine not implemented

		;subtraction
		LDA A
		SEC
		SBC B
		JSR DisplaySubtraction	;routine not implemented

		;multiplication - overflow not handled
		LDA A
		LDX B
Multiply:	CLC
		ADC A
		DEX
		BNE Multiply
		JSR DisplayMultiply	;routine not implemented

		;division	- rounds up
		LDA A
		LDX #0
		SEC
Divide:		INX
		SBC B
		BCS Divide
		TXA			;get result into accumulator
		JSR DisplayDivide	;routine not implemented

		;modulus
		LDA A
		SEC
Modulus:	SBC B
		BCS Modulus
		ADC B
		JSR DisplayModulus	;routine not implemented

		PLA			;restore accumulator and X register from stack
		TAX
		PLA
		RTS			;return from subroutine


ADD.L D0,D1 ; add two numbers
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
SUB.L D1,D0 ; subtract D1 from D0
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
MULU D0,D1  ; multiply two unsigned numbers. Use MULS for signed numbers
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
DIVU D1,D0  ; Divide D0 by D1. Use DIVS for signed numbers. Upper two bytes of D0 are the remainder, lower two are the integer quotient.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
MODULUS:
DIVU D1,D0
SWAP D0     ;swap the order of the 16-bit halves of D0.
RTS


// Create a new array with length 0
{def myArray1 {A.new}}
-> []

// Create an array with 2 members (length is 2)
{def myArray2 {A.new Item1 Item2}}
-> [Item1,Item2]

// Edit a value in an array
{def myArray3 {A.new 1 2 3}}
{A.set! 1 hello {myArray3}}
-> [1,hello,3]

// Add a value at the head of an array
{def myArray4 {A.new 1 2 3}}-> myArray4
{A.addfirst! hello {myArray4}}
-> [hello,1,2,3]

// Add a value at the tail of an array
{def myArray5 {A.new 1 2 3}}
{A.addlast! hello {myArray5}}
-> [1,2,3,hello]

and so on...


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

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

/***********************/
/* Initialized data */
/***********************/
.data
szMessError:          .asciz " Two numbers in command line please ! \n"       // message
szRetourLigne:        .asciz "\n"
szMessResult:         .asciz "resultat : @ \n"      // message result
sMessValeur:          .fill 12, 1, ' '
                      .asciz "\n"
szMessAddition:       .asciz "Addition "
szMessSoustraction:   .asciz "soustraction :"
szMessMultiplication: .asciz "multiplication :"
szMessDivision:       .asciz "division :"
szMessReste:          .asciz "remainder :"

/***********************/
/* No Initialized data */
/***********************/
.bss
qValeur:            .skip  8        // reserve 8 bytes in memory
sZoneConv:          .skip 30
.text
.global main
main:
    mov fp,sp                   // fp <- stack address
    ldr x0,[fp]                 // recup number of parameter in command line
    cmp x0,3
    blt error
    ldr x0,[fp,16]              // adresse of 1er number
    bl conversionAtoD
    mov x3,x0
    ldr x0,[fp,24]              // adresse of 2eme number
    bl conversionAtoD
    mov x4,x0
                                // addition
    add x0,x3,x4
    ldr x1,qAdrsZoneConv        // result in x0
    bl conversion10S            // call function with 2 parameter (x0,x1)
    ldr x0,qAdrszMessAddition
    bl affichageMess            // display message
    ldr x0,qAdrszMessResult
    ldr x1,qAdrsZoneConv
    bl strInsertAtCharInc       // insert result at @ character
    bl affichageMess            // display message
    ldr x0,qAdrsZoneConv
                                // soustraction
    sub x0,x3,x4
    ldr x1,qAdrsZoneConv        // result in x0
    bl conversion10S            // call function with 2 parameter (x0,x1)
    ldr x0,qAdrszMessSoustraction
    bl affichageMess            // display message
    ldr x0,qAdrszMessResult
    ldr x1,qAdrsZoneConv
    bl strInsertAtCharInc       // insert result at @ character
    bl affichageMess            // display message
    ldr x0,qAdrsZoneConv
                                // multiplication
    mul x0,x3,x4
    ldr x1,qAdrsZoneConv        // result in x0
    bl conversion10S            // call function with 2 parameter (x0,x1)
    ldr x0,qAdrszMessMultiplication
    bl affichageMess            // display message
    ldr x0,qAdrszMessResult
    ldr x1,qAdrsZoneConv
    bl strInsertAtCharInc       // insert result at @ character
    bl affichageMess            // display message
    ldr x0,qAdrsZoneConv
                                // division
    mov x0,x3
    mov x1,x4
    udiv x0,x3,x4               // quotient
    msub x3,x0,x4,x3            // remainder x3 = x3 - (x0*x4)
    ldr x1,qAdrsZoneConv        // result in x0
    bl conversion10S            // call function with 2 parameter (x0,x1)
    ldr x0,qAdrszMessDivision
    bl affichageMess            // display message
    ldr x0,qAdrszMessResult
    ldr x1,qAdrsZoneConv
    bl strInsertAtCharInc       // insert result at @ character
    bl affichageMess            // display message
    ldr x0,qAdrsZoneConv

    mov x0,x3                   // remainder
    ldr x1,qAdrsZoneConv        // result in x0
    bl conversion10S            // call function with 2 parameter (x0,x1)
    ldr x0,qAdrszMessReste
    bl affichageMess            // display message
    ldr x0,qAdrszMessResult
    ldr x1,qAdrsZoneConv
    bl strInsertAtCharInc       // insert result at @ character
    bl affichageMess            // display message
    ldr x0,qAdrsZoneConv

    mov x0,0                    // return code
    b 100f
error:
    ldr x0,qAdrszMessError
    bl affichageMess            // call function with 1 parameter (x0)
    mov x0,1                    // return code
100:                            // end of  program
    mov x8,EXIT                 // request to exit program
    svc 0                       // perform the system call
qAdrsMessValeur:          .quad sMessValeur
qAdrszMessResult:         .quad szMessResult
qAdrszMessError:          .quad szMessError
qAdrszMessAddition:       .quad szMessAddition
qAdrszMessSoustraction:   .quad szMessSoustraction
qAdrszMessMultiplication: .quad szMessMultiplication
qAdrszMessDivision:       .quad szMessDivision
qAdrszMessReste:          .quad szMessReste
qAdrsZoneConv:            .quad sZoneConv
/********************************************************/
/*        File Include fonctions                        */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"


report zz_arithmetic no standard page heading.

" Read in the two numbers from the user.
selection-screen begin of block input.
  parameters: p_first type i,
              p_second type i.
selection-screen end of block input.

" Set the text value that is displayed on input request.
at selection-screen output.
  %_p_first_%_app_%-text  = 'First Number: '.
  %_p_second_%_app_%-text = 'Second Number: '.

end-of-selection.
  data: lv_result type i.
  lv_result = p_first + p_second.
  write: / 'Addition:', lv_result.
  lv_result = p_first - p_second.
  write: / 'Substraction:', lv_result.
  lv_result = p_first * p_second.
  write: / 'Multiplication:', lv_result.
  lv_result = p_first div p_second.
  write: / 'Integer quotient:', lv_result. " Truncated towards zero.
  lv_result = p_first mod p_second.
  write: / 'Remainder:',  lv_result.


[]
1 append
['foo 'bar] append
2 reshape
0 remove 2 swap 2 compress collapse .


var .a1 = [1, 2, 3, "abc"]
val .a2 = series 4..10
val .a3 = .a1 ~ .a2

writeln "initial values ..."
writeln ".a1: ", .a1
writeln ".a2: ", .a2
writeln ".a3: ", .a3
writeln()

.a1[4] = .a2[4]
writeln "after setting .a1[4] = .a2[4] ..."
writeln ".a1: ", .a1
writeln ".a2: ", .a2
writeln ".a3: ", .a3
writeln()

writeln ".a2[1]: ", .a2[1]
writeln()

writeln "using index alternate ..."
writeln ".a2[5; 0]: ", .a2[5; 0]
writeln ".a2[10; 0]: ", .a2[10; 0]
writeln()


:set-state-ok t

(defun get-two-nums (state)
   (mv-let (_ a state)
           (read-object *standard-oi* state)
      (declare (ignore _))
      (mv-let (_ b state)
              (read-object *standard-oi* state)
         (declare (ignore _))
         (mv a b state))))

(defun integer-arithmetic (state)
   (mv-let (a b state)
           (get-two-nums state)
      (mv state
          (progn$ (cw "Sum:        ~x0~%" (+ a b))
                  (cw "Difference: ~x0~%" (- a b))
                  (cw "Product:    ~x0~%" (* a b))
                  (cw "Quotient:   ~x0~%" (floor a b))
                  (cw "Remainder:  ~x0~%" (mod a b))))))


DEFINE NO_KEY="255"
DEFINE KEY_Y="43"
DEFINE KEY_N="35"

PROC Main()
  BYTE CH=$02FC ;Internal hardware value for last key pressed
  BYTE k
  INT a,b

  DO
    Print("Input integer value a=")
    a=InputI()
    Print("Input integer value b=")
    b=InputI()

    PrintF("a+b=%I%E",a+b)
    PrintF("a-b=%I%E",a-b)
    PrintF("a*b=%I%E",a*b)
    PrintF("a/b=%I%E",a/b)
    PrintF("a MOD b=%I%E",a MOD b)

    PutE()
    PrintE("Again? (Y/N)")

    CH=NO_KEY ;Flush the keyboard
    DO
      k=CH
    UNTIL k=KEY_Y OR k=KEY_N
    OD
    CH=NO_KEY ;Flush the keyboard

    IF k=KEY_N THEN
      EXIT
    FI
  OD
RETURN


// Create a new empty array
local(array1) = array

// Create an array with 2 members (#myarray->size is 2)
local(array1) = array('ItemA','ItemB')

// Assign a value to member [2]
#array1->get(2) = 5

// Retrieve a value from an array
#array1->get(2) + #array1->size // 8

// Merge arrays
local(
    array1 = array('a','b','c'),
    array2 = array('a','b','c')
)
#array1->merge(#array2) // a, b, c, a, b, c

// Sort an array
#array1->sort // a, a, b, b, c, c

// Remove value by index
#array1->remove(2) // a, b, b, c, c

// Remove matching items
#array1->removeall('b') // a, c, c

// Insert item
#array1->insert('z')  // a, c, c, z

// Insert item at specific position
#array1->insert('0',1)  // 0, a, c, c, z


;; Construct an array.
foo := [1, 2, 3].

;; Arrays can also be constructed explicitly.
bar := Array clone.
bar pushBack (1).
bar pushBack (2).
bar pushBack (3).

;; Accessing values.
println: foo nth (2). ;; 3

;; Mutating values.
foo nth (1) = 99.
println: foo. ;; [1, 99, 3]

;; Appending to either the front or the back of the array.
foo pushBack ("back").
foo pushFront ("front").
println: foo. ;; ["front", 1, 99, 3, "back"]

;; Popping from the front or back.
println: foo popBack. ;; "back"
println: foo popBack. ;; 3
println: foo popFront. ;; "front"
println: foo. ;; [1, 99]


with Ada.Text_Io;
with Ada.Integer_Text_IO;

procedure Integer_Arithmetic is
   use Ada.Text_IO;
   use Ada.Integer_Text_Io;

   A, B : Integer;
begin
   Get(A);
   Get(B);
   Put_Line("a+b = " & Integer'Image(A + B));
   Put_Line("a-b = " & Integer'Image(A - B));
   Put_Line("a*b = " & Integer'Image(A * B));
   Put_Line("a/b = " & Integer'Image(A / B));
   Put_Line("a mod b = " & Integer'Image(A mod B)); -- Sign matches B
   Put_Line("remainder of a/b = " & Integer'Image(A rem B)); -- Sign matches A
   Put_Line("a**b = " & Integer'Image(A ** B));

end Integer_Arithmetic;


var a = 0
var b = 0
stdin -> a    // read int from stdin
stdin -> b    // read int from stdin

println ("a+b=" + (a + b))
println ("a-b=" + (a - b))
println ("a*b=" + (a * b))
println ("a/b=" + (a / b))
println ("a%b=" + (a % b))


; Create a fixed-size array with entries 0-9 set to 'undefined'
> (set a0 (: array new 10))
#(array 10 0 undefined 10)
> (: array size a0)
10

; Create an extendible array and set entry 17 to 'true',
; causing the array to grow automatically
> (set a1 (: array set 17 'true (: array new)))
#(array
  18
  ...
(: array size a1)
18

; Read back a stored value
> (: array get 17 a1)
true

; Accessing an unset entry returns the default value
> (: array get 3 a1)
undefined

; Accessing an entry beyond the last set entry also returns the
; default value, if the array does not have fixed size
> (: array get 18 a1)
undefined

; "sparse" functions ignore default-valued entries
> (set a2 (: array set 4 'false a1))
#(array
  18
  ...
> (: array sparse_to_orddict a2)
(#(4 false) #(17 true))

; An extendible array can be made fixed-size later
> (set a3 (: array fix a2))
#(array
  18
  ...

; A fixed-size array does not grow automatically and does not
; allow accesses beyond the last set entry
> (: array set 18 'true a3)
exception error: badarg
  in (array set 3)

> (: array get 18 a3)
exception error: badarg
  in (array get 2)


main:(
  LONG INT a=355, b=113;
  printf(($"a+b = "gl$, a + b));
  printf(($"a-b = "gl$, a - b));
  printf(($"a*b = a×b = "gl$, a * b));
  printf(($"a/b = "gl$, a / b));
  printf(($"a OVER b = a%b = a÷b = "gl$, a % b));
  printf(($"a MOD b = a%*b = a%×b = a÷×b = a÷*b = "gl$, a %* b));
  printf(($"a UP b = a**b = a↑b = "gl$, a ** b))
)


begin
    integer a, b;
    write( "Enter 2 integers> " );
    read( a, b );
    write( "a  +  b: ", a  +  b ); % addition         %
    write( "a  -  b: ", a  -  b ); % subtraction      %
    write( "a  *  b: ", a  *  b ); % multiplication   %
    write( "a  /  b: ", a div b ); % integer division %
    write( "a mod b: ", a rem b ); % modulo           %
    % the ** operator returns a real result even with integer operands  %
    % ( the right-hand operand must always be an integer, the left-hand %
    % operand can be integer, real or complex )                         %
    write( "a  ^  b: ", round( a ** b ) )
end.


dim Array(10)

Array(0) = -1
Array(10) =  1

print Array( 0), Array( 10)

REDIM Array( 100)

print Array( 0), Array( 10)

Array( 0) = -1
print Array( 0), Array( 10)


PROC main()
  DEF a, b, t
  WriteF('A = ')
  ReadStr(stdin, t)
  a := Val(t)
  WriteF('B = ')
  ReadStr(stdin, t)
  b := Val(t)
  WriteF('A+B=\d\nA-B=\d\n', a+b, a-b)
  WriteF('A*B=\d\nA/B=\d\n', a*b, a/b)
  /* * and / are 16 bit ops; Mul and Div are 32bit ops */
  WriteF('A*B=\d\nA/B=\d\n', Mul(a,b), Div(a,b))
  WriteF('A mod B =\d\n', Mod(a,b))
ENDPROC


∇res ← integer_arithmetic; l; r
  l ← ⎕
  r ← ⎕
  res ← 6 2 ⍴ 'sum' (l+r) 'diff' (l-r) 'prod' (l×r) 'quot' (⌊l÷r) 'rem' (r|l) 'pow' (l*r)
∇


set i1 to (text returned of (display dialog "Enter an integer value" default answer "")) as integer
set i2 to (text returned of (display dialog "Enter another integer value" default answer "")) as integer

set sum to i1 + i2
set diff to i1 - i2
set prod to i1 * i2
set quot to i1 div i2 -- Rounds towards zero.
set remainder to i1 mod i2 -- The result's sign matches the dividend's.
set exp to i1 ^ i2 -- The result's always a real.

return {|integers|:{i1, i2}, difference:diff, product:prod, quotient:quot, remainder:remainder, exponientiation:exp}


# (not) Arrays, in LIL
set a [list abc def ghi]
set b [list 4 5 6]
print [index $a 0]
print [index $b 1]
print [count $a]
append b [list 7 8 9]
print [count $b]
print $b


/* ARM assembly Raspberry PI  */
/*  program arith.s   */
/* Constantes    */
.equ STDOUT, 1
.equ WRITE,  4
.equ EXIT,   1

/***********************/
/* Initialized data */
/***********************/
.data
szMessError:      .asciz " Two numbers in command line please ! \n"       @ message
szRetourLigne: .asciz "\n"
szMessResult:  .asciz "Resultat "      @ message result
sMessValeur:   .fill 12, 1, ' '
                   .asciz "\n"
szMessAddition: .asciz "addition :"
szMessSoustraction: .asciz "soustraction :"
szMessMultiplication: .asciz "multiplication :"
szMessDivision: .asciz "division :"
szMessReste: .asciz "reste :"

/***********************/
/* No Initialized data */
/***********************/
.bss
iValeur:  .skip  4     @ reserve 4 bytes in memory

.text
.global main
main:
    push {fp,lr}                @ save des  2 registres
    add fp,sp,#8                @ fp <- adresse début
    ldr r0,[fp]                 @ recup number of parameter in command line
    cmp r0,#3
    blt error
    ldr r0,[fp,#8]              @ adresse of 1er number
    bl conversionAtoD
    mov r3,r0
    ldr r0,[fp,#12]             @ adresse of 2eme number
    bl conversionAtoD
    mov r4,r0
    @ addition
    add r0,r3,r4
    ldr r1,iAdrsMessValeur      @ result in r0
    bl conversion10S            @ call function with 2 parameter (r0,r1)
    ldr r0,iAdrszMessResult
    bl affichageMess            @ display message
    ldr r0,iAdrszMessAddition
    bl affichageMess            @ display message
    ldr r0,iAdrsMessValeur
    bl affichageMess            @ display message
    @ soustraction
    sub r0,r3,r4
    ldr r1,=sMessValeur
    bl conversion10S            @ call function with 2 parameter (r0,r1)
    ldr r0,iAdrszMessResult
    bl affichageMess            @ display message
    ldr r0,iAdrszMessSoustraction
    bl affichageMess            @ display message
    ldr r0,iAdrsMessValeur
    bl affichageMess            @ display message

    @ multiplication
    mul r0,r3,r4
    ldr r1,=sMessValeur
    bl conversion10S            @ call function with 2 parameter (r0,r1)
    ldr r0,iAdrszMessResult
    bl affichageMess            @ display message
    ldr r0,iAdrszMessMultiplication
    bl affichageMess            @ display message
    ldr r0,iAdrsMessValeur
    bl affichageMess            @ display message

    @ division
    mov r0,r3
    mov r1,r4
    bl division
    mov r0,r2                   @ quotient
    ldr r1,=sMessValeur
    bl conversion10S            @ call function with 2 parameter (r0,r1)
    ldr r0,iAdrszMessResult
    bl affichageMess            @ display message
    ldr r0,iAdrszMessDivision
    bl affichageMess            @ display message
    ldr r0,iAdrsMessValeur
    bl affichageMess            @ display message

    mov r0,r3                   @ remainder
    ldr r1,=sMessValeur
    bl conversion10S            @ call function with 2 parameter (r0,r1)
    ldr r0,iAdrszMessResult
    bl affichageMess            @ display message
    ldr r0,iAdrszMessReste
    bl affichageMess            @ display message
    ldr r0,iAdrsMessValeur
    bl affichageMess            @ display message

    mov r0, #0                  @ return code
    b 100f
error:
    ldr r0,iAdrszMessError
    bl affichageMess            @ call function with 1 parameter (r0)
    mov r0, #1                  @ return code
100: /* end of  program */
    mov r7, #EXIT               @ request to exit program
    swi 0                       @ perform the system call
iAdrsMessValeur: .int sMessValeur
iAdrszMessResult: .int szMessResult
iAdrszMessError: .int szMessError
iAdrszMessAddition: .int szMessAddition
iAdrszMessSoustraction: .int szMessSoustraction
iAdrszMessMultiplication: .int szMessMultiplication
iAdrszMessDivision: .int szMessDivision
iAdrszMessReste: .int szMessReste
/******************************************************************/
/*     affichage des messages   avec calcul longueur              */
/******************************************************************/
/* r0 contient l adresse du message */
affichageMess:
    push {fp,lr}        /* save des  2 registres */
    push {r0,r1,r2,r7}  /* save des autres registres */
    mov r2,#0           /* compteur longueur */
1:                      /*calcul de la longueur */
    ldrb r1,[r0,r2]     /* recup octet position debut + indice */
    cmp r1,#0           /* si 0 c est fini */
    beq 1f
    add r2,r2,#1        /* sinon on ajoute 1 */
    b 1b
1:                      /* donc ici r2 contient la longueur du message */
    mov r1,r0           /* adresse du message en r1 */
    mov r0,#STDOUT      /* code pour écrire sur la sortie standard Linux */
    mov r7, #WRITE      /* code de l appel systeme 'write' */
    swi #0              /* appel systeme */
    pop {r0,r1,r2,r7}   /* restaur des autres registres */
    pop {fp,lr}         /* restaur des  2 registres */
    bx lr	        /* retour procedure */
/***************************************************/
/*   conversion registre en décimal   signé  */
/***************************************************/
/* r0 contient le registre   */
/* r1 contient l adresse de la zone de conversion */
conversion10S:
    push {fp,lr}      /* save des  2 registres frame et retour */
    push {r0-r5}      /* save autres registres  */
    mov r2,r1         /* debut zone stockage */
    mov r5,#'+'       /* par defaut le signe est + */
    cmp r0,#0         /* nombre négatif ? */
    movlt r5,#'-'     /* oui le signe est - */
    mvnlt r0,r0       /* et inversion en valeur positive */
    addlt r0,#1
    mov r4,#10       /* longueur de la zone */
1:                   /* debut de boucle de conversion */
    bl divisionpar10 /* division  */
    add r1,#48       /* ajout de 48 au reste pour conversion ascii */
    strb r1,[r2,r4]  /* stockage du byte en début de zone r5 + la position r4 */
    sub r4,r4,#1     /* position précedente */
    cmp r0,#0
    bne 1b	     /* boucle si quotient different de zéro */
    strb r5,[r2,r4]  /* stockage du signe à la position courante */
    subs r4,r4,#1    /* position précedente */
    blt  100f        /* si r4 < 0  fin  */
                     /* sinon il faut completer le debut de la zone avec des blancs */
    mov r3,#' '      /* caractere espace */
2:
    strb r3,[r2,r4]  /* stockage du byte  */
    subs r4,r4,#1    /* position précedente */
    bge 2b           /* boucle si r4 plus grand ou egal a zero */
100:                 /* fin standard de la fonction  */
    pop {r0-r5}      /*restaur des autres registres */
    pop {fp,lr}      /* restaur des  2 registres frame et retour  */
    bx lr

/***************************************************/
/*   division par 10   signé                       */
/* Thanks to http://thinkingeek.com/arm-assembler-raspberry-pi/*
/* and   http://www.hackersdelight.org/            */
/***************************************************/
/* r0 contient le dividende   */
/* r0 retourne le quotient */
/* r1 retourne le reste  */
divisionpar10:
  /* r0 contains the argument to be divided by 10 */
   push {r2-r4}   /* save autres registres  */
   mov r4,r0
   ldr r3, .Ls_magic_number_10 /* r1 <- magic_number */
   smull r1, r2, r3, r0   /* r1 <- Lower32Bits(r1*r0). r2 <- Upper32Bits(r1*r0) */
   mov r2, r2, ASR #2     /* r2 <- r2 >> 2 */
   mov r1, r0, LSR #31    /* r1 <- r0 >> 31 */
   add r0, r2, r1         /* r0 <- r2 + r1 */
   add r2,r0,r0, lsl #2   /* r2 <- r0 * 5 */
   sub r1,r4,r2, lsl #1   /* r1 <- r4 - (r2 * 2)  = r4 - (r0 * 10) */
   pop {r2-r4}
   bx lr                  /* leave function */
   .align 4
.Ls_magic_number_10: .word 0x66666667
/******************************************************************/
/*     Conversion d une chaine en nombre stocké dans un registre  */
/******************************************************************/
/* r0 contient l adresse de la zone terminée par 0 ou 0A */
conversionAtoD:
    push {fp,lr}      /* save des  2 registres */
    push {r1-r7}      /* save des autres registres */
    mov r1,#0
    mov r2,#10        /* facteur */
    mov r3,#0         /* compteur */
    mov r4,r0         /* save de l adresse dans r4 */
    mov r6,#0         /* signe positif par defaut */
    mov r0,#0         /* initialisation à 0 */
1:                    /* boucle d élimination des blancs du debut */
    ldrb r5,[r4,r3]   /* chargement dans r5 de l octet situé au debut + la position */
    cmp r5,#0         /* fin de chaine -> fin routine */
    beq 100f
    cmp r5,#0x0A      /* fin de chaine -> fin routine */
    beq 100f
    cmp r5,#' '       /* blanc au début */
    bne 1f            /* non on continue */
    add r3,r3,#1      /* oui on boucle en avançant d un octet */
    b 1b
1:
    cmp r5,#'-'       /* premier caracteres est -    */
    moveq r6,#1       /* maj du registre r6 avec 1 */
    beq 3f            /* puis on avance à la position suivante */
2:                    /* debut de boucle de traitement des chiffres */
    cmp r5,#'0'       /* caractere n est pas un chiffre */
    blt 3f
    cmp r5,#'9'       /* caractere n est pas un chiffre */
    bgt 3f
                      /* caractère est un chiffre */
    sub r5,#48
    ldr r1,iMaxi      /*verifier le dépassement du registre  */
    cmp r0,r1
    bgt 99f
    mul r0,r2,r0     /* multiplier par facteur */
    add r0,r5        /* ajout à r0 */
3:
    add r3,r3,#1     /* avance à la position suivante */
    ldrb r5,[r4,r3]  /* chargement de l octet */
    cmp r5,#0        /* fin de chaine -> fin routine */
    beq 4f
    cmp r5,#10       /* fin de chaine -> fin routine */
    beq 4f
    b 2b             /* boucler */
4:
    cmp r6,#1        /* test du registre r6 pour le signe */
    bne 100f
    mov r1,#-1
    mul r0,r1,r0    /* si negatif, on multiplie par -1 */
    b 100f
99:                 /* erreur de dépassement */
    ldr r1,=szMessErrDep
    bl   afficheerreur
    mov r0,#0       /* en cas d erreur on retourne toujours zero */
100:
    pop {r1-r7}     /* restaur des autres registres */
    pop {fp,lr}     /* restaur des  2 registres */
    bx lr           /* retour procedure */
/* constante programme */
iMaxi: .int 1073741824
szMessErrDep:  .asciz  "Nombre trop grand : dépassement de capacite de 32 bits. :\n"
.align 4
/*=============================================*/
/* division entiere non signée                */
/*============================================*/
division:
    /* r0 contains N */
    /* r1 contains D */
    /* r2 contains Q */
    /* r3 contains R */
    push {r4, lr}
    mov r2, #0              /* r2 ? 0 */
    mov r3, #0              /* r3 ? 0 */
    mov r4, #32             /* r4 ? 32 */
    b 2f
1:
    movs r0, r0, LSL #1    /* r0 ? r0 << 1 updating cpsr (sets C if 31st bit of r0 was 1) */
    adc r3, r3, r3         /* r3 ? r3 + r3 + C. This is equivalent to r3 ? (r3 << 1) + C */

    cmp r3, r1             /* compute r3 - r1 and update cpsr */
    subhs r3, r3, r1       /* if r3 >= r1 (C=1) then r3 ? r3 - r1 */
    adc r2, r2, r2         /* r2 ? r2 + r2 + C. This is equivalent to r2 ? (r2 << 1) + C */
2:
    subs r4, r4, #1        /* r4 ? r4 - 1 */
    bpl 1b                 /* if r4 >= 0 (N=0) then branch to .Lloop1 */

    pop {r4, lr}
    bx lr


+ a : ARRAY(INTEGER);
a := ARRAY(INTEGER).create 0 to 9;
a.put 1 to 0;
a.put 3 to 1;
a.item(1).print;


a: to :integer input "give me the first number  : "
b: to :integer input "give me the second number : "

print [a "+" b "=" a+b]
print [a "-" b "=" a-b]
print [a "*" b "=" a*b]
print [a "/" b "=" a/b]
print [a "%" b "=" a%b]
print [a "^" b "=" a^b]


int a = -12;
int b = 7;

int suma = a + b;
int resta = a - b;
int producto = a * b;
real division = a / b;
int resto = a % b;
int expo = a ** b;

write("Siendo dos enteros a = -12 y b = 7");
write("       suma de a + b = ", suma);
write("      resta de a - b = ", resta);
write("   producto de a * b = ", producto);
write("   división de a / b = ", division);
write("   resto de a mod  b = ", resto);
write("exponenciación a ^ b = ", expo);


String fruit[] = {"apple", "orange", "Pear"}


array 5      ; default origin is 1, every item is empty
(array 5 0)  ; custom origin
make "a {1 2 3 4 5}  ; array literal
setitem 1 :a "ten       ; Logo is dynamic; arrays can contain different types
print item 1 :a   ; ten


Gui, Add, Edit, va, 5
Gui, Add, Edit, vb, -3
Gui, Add, Button, Default, Compute
Gui, Show
Return

ButtonCompute:
  Gui, Submit
  MsgBox,%
  (Join`s"`n"
   a "+" b " = " a+b
   a "-" b " = " a-b
   a "*" b " = " a*b
   a "//" b " = " a//b " remainder " Mod(a,b)
   a "**" b " = " a**b
  )
; fallthrough
GuiClose:
  ExitApp


Method "arithmetic demo_,_" is
[
    a : integer,
    b : integer
|
    Print: “a + b”;
    Print: “a - b”;
    Print: “a × b”; // or a * b
    Print: “a ÷ b”; // or a / b, rounds toward negative infinity
    Print: “a mod b”; // sign matches second argument
    Print: “a ^ b”;
];


HAI 1.4
BTW declaring array
I HAS A array ITZ A BUKKIT
BTW store values in array
array HAS A one ITZ 1
array HAS A two ITZ 2
array HAS A three ITZ 3
array HAS A string ITZ "MEOW"
OBTW
there is no way to get an element of an array at a specified index in LOLCODE
therefore, you can't really iterate through an array
TLDR
BTW get the element of array
VISIBLE array'Z one
VISIBLE array'Z two
VISIBLE array'Z three
VISIBLE array'Z string
KTHXBYE


10 myArray :array
0 array 5 [] !      # store 0 at the sixth cell in the array
array 5 [] @     # contents of sixth cell in array


/^[ \t]*-?[0-9]+[ \t]+-?[0-9]+[ \t]*$/ {
	print "add:", $1 + $2
	print "sub:", $1 - $2
	print "mul:", $1 * $2
	print "div:", int($1 / $2) # truncates toward zero
	print "mod:", $1 % $2      # same sign as first operand
	print "exp:", $1 ^ $2
	exit }


' Arthimetic/Integer
DECLARE a%, b%
INPUT "Enter integer A: ", a%
INPUT "Enter integer B: ", b%
PRINT

PRINT a%, " + ", b%, "     is ", a% + b%
PRINT a%, " - ", b%, "     is ", a% - b%
PRINT a%, " * ", b%, "     is ", a% * b%
PRINT a%, " / ", b%, "     is ", a% / b%, ", trucation toward zero"
PRINT "MOD(", a%, ", ", b%, ") is ", MOD(a%, b%), ", same sign as first operand"
PRINT "POW(", a%, ", ", b%, ") is ", INT(POW(a%, b%))


default {
    state_entry() {
        list lst = ["1", "2", "3"];
        llSay(0, "Create and Initialize a List\nList=["+llList2CSV(lst)+"]\n");

        lst += ["A", "B", "C"];
        llSay(0, "Append to List\nList=["+llList2CSV(lst)+"]\n");

        lst = llListInsertList(lst, ["4", "5", "6"], 3);
        llSay(0, "List Insertion\nList=["+llList2CSV(lst)+"]\n");

        lst = llListReplaceList(lst, ["a", "b", "c"], 3, 5);
        llSay(0, "Replace a portion of a list\nList=["+llList2CSV(lst)+"]\n");

        lst = llListRandomize(lst, 1);
        llSay(0, "Randomize a List\nList=["+llList2CSV(lst)+"]\n");

        lst = llListSort(lst, 1, TRUE);
        llSay(0, "Sort a List\nList=["+llList2CSV(lst)+"]\n");

        lst = [1, 2.0, "string", (key)NULL_KEY, ZERO_VECTOR, ZERO_ROTATION];
        string sCSV = llList2CSV(lst);
        llSay(0, "Serialize a List of different datatypes to a string\n(integer, float, string, key, vector, rotation)\nCSV=\""+sCSV+"\"\n");

        lst = llCSV2List(sCSV);
        llSay(0, "Deserialize a string CSV List\n(note that all elements are now string datatype)\nList=["+llList2CSV(lst)+"]\n");
    }
}


l = {}
l[1] = 1      -- Index starts with 1, not 0.
l[0] = 'zero' -- But you can use 0 if you want
l[10] = 2     -- Indexes need not be continuous
l.a = 3       -- Treated as l['a']. Any object can be used as index
l[l] = l      -- Again, any object can be used as an index. Even other tables
for i,v in next,l do print (i,v) end


input "enter a number ?", a
input "enter another number ?", b

print "addition " + a + " + " + b + " = " + (a + b)
print "subtraction " + a + " - " + b + " = " + (a - b)
print "multiplication " + a + " * " + b + " = " + (a * b)
print "integer division " + a + " \ " + b + " = " + (a \ b)
print "remainder or modulo " + a + " % " + b + " = " + (a % b)
print "power " + a + " ^ " + b + " = " + (a ^ b)


set /p equation=
set /a result=%equation%
echo %result%
pause


Module CheckArray {
      \\ Array with parenthesis in name
      Dim A(10)=1
      Global B(10)=1
      For This {
            Local A(10)=5
            Print A(4)=5
      }
      Print A(4)=1

      \\ Auto Array
      M=(1,2,3,4,5)
      Link M to M()
      Print M(2)=3
      Return M, 0:=100, 5-4:=300

      \\ Retrieve an Element of an Array
      k=Each(M, 1, 2)
      \\ print 100 300
      While k { Print Array(k),}
      Print
      Print Array(M, 2)=3
      Print Array("M", 2)=3
      Print Array(B(), 1)=1
      \\ arrays are containers for every value/object/pointer
      B(0):="Hello",100,"Good Morning", 200
      \\ using set to make B$() global too
      Set Link B() to B$()
      Print B$(0), B(1), B$(2), B(3)
      Swap B(0), B(2)
      Swap B(1), B(3)
      Print B$(0), B(1), B$(2), B(3)
      Print B()
      \\ Reduce B() to 4 elements - and change dimensions
      \\ we have to redim the global array, using set to send line to console
      \\ all globals are part of level 0, at console input.
      Set Dim B(4)
      Module CheckGlobal {
            Print B$(0), B(1), B$(2), B(3)
      }
      CheckGlobal
      Print B()
      Dim BB(4)
      \\ Copy 4 items from B() to BB(), from B(0), to BB(0)
      Stock B(0) keep 4, BB(0)
      Link BB() to BB$()
      Print BB$(0), BB(1), BB$(2), BB(3)
      \\ Arrays of structures in Buffers

      Structure TwoByte {
            {
                  ab as integer
            }
            a as byte
            b as byte
      }
      Print Len(TwoByte) = 2
      \ Use clear to clear memory
      \\ Mem is a pointer to a Buffer object
      Buffer Clear Mem as TwoByte*20
      Print Len(Mem)=40
      Return Mem, 0!ab:=0xFFAA
      Print Eval(Mem, 0!a)=0xAA,  Eval(Mem, 0!b)=0xFF
      Return Mem, 0!b:=0xF2
      Hex Eval(Mem,0!ab)   ' print 0xF2AA
      \\ Redim with preserve
      Buffer Mem as TwoByte*40
      \\ copy 40 bytes  at index 20 (40 bytes from start)
      Return Mem, 20:=Eval$(Mem, 0, 20*2)
      Hex Eval(Mem,20!ab)   ' print 0xF2AA
      A(3)=Mem
      Hex Eval(A(3),20!ab)   ' print 0xF2AA
      \\ now Mem change pointer
      Clear Mem
      Print Len(Mem)
      \\ old Mem is in A(3)
      Hex Eval(A(3),20!ab)   ' print 0xF2AA
      \\ we can change
      Buffer Clear Mem as Integer * 200
      Print Len(Mem)=400
      Return Mem, 0:=Eval$(A(3), 0, 80)
      Hex Eval(Mem,20)   ' print 0xF2AA
      \\ change type without use of clear
      Buffer Mem as TwoByte * 200
      Hex Eval(Mem,20!ab)   ' print 0xF2AA
}
CheckArray


#defining an array of a certain length
a := Array (1..5);
                                 a := [ 0 0 0 0 0 ]
#can also define with a list of entries
a := Array ([1, 2, 3, 4, 5]);
                                a := [ 1 2 3 4 5 ]
a[1] := 9;
a
                                a[1] := 9
                                [ 9 2 3 4 5 ]
a[5];
                                5
#can only grow arrays using ()
a(6) := 6;
                                a := [ 9 2 3 4 5 6 ]
a[7] := 7;
Error, Array index out of range


      INPUT "Enter the first integer: " first%
      INPUT "Enter the second integer: " second%

      PRINT "The sum is " ; first% + second%
      PRINT "The difference is " ; first% - second%
      PRINT "The product is " ; first% * second%
      PRINT "The integer quotient is " ; first% DIV second% " (rounds towards 0)"
      PRINT "The remainder is " ; first% MOD second% " (sign matches first operand)"
      PRINT "The first raised to the power of the second is " ; first% ^ second%


define f(a, b) {
	"add: "; a + b
	"sub: "; a - b
	"mul: "; a * b
	"div: "; a / b  /* truncates toward zero */
	"mod: "; a % b  /* same sign as first operand */
	"pow: "; a ^ b
}


>> a = [1 2 35] %Declaring a vector (i.e. one-dimensional array)

a =

     1     2    35

>> a = [1 2 35;5 7 9] % Declaring a matrix (i.e. two-dimensional array)

a =

     1     2    35
     5     7     9

>> a3 = reshape(1:2*3*4,[2,3,4]);   % declaring a three-dimensional array of size 2x3x4

a3 =

ans(:,:,1) =

   1   3   5
   2   4   6

ans(:,:,2) =

    7    9   11
    8   10   12

ans(:,:,3) =

   13   15   17
   14   16   18

ans(:,:,4) =

   19   21   23
   20   22   24

>> a(2,3) %Retrieving value using row and column indicies

     9

>> a(6) %Retrieving value using array subscript

ans =

     9

>> a = [a [10;42]] %Added a column vector to the array

a =

     1     2    35    10
     5     7     9    42

>> a(:,1) = [] %Deleting array elements

a =

     2    35    10
     7     9    42


•Out "Enter number 1: "
a ← •BQN •GetLine @
•Out "Enter number 2: "
b ← •BQN •GetLine @

•Show a + b
•Show a - b
•Show a × b
•Show a ÷ b
•Show b | a
•Show a ⋆ b


/* Declare an array, subscripts run from 0 to max value */
array(a, flonum, 20, 20, 3)$

arrayinfo(a);
/* [complete, 3, [20, 20, 3]] */

a[0, 0]: 1.0;

listarray(a);
/* [1.0, 0.0, 0.0, ..., 0.0] */

/* Show all declared arrays */
arrays;
/* [a] */

/* One may also use an array without declaring it, it's a hashed array */
b[1]: 1000;
b['x]: 3/4; /* hashed array may have any subscript */

arrayinfo(b);
/* [hashed, 1, [1], [x]] */

listarray(b);
/* [1000, 3/4] */


:- module array_example.
:- interface.
:- import_module io.
:- pred main(io::di, io::uo) is det.
:- implementation.
:- import_module array, int.
:- use_module exception.

:- type example_error ---> impossible.

main(!IO) :-
    some [!A] ( % needed to introduce a state variable not present in the head
        % Create an array(int) of length 10, with initial values of 0
        array.init(10, 0, !:A),

        % create an empty array (with no initial value)
        % since the created array is never used, type inference can't tell what
        % kind of array it is, and there's an unresolved polymorphism warning.
        array.make_empty_array(_Empty),

        % resize our first array, so that we can then set its 17th member
        % new values are set to -1
        array.resize(20, -1, !A),
        !A ^ elem(17) := 5,

        % Mercury data structures tend to have deterministic (exception thrown
        % on error), semideterministic (logical failure on error), and unsafe
        % (undefined behavior on error) access methods.
        array.lookup(!.A, 5, _), % det
        ( if array.semidet_lookup(!.A, 100, _) then  % semidet
            exception.throw(impossible)
        else
            true
        ),
        array.unsafe_lookup(!.A, 5, _), % could cause a segfault on a smaller array

        % output: array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, -1, -1, -1, -1, -1, -1, 5, -1, -1])
        io.print_line(!.A, !IO),

        plusminus(2, 0, !A),

        % output: array([2, -2, 2, -2, 2, -2, 2, -2, 2, -2, 1, -3, 1, -3, 1, -3, 1, 3, 1, -3])
        io.print_line(!.A, !IO)
    ).

    % Sample predicate operating on an array.
    % Note the array_* modes instead of in/out.
:- pred plusminus(int, int, array(int), array(int)).
:- mode plusminus(in, in, array_di, array_uo) is det.
plusminus(N, I, !A) :-
    ( if array.semidet_lookup(!.A, I, X) then
        !A ^ unsafe_elem(I) := X + N,
        plusminus(-N, I+1, !A)
    else
        true
    ).


  ( enter
  =     put$"Enter two integer numbers, separated by space:"
      & get':(~/#?k_~/#?m|quit:?k)
    |     out
        $ "You must enter two integer numbers! Enter \"quit\" if you don't know how to do that."
      & !enter
  )
& !enter
& !k:~quit
& out$("You entered" !k and !m ". Now look:")
& out$("Sum:" !k+!m)
& out$("Difference:" !k+-1*!m)
& out$("Product:" !k*!m)
& out$("Integer division:" div$(!k.!m))
& out$("Remainder:" mod$(!k.!m))
& out$("Exponentiation:" !k^!m)
& done;


x = ask("First number: ").to_i
y = ask("Second number: ").to_i

#Division uses floating point
#Remainder uses sign of right hand side
[:+ :- :* :/ :% :^].each { op |
  p "#{x} #{op} #{y} = #{x.call_method op, y}"


+	list concatenation
*	replication (i.e. repeat the list some number of times)
/	division (get some fraction of a list)
==, !=	comparison (for equality)
[i]	get/set item i (first item is 0)
[i:j]	get sublist ("slice") from i up to j


	.data
array:	.word	1, 2, 3, 4, 5, 6, 7, 8, 9 # creates an array of 9 32 Bit words.

	.text
main:	la 	$s0, array
	li	$s1, 25
	sw	$s1, 4($s0)	# writes $s1 (25) in the second array element
# the four counts thi bytes after the beginning of the address. 1 word = 4 bytes, so 4 acesses the second element

	lw	$s2, 20($s0)	# $s2 now contains 6

	li	$v0, 10		# end program
	syscall


#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
  int a, b;
  if (argc < 3) exit(1);
  b = atoi(argv[--argc]);
  if (b == 0) exit(2);
  a = atoi(argv[--argc]);
  printf("a+b = %d\n", a+b);
  printf("a-b = %d\n", a-b);
  printf("a*b = %d\n", a*b);
  printf("a/b = %d\n", a/b); /* truncates towards 0 (in C99) */
  printf("a%%b = %d\n", a%b); /* same sign as first operand (in C99) */
  return 0;
}


using System;

class Program
{
    static void Main(string[] args)
    {
        int a = Convert.ToInt32(args[0]);
        int b = Convert.ToInt32(args[1]);

        Console.WriteLine("{0} + {1} = {2}", a, b, a + b);
        Console.WriteLine("{0} - {1} = {2}", a, b, a - b);
        Console.WriteLine("{0} * {1} = {2}", a, b, a * b);
        Console.WriteLine("{0} / {1} = {2}", a, b, a / b); // truncates towards 0
        Console.WriteLine("{0} % {1} = {2}", a, b, a % b); // matches sign of first operand
        Console.WriteLine("{0} to the power of {1} = {2}", a, b, Math.Pow(a, b));
    }
}


VAR staticArray: ARRAY [1..10] OF INTEGER;


#include <iostream>

int main()
{
  int a, b;
  std::cin >> a >> b;
  std::cout << "a+b = " << a+b << "\n";
  std::cout << "a-b = " << a-b << "\n";
  std::cout << "a*b = " << a*b << "\n";
  std::cout << "a/b = " << a/b << ", remainder " << a%b << "\n";
  return 0;
}


Number Soup.

Only reads single values.

Ingredients.
1 g Numbers
3 g Water
5 g Soup

Method.
Take Numbers from refrigerator.
Take Soup from refrigerator.
Put Numbers into 1st mixing bowl.
Add Soup into the 1st mixing bowl.
Pour contents of the 1st mixing bowl into 1st baking dish.
Clean 1st mixing bowl.
Put Numbers into 1st mixing bowl.
Remove Soup from 1st mixing bowl.
Pour contents of the 1st mixing bowl into 2nd baking dish.
Clean 1st mixing bowl.
Put Numbers into 1st mixing bowl.
Combine Soup into 1st mixing bowl.
Pour contents of the 1st mixing bowl into 3rd baking dish.
Clean 1st mixing bowl.
Put Numbers into 1st mixing bowl.
Divide Soup into 1st mixing bowl.
Pour contents of the 1st mixing bowl into 4th baking dish.
Clean 1st mixing bowl.
Put Water into 1st mixing bowl.
Verb the Soup.
Combine Numbers into 1st mixing bowl.
Verb the Soup until verbed.
Pour contents of the 1st mixing bowl into 5th baking dish.
Clean 1st mixing bowl.

Serves 5.


// create a fixed-length array (length 10)
arr = array(10)

// assign a value to the first position in the array and then display it
arr[0] = "hello, world!"
println arr[0]

// create a variable-length list
l = list()

// place the numbers 1-10 in the list
for i in range(1,10)
	append l i
end

// display the list
println l


procedure Test( a, b )
   ? "a+b", a + b
   ? "a-b", a - b
   ? "a*b", a * b
   // The quotient isn't integer, so we use the Int() function, which truncates it downward.
   ? "a/b", Int( a / b )
   // Remainder:
   ? "a%b", a % b
   // Exponentiation is also a base arithmetic operation
   ? "a**b", a ** b
   return


(defn myfunc []
  (println "Enter x and y")
  (let [x (read), y (read)]
    (doseq [op '(+ - * / Math/pow rem)]
      (let [exp (list op x y)]
	(printf "%s=%s\n" exp (eval exp))))))


var myArray = $array(1);

$print(myArray[0]);


using System;
using System.Console;
using System.Collections;

module ArrayOps
{
    Main() : void
    {
        def fives = array(10);
        foreach (i in [1 .. 10]) fives[i - 1] = i * 5;
        def ten = fives[1];
        WriteLine($"Ten: $ten");

        def dynamic = ArrayList();
        dynamic.Add(1);
        dynamic.Add(3);
        dynamic[1] = 2;
        foreach (i in dynamic) Write($"$i\t"); // Nemerle isn't great about displaying arrays, it's better with lists though
    }
}


       IDENTIFICATION DIVISION.
       PROGRAM-ID. Int-Arithmetic.

       DATA DIVISION.
       WORKING-STORAGE SECTION.

       01 A      PIC S9(10).
       01 B      PIC S9(10).
       01 Result PIC S9(10).

       PROCEDURE DIVISION.
           DISPLAY "First number: " WITH NO ADVANCING
           ACCEPT A
           DISPLAY "Second number: " WITH NO ADVANCING
           ACCEPT B

*          *> Note: The various ADD/SUBTRACT/etc. statements can be
*          *> replaced with COMPUTE statements, which allow those
*          *> operations to be defined similarly to other languages,
*          *> e.g. COMPUTE Result = A + B

           ADD A TO B GIVING Result
           DISPLAY "A + B = " Result

           SUBTRACT B FROM A GIVING Result
           DISPLAY "A - B = " Result

           MULTIPLY A BY B GIVING Result
           DISPLAY "A * B = " Result

*          *> Division here truncates towards zero. DIVIDE can take a
*          *> ROUNDED clause, which will round the result to the nearest
*          *> integer.
           DIVIDE A BY B GIVING Result
           DISPLAY "A / B = " Result

           COMPUTE Result = A ^ B
           DISPLAY "A ^ B = " Result

*          *> Matches sign of first argument.
           DISPLAY "A % B = " FUNCTION REM(A, B)

           GOBACK
           .


(defun arithmetic (&optional (a (read *query-io*)) (b (read *query-io*)))
  (mapc
    (lambda (op)
      (format t "~a => ~a~%" (list op a b) (funcall (symbol-function op) a b)))
    '(+ - * mod rem floor ceiling truncate round expt))
  (values))


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

array = int[10]
array[0] = 42

say array[0] array[3]
say

words = ['Ogof', 'Ffynnon', 'Ddu']

say words[0] words[1] words[2]
say

-- Dynamic arrays can be simulated via the Java Collections package
splk = ArrayList()
splk.add(words[0])
splk.add(words[1])
splk.add(words[2])
splk.add('Draenen')

say splk.get(0) splk.get(3)
say splk.get(0) splk.get(1) splk.get(2)
say

-- or by using NetRexx "indexed strings" (associative arrays)
cymru = ''
cymru[0] = 0
cymru[0] = cymru[0] + 1; cymru[cymru[0]] = splk.get(0) splk.get(1) splk.get(2)
cymru[0] = cymru[0] + 1; cymru[cymru[0]] = splk.get(0) splk.get(3)

loop x_ = 1 to cymru[0] by 1
  say x_':' cymru[x_]
  end x_


MODULE Arithmetic;
IMPORT CPmain,Console,RTS;

VAR
   x,y	  : INTEGER;
   arg	  : ARRAY 128 OF CHAR;
   status : BOOLEAN;

PROCEDURE Error(IN str : ARRAY OF CHAR);
BEGIN
   Console.WriteString(str);Console.WriteLn;
   HALT(1)
END Error;

BEGIN
   IF CPmain.ArgNumber() < 2 THEN Error("Give me two integers!") END;
   CPmain.GetArg(0,arg); RTS.StrToInt(arg,x,status);
   IF ~status THEN Error("Can't convert 	'"+arg+"' to Integer") END;
   CPmain.GetArg(1,arg); RTS.StrToInt(arg,y,status);
   IF ~status THEN Error("Can't convert '"+arg+"' to Integer") END;
   Console.WriteString("x + y >");Console.WriteInt(x + y,6);Console.WriteLn;
   Console.WriteString("x - y >");Console.WriteInt(x - y,6);Console.WriteLn;
   Console.WriteString("x * y >");Console.WriteInt(x * y,6);Console.WriteLn;
   Console.WriteString("x / y >");Console.WriteInt(x DIV y,6);Console.WriteLn;
   Console.WriteString("x MOD y >");Console.WriteInt(x MOD y,6);Console.WriteLn;
END Arithmetic.


var # fixed size arrays
  x = [1,2,3,4,5,6,7,8,9,10] # type and size automatically inferred
  y: array[1..5, int] = [1,2,3,4,5] # starts at 1 instead of 0
  z: array['a'..'z', int] # indexed using characters

x[0] = x[1] + 1
echo x[0]
echo z['d']

x[7..9] = y[3..5] # copy part of array

var # variable size sequences
  a = @[1,2,3,4,5,6,7,8,9,10]
  b: seq[int] = @[1,2,3,4,5]

a[0] = a[1] + 1
echo a[0]

a.add(b) # append another sequence
a.add(200) # append another element
echo a.pop() # pop last item, removing and returning it
echo a


a = gets.not_nil!.to_i64
b = gets.not_nil!.to_i64

puts "Sum: #{a + b}"
puts "Difference: #{a - b}"
puts "Product: #{a * b}"
puts "Quotient (float division): #{a / b}"  # / always returns a float.
puts "Quotient (floor division): #{a // b}"
puts "Remainder: #{a % b}" # Sign of remainder matches that of the second operand (b).
puts "Power: #{a ** b}"    # Integers can only be raised to a positive exponent.


import std.stdio, std.string, std.conv;

void main() {
    int a = 10, b = 20;
    try {
        a = readln().strip().to!int();
        b = readln().strip().to!int();
    } catch (StdioException e) {}
    writeln("a = ", a, ", b = ", b);

    writeln("a + b = ", a + b);
    writeln("a - b = ", a - b);
    writeln("a * b = ", a * b);
    writeln("a / b = ", a / b);
    writeln("a % b = ", a % b);
    writeln("a ^^ b = ", a ^^ b);
}


!include NSISArray.nsh
Function ArrayTest
	Push $0
	; Declaring an array
	NSISArray::New TestArray 1 2
	NSISArray::Push TestArray "Hello"
	; NSISArray arrays are dynamic by default.
	NSISArray::Push TestArray "World"
	NSISArray::Read TestArray 1
	Pop $0
	DetailPrint $0
	Pop $0
FunctionEnd


[Enter 2 integers on 1 line.
  Use whitespace to separate. Example: 2 3
  Use underscore for negative integers. Example: _10
]P ? sb sa
[add: ]P la lb + p sz
[sub: ]P la lb - p sz
[mul: ]P la lb * p sz
[div: ]P la lb / p sz  [truncates toward zero]sz
[mod: ]P la lb % p sz  [sign matches first operand]sz
[pow: ]P la lb ^ p sz


$ inquire a "Enter first number"
$ a = f$integer( a )
$ inquire b "Enter second number"
$ b = f$integer( b )
$ write sys$output "a + b = ", a + b
$ write sys$output "a - b = ", a - b
$ write sys$output "a * b = ", a * b
$ write sys$output "a / b = ", a / b  ! truncates down


MODULE Arrays;
IMPORT
  Out;

  PROCEDURE Static;
  VAR
    x: ARRAY 5 OF LONGINT;
  BEGIN
    x[0] := 10;
    x[1] := 11;
    x[2] := 12;
    x[3] := 13;
    x[4] := x[0];

    Out.String("Static at 4: ");Out.LongInt(x[4],0);Out.Ln;
  END Static;

  PROCEDURE Dynamic;
  VAR
    x: POINTER TO ARRAY OF LONGINT;
  BEGIN
    NEW(x,5);

    x[0] := 10;
    x[1] := 11;
    x[2] := 12;
    x[3] := 13;
    x[4] := x[0];

    Out.String("Dynamic at 4: ");Out.LongInt(x[4],0);Out.Ln;
  END Dynamic;

BEGIN
  Static;
  Dynamic
END Arrays.


program IntegerArithmetic;

{$APPTYPE CONSOLE}

uses SysUtils, Math;

var
  a, b: Integer;
begin
  a := StrToInt(ParamStr(1));
  b := StrToInt(ParamStr(2));

  WriteLn(Format('%d + %d = %d', [a, b, a + b]));
  WriteLn(Format('%d - %d = %d', [a, b, a - b]));
  WriteLn(Format('%d * %d = %d', [a, b, a * b]));
  WriteLn(Format('%d / %d = %d', [a, b, a div b])); // rounds towards 0
  WriteLn(Format('%d %% %d = %d', [a, b, a mod b])); // matches sign of the first operand
  WriteLn(Format('%d ^ %d = %d', [a, b, Trunc(Power(a, b))]));
end.


bundle Default {
  class Arithmetic {
    function : Main(args : System.String[]), Nil {
      array := Int->New[2];
      array[0] := 13;
      array[1] := 7;
      (array[0] + array[1])->PrintLine();
    }
  }
}


var a := StrToInt(ParamStr(0));
var b := StrToInt(ParamStr(1));

PrintLn(Format('%d + %d = %d', [a, b, a + b]));
PrintLn(Format('%d - %d = %d', [a, b, a - b]));
PrintLn(Format('%d * %d = %d', [a, b, a * b]));
PrintLn(Format('%d / %d = %d', [a, b, a div b]));
PrintLn(Format('%d mod %d = %d', [a, b, a mod b]));
PrintLn(Format('%d ^ %d = %d', [a, b, Trunc(Power(a, b))]));


// NSArrays are ordered collections of NSObject subclasses only.

// Create an array of NSString objects.
NSArray *firstArray = [[NSArray alloc] initWithObjects:@"Hewey", @"Louie", @"Dewey", nil];

// NSArrays are immutable; it does have a mutable subclass, however - NSMutableArray.
// Let's instantiate one with a mutable copy of our array.
// We can do this by sending our first array a -mutableCopy message.
NSMutableArray *secondArray = [firstArray mutableCopy];

// Replace Louie with Launchpad McQuack.
[secondArray replaceObjectAtIndex:1 withObject:@"Launchpad"];

// Display the first object in the array.
NSLog(@"%@", [secondArray objectAtIndex:0]);

// In non-ARC or non-GC environments, retained objects must be released later.
[firstArray release];
[secondArray release];

// There is also a modern syntax which allows convenient creation of autoreleased immutable arrays.
// No nil termination is then needed.
NSArray *thirdArray = @[ @"Hewey", @"Louie", @"Dewey", @1, @2, @3 ];


let a = 6
let b = 4

print("sum = \(a+b)")
print("difference = \(a-b)")
print("product = \(a*b)")
print("Integer quotient = \(a/b)")
print("Remainder = \(a%b)")


def arithmetic(a :int, b :int) {
  return `$\
   Sum:        ${a + b}
   Difference: ${a - b}
   Product:    ${a * b}
   Quotient:   ${a // b}
   Remainder:  ${a % b}$\n`
}


a = number input
b = number input
print a + b
print a - b
print a * b
print a div b
print a mod b
print pow a b


ArithmeticDemo(INTEGER A,INTEGER B) := FUNCTION
  ADDit       := A + B;
  SUBTRACTit  := A - B;
  MULTIPLYit  := A * B;
  INTDIVIDEit := A DIV B; //INTEGER DIVISION
  DIVIDEit    := A / B;   //standard division
  Remainder   := A % B;
  EXPit       := POWER(A,B);
  DS          := DATASET([{A,B,'A PLUS B is:',ADDit},
                          {A,B,'A MINUS B is:',SUBTRACTit},
			  {A,B,'A TIMES B is:',MULTIPLYit},
			  {A,B,'A INT DIVIDE BY B is:',INTDIVIDEit},
			  {A,B,'REMAINDER is:',Remainder},
			  {A,B,'A DIVIDE BY B is:',DIVIDEit},
			  {A,B,'A RAISED TO B:',EXPit}],
			  {INTEGER AVal,INTEGER BVal,STRING18 valuetype,STRING val});

  RETURN DS;
  END;

ArithmeticDemo(1,1);
ArithmeticDemo(2,2);
ArithmeticDemo(50,5);
ArithmeticDemo(10,3);
ArithmeticDemo(-1,2);

/* 	NOTE:Division by zero defaults to generating a zero result (0),
   	rather than reporting a “divide by zero” error.
   	This avoids invalid or unexpected data aborting a long job.
   	This default behavior can be changed
*/


[ "abd", "def", "ghi" ] at( 3 ) .

Array new dup addAll( [1, 2, 3] ) dup put( 2, 8.1 ) .


; making a vector
> #(1 2 3 4 5)
#(1 2 3 4 5)

; making a vector in a functional way
> (vector 1 2 3 4 5)
#(1 2 3 4 5)

; another functional vector making way
> (make-vector '(1 2 3 4 5))
#(1 2 3 4 5)

; the same as above functional vector making way
> (list->vector '(1 2 3 4 5))
#(1 2 3 4 5)

; modern syntax of making a vector
> [1 2 3 4 5]
#(1 2 3 4 5)

; making a vector of symbols
> '[a b c d e]
#(a b c d e)

; making a vector of symbols but evaluate a third element
> `[a b ,(* 7 13) d e]
#(a b 91 d e)

; making an empty vectors
> #()
#()

> []
#()

> '[]
#()

> `[]
#()

> (make-vector '())
#()

> (list->vector '())
#()

; making a vector of a vectors (a matrix, for example)
> [[1 2 3]
   [4 5 6]
   [7 8 9]]
#(#(1 2 3) #(4 5 6) #(7 8 9))

; getting length of a vector
> (size [1 2 3 4 5])
5

; making n-length vector with undefined values (actually, #false)
> (make-vector 5)
#(#false #false #false #false #false)

; making n-length vector with default values
> (make-vector 5 0)
#(0 0 0 0 0)

; define a test vector for use in below
> (define array [3 5 7 9 11])
;; Defined array

; getting first element of a vector
> (ref array 1)
3

> (ref array (- (size array)))
3

; getting last element of a vector
> (ref array (size array))
11

> (ref array -1)
11

; vectors comparison
> (equal? [1 2 3 4 5] [1 2 3 4 5])
#true

> (equal? [1 2 3 4 5] [7 2 3 4 5])
#false

; vectors of vectors comparison
> (equal?
   [[1 2 3]
    [4 5 6]
    [7 8 9]]
   [[1 2 3]
    [4 5 6]
    [7 8 9]])
#true

> (equal?
   [[1 2 3]
    [4 5 6]
    [7 8 9]]
   [[1 2 3]
    [4 5 6]
    [7 8 3]])
#false


@public
run = fn () {

    First = io.get_line("First number: ")
    Second = io.get_line("Second number: ")

    A = list_to_integer(lists.delete($\n, First))
    B = list_to_integer(lists.delete($\n, Second))

    io.format("Sum: ~p~n", [A + B])
    io.format("Difference: ~p~n", [A - B])
    io.format("Product: ~p~n", [A * B])
    io.format("Quotient: ~p~n", [A / B])
    io.format("Remainder: ~p~n", [A % B])
}


class MAIN
    creation make
    feature make is
        local
            a, b: REAL;
        do
            print("a = ");
            io.read_real;
            a := io.last_real;

            print("b = ");
            io.read_real;
            b := io.last_real;

            print("a + b = ");
            io.put_real(a + b);
            print("%Na - b = ");
            io.put_real(a - b);
            print("%Na * b = ");
            io.put_real(a * b);
            print("%Na / b = ");
            io.put_real(a / b);
            print("%Na %% b = ");
            io.put_real(((a / b) - (a / b).floor) * b);
            print("%Na ^ b = ");
            io.put_real(a.pow(b));
            print("%N");
        end
end


   a = .array~new       -- create a zero element array
   b = .array~new(10)   -- create an array with initial size of 10
   c = .array~of(1, 2, 3)  -- create a 3 element array holding objects 1, 2, and 3
   a[3] = "Fred"        -- assign an item
   b[2] = a[3]          -- retrieve an item from the array
   c~append(4)          -- adds to end.  c[4] == 4 now


'CREATING A STATIC ARRAY
float f[100]

'SETTING INDEX BASE
indexbase 1 'default

'FILLING PART OF AN ARRAY
f[20]={2,4,6,8,10,12}

'MAPPING AN ARRAY TO ANOTHER
float *g
@[email protected][20]
print g[6] 'result 12

'DYNAMIC (RESIZEABLE) ARRAYS
redim float f(100)
f={2,4,6,8}               'assign some values
redim float f(200)        'expand array
print f(2)                'original values are preserved by default
redim float f(200) clear  'array elements are cleared
print f(2)                'value set to 0.0
redim float f(0)          'release allocated memory          '


import system'math;
import extensions;

public program()
{
    var a := console.loadLineTo(new Integer());
    var b := console.loadLineTo(new Integer());

    console.printLine(a," + ",b," = ",a + b);
    console.printLine(a," - ",b," = ",a - b);
    console.printLine(a," * ",b," = ",a * b);
    console.printLine(a," / ",b," = ",a / b);   // truncates towards 0
    console.printLine(a," % ",b," = ",a.mod:b); // matches sign of first operand
    console.printLine(a," ^ ",b," = ",a ^ b);
}


defmodule Arithmetic_Integer do
  # Function to remove line breaks and convert string to int
  defp get_int(msg) do
    IO.gets(msg) |> String.strip |> String.to_integer
  end

  def task do
    # Get user input
    a = get_int("Enter your first integer: ")
    b = get_int("Enter your second integer: ")

    IO.puts "Elixir Integer Arithmetic:\n"
    IO.puts "Sum:            #{a + b}"
    IO.puts "Difference:     #{a - b}"
    IO.puts "Product:        #{a * b}"
    IO.puts "True Division:  #{a / b}"                  # Float
    IO.puts "Division:       #{div(a,b)}"               # Truncated Towards 0
    IO.puts "Floor Division: #{Integer.floor_div(a,b)}" # floored integer division
    IO.puts "Remainder:      #{rem(a,b)}"               # Sign from first digit
    IO.puts "Modulo:         #{Integer.mod(a,b)}"       # modulo remainder (uses floored division)
    IO.puts "Exponent:       #{:math.pow(a,b)}"         # Float, using Erlang's :math
  end
end

Arithmetic_Integer.task


declare
  Arr = {Array.new 1   %% lowest index
                   10  %% highest index
                   37} %% all 10 fields initialized to 37
in
  {Show Arr.1}
  Arr.1 := 64
  {Show Arr.1}


🏁🍇
  🍺🔢🆕🔡▶👂🏼❗ 10❗ ➡ x 💭 Get first number
  🍺🔢🆕🔡▶👂🏼❗ 10❗ ➡ y 💭 Get second number
  😀 🔤Sum: 🧲x➕y🧲🔤 ❗
  😀 🔤Difference: 🧲x➖y🧲🔤 ❗
  😀 🔤Product: 🧲x✖y🧲🔤 ❗
  😀 🔤Quotient: 🧲x➗y🧲🔤 ❗ 💭 Rounds towards 0
  😀 🔤Remainder: 🧲x🚮y🧲🔤 ❗ 💭 Matches sign of first operand
🍉


% Implemented by Arjun Sunel
-module(arith).
-export([start/0]).

start() ->
   case io:fread("","~d~d") of
       {ok, [A,B]} ->
           io:format("Sum = ~w~n",[A+B]),
           io:format("Difference = ~w~n",[A-B]),
           io:format("Product = ~w~n",[A*B]),
           io:format("Quotient = ~w~n",[A div B]),      % truncates towards zero
           io:format("Remainder= ~w~n",[A rem B]),    % same sign as the first operand
           halt()
   end.


Program ArrayDemo;
uses
  SysUtils;
var
  StaticArray: array[0..9] of Integer;
  DynamicArray: array of Integer;
  StaticArrayText,
  DynamicArrayText: string;
  lcv: Integer;
begin
  // Setting the length of the dynamic array the same as the static one
  SetLength(DynamicArray, Length(StaticArray));
  // Asking random numbers storing into the static array
  for lcv := 0 to Pred(Length(StaticArray)) do
  begin
    write('Enter a integer random number for position ', Succ(lcv), ': ');
    readln(StaticArray[lcv]);
  end;
  // Storing entered numbers of the static array in reverse order into the dynamic
  for lcv := 0 to Pred(Length(StaticArray)) do
    DynamicArray[Pred(Length(DynamicArray)) - lcv] := StaticArray[lcv];
  // Concatenating the static and dynamic array into a single string variable
  StaticArrayText := '';
  DynamicArrayText := '';
  for lcv := 0 to Pred(Length(StaticArray)) do
  begin
    StaticArrayText := StaticArrayText + IntToStr(StaticArray[lcv]) + ' ';
    DynamicArrayText := DynamicArrayText + IntToStr(DynamicArray[lcv]) + ' ';
  end;
  // Displaying both arrays
  writeln(StaticArrayText);
  writeln(DynamicArrayText);
end.


PROGRAM INTEGER_ARITHMETIC

!
! for rosettacode.org
!

!$INTEGER

BEGIN
  INPUT("Enter a number ",A)
  INPUT("Enter another number ",B)

  PRINT("Addition ";A;"+";B;"=";(A+B))
  PRINT("Subtraction ";A;"-";B;"=";(A-B))
  PRINT("Multiplication ";A;"*";B;"=";(A*B))
  PRINT("Integer division ";A;"div";B;"=";(A DIV B))
  PRINT("Remainder or modulo ";A;"mod";B;"=";(A MOD B))
  PRINT("Power ";A;"^";B;"=";(A^B))
END PROGRAM


include get.e

integer a,b

a = floor(prompt_number("a = ",{}))
b = floor(prompt_number("b = ",{}))

printf(1,"a + b = %d\n", a+b)
printf(1,"a - b = %d\n", a-b)
printf(1,"a * b = %d\n", a*b)
printf(1,"a / b = %g\n", a/b) -- does not truncate
printf(1,"remainder(a,b) = %d\n", remainder(a,b)) -- same sign as first operand
printf(1,"power(a,b) = %g\n", power(a,b))


 my @empty;
 my @empty_too = ();

 my @populated   = ('This', 'That', 'And', 'The', 'Other');
 print $populated[2];  # And

 my $aref = ['This', 'That', 'And', 'The', 'Other'];
 print $aref->[2];  # And


-- simple one-dimensional arrays:
sequence s1 = {0.5, 1, 4.7, 9}, -- length(s1) is now 4
         s2 = repeat(0,6),     -- s2 is {0,0,0,0,0,0}
         s3 = tagset(5)         -- s3 is {1,2,3,4,5}

    ?s1[3]      -- displays 4.7 (nb 1-based indexing)
    s1[3] = 0   -- replace that 4.7
    s1 &= {5,6} -- length(s1) is now 6 ({0.5,1,0,9,5,6})
    s1 = s1[2..5]   -- length(s1) is now 4 ({1,0,9,5})
    s1[2..3] = {2,3,4} -- length(s1) is now 5 ({1,2,3,4,5})
    s1 = append(s1,6)   -- length(s1) is now 6 ({1,2,3,4,5,6})
    s1 = prepend(s1,0)  -- length(s1) is now 7 ({0,1,2,3,4,5,6})

-- negative subscripts can also be used, counting from the other end, eg
    s2[-2..-1] = {-2,-1}    -- s2 is now {0,0,0,0,-2,-1}

-- multi dimensional arrays:
sequence y = {{{1,1},{3,3},{5,5}},
              {{0,0},{0,1},{9,1}},
              {{1,7},{1,1},{2,2}}}
    -- y[2][3][1] is 9

         y = repeat(repeat(repeat(0,2),3),3)
    -- same structure, but all 0s

-- Array of strings:
sequence s = {"Hello", "World", "Phix", "", "Last One"}
    -- s[3] is "Phix"
    -- s[3][2] is 'h'

-- A Structure:
sequence employee = {{"John","Smith"},
                     45000,
                     27,
                     185.5}

-- To simplify access to elements within a structure it is good programming style to define constants that name the various fields, eg:
    constant SALARY = 2

-- Array of structures:
sequence employees = {
                      {{"Jane","Adams"}, 47000, 34, 135.5},  -- a[1]
                      {{"Bill","Jones"}, 57000, 48, 177.2},  -- a[2]
                      -- .... etc.
                     }
    -- employees[2][SALARY] is 57000

-- A tree can be represented easily, for example after adding "b","c","a" to it you might have:
sequence tree = {{"b",3,2},
                 {"c",0,0},
                 {"a",0,0}}

-- ie assuming
constant ROOT=1, VALUE=1, LEFT=2, RIGHT=3 -- then
--  tree[ROOT][VALUE] is "b"
--  tree[ROOT][LEFT] is 3, and tree[3] is the "a"
--  tree[ROOT][RIGHT] is 2, and tree[2] is the "c"

-- The operations you might use to build such a tree (tests/loops/etc omitted) could be:
    tree = {}
    tree = append(tree,{"b",0,0})
    tree = append(tree,{"c",0,0})
    tree[1][RIGHT] = length(tree)
    tree = append(tree,{"a",0,0})
    tree[1][LEFT] = length(tree)

-- Finally, some tests (recall that we have already output a 4.7):
?s[3]
?tree
?tree[ROOT][VALUE]
employees = append(employees, employee)
?employees[3][SALARY]
?s1
?s2


USING: combinators io kernel math math.functions math.order
math.parser prettyprint ;

"a=" "b=" [ write readln string>number ] [email protected]
{
    [ + "sum: " write . ]
    [ - "difference: " write . ]
    [ * "product: " write . ]
    [ / "quotient: " write . ]
    [ /i "integer quotient: " write . ]
    [ rem "remainder: " write . ]
    [ mod "modulo: " write . ]
    [ max "maximum: " write . ]
    [ min "minimum: " write . ]
    [ gcd "gcd: " write . drop ]
    [ lcm "lcm: " write . ]
} 2cleave


12 7
\[email protected][email protected][email protected][email protected][email protected][email protected][email protected][email protected][email protected][email protected]\  { 6 copies }
"sum = "+."
difference = "-."
product = "*."
quotient = "/."
modulus = "/*-."
"


?a;
?b;
!!('Sum:              a+b=',a+b);
!!('Difference:       a-b=',a-b);
!!('Product:          a*b=',a*b);
!!('Integer quotient: a\b=',a\b);
!!('Remainder:        a|b=',a|b);
!!('Exponentiation:   a^b=',a^b);


include ..\Utilitys.pmt

0 tolist            /# create an empty array/list. '( )' is equivalent #/
drop                /# remove top of the stack #/
0 10 repeat         /# put an array/list of 10 elements (each element has value 0) to the stack #/
flush               /# remove all elements. List is empty [] #/
drop
( 1 2 "Hello" pi )  /# put an initialize array/list to stack #/
-7 1 set            /# modified first element to -7 #/
0 get               /# get the last element. '-1 get' is equivalent #/
drop
( "next" "level" ) 2 put    /# insert a list in a list = [-7, ["next", "level"], 2, "Hello", 3.141592653589793]] #/
3 2 slice           /# extract the subarray/sublist [ 2 "Hello" ] #/

pstack              /# show the content of the stack #/


$NumberArray = array(0, 1, 2, 3, 4, 5, 6);
$LetterArray = array("a", "b", "c", "d", "e", "f");
$simpleForm = ['apple', 'orange'];


: arithmetic ( a b -- )
  cr ." a=" over . ." b=" dup .
  cr ." a+b=" 2dup + .
  cr ." a-b=" 2dup - .
  cr ." a*b=" 2dup * .
  cr ." a/b=" /mod .
  cr ." a mod b = " . cr ;


 INTEGER A, B
 PRINT *, 'Type in two integer numbers separated by white space',
+         ' and press ENTER'
 READ *, A, B
 PRINT *, '   A + B = ', (A + B)
 PRINT *, '   A - B = ', (A - B)
 PRINT *, '   A * B = ', (A * B)
 PRINT *, '   A / B = ', (A / B)
 PRINT *, 'MOD(A,B) = ', MOD(A,B)
 PRINT *
 PRINT *, 'Even though you did not ask, ',
+         'exponentiation is an intrinsic op in Fortran, so...'
 PRINT *, '  A ** B = ', (A ** B)
 END


import util.

go =>

   % Create an array of length 10
   Len = 10,
   A = new_array(Len),
   bind_vars(A,0), % Initialize all values to 0
   println(a=A),
   A[1] := 1, % Assign a value
   println(a=A),
   println(a1=A[1]), % print first element
   % (re)assign a value
   foreach(I in 1..Len) A[I] := I end,
   println(A[3..7]), % print some interval of an array
   nl,

   % 2D arrays
   A2 = new_array(4,4),
   foreach(I in 1..4, J in 1..4)
     A2[I,J] := (I-1)*4+J
   end,
   foreach(Row in A2) println(Row) end,

   % These functions are defined in the util module.
   % They returns lists so we have to convert them to arrays.
   println('rows     '=to_array(A2.rows)),
   println('columns  '=A2.columns.to_array),
   println(diagonal1=A2.diagonal1.to_array),
   println(diagonal2=A2.diagonal2.to_array),

   nl,

   % Pushing values to an array
   A3 = {}, % an empty array
   foreach(I in 1..4)
     A3 := A3 ++ {10**I+I}
   end,
   println(a3=A3),
   nl,

   % Some misc functions
   println([first=A3.first(), second=A3.second(),last=A3.last()]),

   nl.


(setq A '((1 2 3) (a b c) ((d e) NIL 777)))  # Create a 3x3 structure
(mapc println A)  # Show it


' FB 1.05.0 Win64

Dim As Integer i, j
Input "Enter two integers separated by a comma"; i, j
Print i;" + "; j; " = "; i + j
Print i;" - "; j; " = "; i - j
Print i;" * "; j; " = "; i * j
Print i;" / "; j; " = "; i \ j
Print i;" % "; j; " = "; i Mod j
Print i;" ^ "; j; " = "; i ^ j
Sleep

' Integer division (for which FB uses the '\' operator) rounds towards zero

' Remainder (for which FB uses the Mod operator) will, if non-zero, match the sign
' of the first operand


read a
read b
echo 'a + b =' (math "$a + $b") # Sum
echo 'a - b =' (math "$a - $b") # Difference
echo 'a * b =' (math "$a * $b") # Product
echo 'a / b =' (math "$a / $b") # Integer quotient
echo 'a % b =' (math "$a % $b") # Remainder
echo 'a ^ b =' (math "$a ^ $b") # Exponentation


int main(){
   // Initial array, few random elements.
   array arr = ({3,"hi",84.2});

   arr += ({"adding","to","the","array"}); // Lets add some elements.

   write(arr[5] + "\n"); // And finally print element 5.
}


/* Example of an array having fixed dimensions */
declare A(10) float initial (1, 9, 4, 6, 7, 2, 5, 8, 3, 10);

A(6) = -45;

/* Example of an array having dynamic bounds. */
get list (N);

begin;
   declare B(N) float initial (9, 4, 7, 3, 8, 11, 0, 5, 15, 6);
   B(3) = -11;
   put (B(2));
end;

/* Example of a dynamic array. */
   declare C(N) float controlled;
   get list (N);
   allocate C;
   C = 0;
   c(7) = 12;
   put (C(9));


[a,b] = input["Enter numbers",["a","b"]]
ops=["+", "-", "*", "/", "div" ,"mod" ,"^"]
for op = ops
{
   str = "$a $op $b"
   println["$str = " + eval[str]]
}


window 1, @"Integer Arithmetic", ( 0, 0, 400, 300 )

NSInteger a = 25
NSInteger b = 53

print "addition        "a" + "b" = " (a + b)
print "subtraction     "a" - "b" = " (a - b)
print "multiplication  "a" * "b" = " (a * b)
print "division        "a" / "b" = " (a / b)
printf @"float division  %ld / %ld = %f", a, b, (float)a / (float)b
print "modulo          "a" % "b" = " (a mod b)
print "power           "a" ^ "b" = " (a ^ b)

HandleEvents


Public Sub Main()
  Dim a, b As String
  Dim c, d As Integer

  Print "Enter two integer numbers, separated by space:"
  Input a, b

  c = CInt(a)
  d = CInt(b)

  Print "Sum: " & (c + d)
  Print "Difference:" & (c - d)
  Print "Product: " & (c * d)
  Print "Integer: " & (c Div d)
  Print "Remainder: " & (c Mod d)
  Print "Exponentiation: " & (c ^ d)

End


To run:
Start up.
Write "Creating an array of 100 numbers..." on the console.
Create a number array given 100.
Write "Putting 1 into the array at index 0." on the console.
Put 1 into the number array at 0.
Write "Putting 33 into the array at index 50." on the console.
Put 33 into the number array at 50.
Write "Retrieving value from array at index 0... " on the console without advancing.
Get a number from the number array at 0.
Write "" then the number on the console.
Write "Retrieving value from array at index 50... " on the console without advancing.
Get another number from the number array at 50.
Write "" then the other number on the console.
Write "Retrieving value from array at index 99... " on the console without advancing.
Get a third number from the number array at 99.
Write "" then the third number on the console.
Destroy the number array.
Wait for the escape key.
Shut down.

\\\\\\\\\\\\\\\\\\ Array implementation \\\\\\\\\\\\\\\\\\\\

A number array has a first element pointer.

A location is a number.

To create a number array given a count:
Put a number's magnitude times the count into a size.
Assign the number array's first element pointer given the size. \ allocate memory for the array

To destroy a number array:
Unassign the number array's first element pointer. \ free the array's memory

To get a number from a number array at a location:
Put the location times the number's magnitude into an offset.
Put the number array's first element pointer into a number pointer.
Add the offset to the number pointer.
Put the number pointer's target into the number.

To put a number into a number array at a location:
Put the location times the number's magnitude into an offset.
Put the number array's first element pointer into a number pointer.
Add the offset to the number pointer.
Put the number into the number pointer's target.


use "assert"      // due to the use of Fact

- - -

var numbers = Array[I32](16) // creating array of 32-bit ints with initial allocation for 16 elements
numbers.push(10) // add value 10 to the end of array, extending the underlying memory if needed
try
  let x = numbers(0) // fetch the first element of array. index starts at 0
  Fact(x == 10)      // try block is needed, because both lines inside it can throw exception
end

var other: Array[U64] = [10, 20, 30] // array literal
let s = other.size() // return the number of elements in array
try
  Fact(s == 3)  // size of array 'other' is 3
  other(1) = 40 // 'other' now is [10, 40, 30]
end


run := function()
  local a, b, f;
  f := InputTextUser();
  Print("a =\n");
  a := Int(Chomp(ReadLine(f)));
  Print("b =\n");
  b := Int(Chomp(ReadLine(f)));
  Display(Concatenation(String(a), " + ", String(b), " = ", String(a + b)));
  Display(Concatenation(String(a), " - ", String(b), " = ", String(a - b)));
  Display(Concatenation(String(a), " * ", String(b), " = ", String(a * b)));
  Display(Concatenation(String(a), " / ", String(b), " = ", String(QuoInt(a, b)))); # toward 0
  Display(Concatenation(String(a), " mod ", String(b), " = ", String(RemInt(a, b)))); # nonnegative
  Display(Concatenation(String(a), " ^ ", String(b), " = ", String(a ^ b)));
  CloseStream(f);
end;


[indent=4]
/*
   Arithmethic/Integer, in Genie
   valac arithmethic-integer.gs
*/

init:int
    a:int = 0
    b:int = 0
    if args.length > 2 do b = int.parse(args[2])
    if args.length > 1 do a = int.parse(args[1])

    print @"a+b: $a plus  $b is $(a+b)"
    print @"a-b: $a minus $b is $(a-b)"
    print @"a*b: $a times $b is $(a*b)"
    print @"a/b: $a by    $b quotient is  $(a/b)  (rounded mode is TRUNCATION)"
    print @"a%b: $a by    $b remainder is $(a%b)  (sign matches first operand)"

    print "\nGenie does not include a raise to power operator"

    return 0


%Declaring array

/x [0 1] def

%Assigning value to an element, PostScript arrays are 0 based.

x 0 3 put

%Print array

x pstack
[3 1]

%Get an element

x 1 get


R (m) ;
R (n) ;
m n + P;
m n - P;
m n × P;
m n div P;
m n rem P;


package main

import "fmt"

func main() {
    var a, b int
    fmt.Print("enter two integers: ")
    fmt.Scanln(&a, &b)
    fmt.Printf("%d + %d = %d\n", a, b, a+b)
    fmt.Printf("%d - %d = %d\n", a, b, a-b)
    fmt.Printf("%d * %d = %d\n", a, b, a*b)
    fmt.Printf("%d / %d = %d\n", a, b, a/b)  // truncates towards 0
    fmt.Printf("%d %% %d = %d\n", a, b, a%b) // same sign as first operand
    // no exponentiation operator
}


singleassignment:-
    functor(Array,array,100), % create a term with 100 free Variables as arguments
                              % index of arguments start at 1
    arg(1 ,Array,a),          % put an a at position 1
    arg(12,Array,b),          % put an b at position 12
    arg(1 ,Array,Value1),     % get the value at position 1
    print(Value1),nl,         % will print Value1 and therefore a followed by a newline
    arg(4 ,Array,Value2),     % get the value at position 4 which is a free Variable
    print(Value2),nl.         % will print that it is a free Variable followed by a newline


  ;Set up an Array of 23 cells, e.g. 0-22
Dim MyArray.i(22)
  MyArray(0) = 7
  MyArray(1) = 11
  MyArray(7) = 23


def arithmetic = { a, b ->
    println """
       a + b =        ${a} + ${b} = ${a + b}
       a - b =        ${a} - ${b} = ${a - b}
       a * b =        ${a} * ${b} = ${a * b}
       a / b =        ${a} / ${b} = ${a / b}   !!! Converts to floating point!
(int)(a / b) = (int)(${a} / ${b}) = ${(int)(a / b)}              !!! Truncates downward after the fact
 a.intdiv(b) =  ${a}.intdiv(${b}) = ${a.intdiv(b)}              !!! Behaves as if truncating downward, actual implementation varies
       a % b =        ${a} % ${b} = ${a % b}

Exponentiation is also a base arithmetic operation in Groovy, so:
      a ** b =       ${a} ** ${b} = ${a ** b}
"""
}


procedure Test( a, b )
   ? "a+b", a + b
   ? "a-b", a - b
   ? "a*b", a * b
   // The quotient isn't integer, so we use the Int() function, which truncates it downward.
   ? "a/b", Int( a / b )
   // Remainder:
   ? "a%b", a % b
   // Exponentiation is also a base arithmetic operation
   ? "a**b", a ** b
   return


array = []

array.append(1)
array.append(3)

array[0] = 2

print array[0]


'Task
'Show basic array syntax in your language.

'Basically, create an array, assign a value to sit, and retrieve an element   (if available, show both fixed-length arrays and dynamic arrays, pushing a value into it).
Rem  DECLARATION PART

Rem QB64/QuickBasic/Qbasic array examples
'-----------
MyArray%(10) = 11 ' it creates an array integer of 11 elements  from 0 to 11
Dim MyArray2%(0 To 10) ' it is equal to the previous line of code, it is its explicit way

'--------------
Option Base 1 ' from here all arrays have as default as index of first item 1
MyArray3%(10) = 14 'it creates array from 1 to 14

Dim Myarray4%(1 To 14) ' it is equal to the 2 previous lines of code

'-----------------
Dim Shared myArray$(-12 To 12) ' it creates a string array with 25 elements and SHARED makes it global array

'---------------------
'$dynamic
Dim MyArray1!(1 To 4) ' these two lines of code create a resizable array

ReDim myArray2!(1 To 4) ' it does the same of the 2 previous lines of code

'-------------------------
' alternatively at the place of suffix ! or $ or % or # or &
' you can use the explicit way  "DIM namearray (start to end) AS TypeOfVariable"
Dim MyIntegerArray(1 To 10) As Integer
Dim MyStringArray(1 To 10) As String
Dim MySingleArray(1 To 10) As Single
Dim MyLongArray(1 To 10) As Long
Dim MyDoubleArray(1 To 10) As Double

'---------------------------
'it is possible defining an User Data Type and creating an array with that type
Type MyType
    Name As String * 8 ' a fixed lenght string variable
    ID As Integer
    Position As Single
End Type

Dim Lists(1 To 10) As MyType
ReDim WhoIs(-19 To 10) As MyType

'------------------------------
' Number of dimensions of an array: QuickBasic vs QB64
' an array can have from 1 to until 60 dimensions in QuickBasic
' an array can have from 1 to RAM dimension of your machine
' you must think that in the dayly practice is rare to use more than 3 dimensions
Dim Calendar%(1 To 31, 1 To 56, 1 To 12) ' array calendar with days, week, mounths
ReDim Time(1 To 60, 1 To 60, 1 To 24) As Integer ' array Time with seconds, minutes and hours

Rem  ONLY QB64 arrays
'--------
' QB64 introduces more TypeOfVariable all of them associated to a suffix
' so you can declare also these kind of data
' _BIT  or `, _BYTE or %%, _INTEGER64 or &&, _FLOAT or ##, OFFSET or %&, _MEM (no suffix)
Dim MyByteArray%%(1 To 4)
Dim MyByteArray2(1 To 4) As _Byte
' are the same declaration of the array

'----------------
'QB64 lets you to use an alternative way to declare variables and array
'using the following syntax:   DIM / REDIM  AS Type of data  Array1, Array2, Array3"
ReDim As _MEM Mem1(1 To 5), Mem2(6 To 10)
Dim As _Unsigned _Byte UByte(-3 To 25), Ubyte2(100 To 200)

Rem QB64 / QB PDS (7.1) arrays
ReDim MyPreservedArray(1 To 5) As Integer ' it creates a dynamic array
ReDim _Preserve MyPreservedArray(-3 To 100) As Integer ' it changes limit of dimension of array

Rem ASSIGNING PART
' at declaration point each array is initializated: 0 for digit arrays, "" for string arrays
' in the UDT arrays each variable is initializated following its type

' all types of array can be accessed using the index of item choice to change
' in the UDT array each item of UDT is reached using the "." while the item of array needs the index
Print MyPreservedArray(2)
MyPreservedArray(2) = 12345
Print MyPreservedArray(2)

Print WhoIs(-10).Name
WhoIs(-10).Name = "QB64"
Print WhoIs(-10).Name
WhoIs(10).Name = WhoIs(-10).Name
Print WhoIs(10).Name

Rem RETRIEVE AN ELEMENT
' basically the coder must use a loop for scanning the whole array for that value choosen

'-----------------
' static array
MySingleArray(4) = 4
MySingleArray(8) = 8
For n = 1 To 10
    If MySingleArray(n) > 0 Then Print MySingleArray(n)
Next

'dynamic array

WhoIs(-10).Name = "QB64"
WhoIs(10).Name = "C#"
WhoIs(1).Name = "Java"
Print WhoIs(-10).Name, WhoIs(10).Name, WhoIs(1).Name
ReDim _Preserve WhoIs(-10 To 19) As MyType
Print
Print WhoIs(-10).Name, WhoIs(10).Name, WhoIs(1).Name
Print WhoIs(-1).Name, WhoIs(19).Name, WhoIs(10).Name


main = do
  a <- readLn :: IO Integer
  b <- readLn :: IO Integer
  putStrLn $ "a + b = " ++ show (a + b)
  putStrLn $ "a - b = " ++ show (a - b)
  putStrLn $ "a * b = " ++ show (a * b)
  putStrLn $ "a to the power of b = " ++ show (a ** b)
  putStrLn $ "a to the power of b = " ++ show (a ^ b)
  putStrLn $ "a to the power of b = " ++ show (a ^^ b)
  putStrLn $ "a `div` b = "  ++ show (a `div` b)  -- truncates towards negative infinity
  putStrLn $ "a `mod` b = "  ++ show (a `mod` b)  -- same sign as second operand
  putStrLn $ "a `divMod` b = "  ++ show (a `divMod` b)
  putStrLn $ "a `quot` b = " ++ show (a `quot` b) -- truncates towards 0
  putStrLn $ "a `rem` b = "  ++ show (a `rem` b)  -- same sign as first operand
  putStrLn $ "a `quotRem` b = "  ++ show (a `quotRem` b)


Welcome to Quackery.

Enter "leave" to leave the shell.

Building extensions.

/O> ( nests are dynamic arrays, zero indexed from the left, -1 indexed from the right )
...

Stack empty.

/O> []                ( create an empty nest )
... 23 join 24 join   ( append two numbers   )
... ' [ 33 34 ]       ( create a nest of two numbers )
... join              ( concatenate them )
... ' [ 45 46 ]       ( create a nest of two numbers )
... nested join       ( add that nest as an item of the nest )
...

Stack: [ 23 24 33 34 [ 45 46 ] ]

/O> ' [ 55 56 ]       ( create a nest of two numbers )
... swap 2 stuff      ( insert it into the previous nest as the 2nd item )
...

Stack: [ 23 24 [ 55 56 ] 33 34 [ 45 46 ] ]

/O> -3 pluck drop     ( remove the third item from the end and dispose of it )
...

Stack: [ 23 24 [ 55 56 ] 34 [ 45 46 ] ]

/O> dup 0 peek        ( copy the first item )
...

Stack: [ 23 24 [ 55 56 ] 34 [ 45 46 ] ] 23

/O> swap -1 poke      ( ... and overwrite the last item with it )
...

Stack: [ 23 24 [ 55 56 ] 34 23 ]

/O> behead join      ( remove the first item and append it to the end )
...

Stack: [ 24 [ 55 56 ] 34 23 23 ]

/O> -2 split nip     ( split it two items from the end and dispose of the left hand side )
...

Stack: [ 23 23 ]

/O> ' ** join        ( append the exponentiation word )
...

Stack: [ 23 23 ** ]

/O> do               ( ... and perform the nest as Quackery code. )
...

Stack: 20880467999847912034355032910567


arr <- array(1)

arr <- append(arr,3)

arr[1] <- 2

print(arr[1])


class BasicIntegerArithmetic {
    public static function main() {
        var args =Sys.args();
        if (args.length < 2) return;
        var a = Std.parseFloat(args[0]);
        var b = Std.parseFloat(args[1]);
        trace("a+b = " + (a+b));
        trace("a-b = " + (a-b));
        trace("a*b = " + (a*b));
        trace("a/b = " + (a/b));
        trace("a%b = " + (a%b));
    }
}


DLG(Edit=A, Edit=B, TItle='Enter numeric A and B')
WRITE(Name) A, B
WRITE() '              A + B = ', A + B
WRITE() '              A - B = ', A - B
WRITE() '              A * B = ', A * B
WRITE() '              A / B = ', A / B          ! no truncation
WRITE() 'truncate      A / B = ', INT(A / B)     ! truncates towards 0
WRITE() 'round next    A / B = ', NINT(A / B)    ! truncates towards next integer
WRITE() 'round down    A / B = ', FLOOR(A / B)   ! truncates towards minus infinity
WRITE() 'round up      A / B = ', CEILING(A / B) ! truncates towards plus infinity
WRITE() 'remainder of  A / B = ', MOD(A, B)      ! same sign as A
WRITE() 'A to the power of B = ', A ^ B
WRITE() 'A to the power of B = ', A ** B


#lang racket

;; import dynamic arrays
(require data/gvector)

(define v (vector 1 2 3 4))   ; array
(vector-ref v 0)              ; 1
(vector-set! v 1 4)           ; 2 -> 4

(define gv (gvector 1 2 3 4)) ; dynamic array
(gvector-ref gv 0)            ; 1
(gvector-add! gv 5)           ; increase size


my @arr;

push @arr, 1;
push @arr, 3;

@arr[0] = 2;

say @arr[0];


I64 *a, *b;
a = Str2I64(GetStr("Enter your first number: "));
b = Str2I64(GetStr("Enter your second number: "));

if (b == 0)
  Print("Error: The second number must not be zero.\n");
else {
  Print("a + b = %d\n", a + b);
  Print("a - b = %d\n", a - b);
  Print("a * b = %d\n", a * b);
  Print("a / b = %d\n", a / b); /* rounds down */
  Print("a % b = %d\n", a % b); /* same sign as first operand */
  Print("a ` b = %d\n", a ` b);
}


main
	a $= integer(in(' ')); ignore
	b $= integer(in('\n')); ignore

	print("Sum:"		, a + b)
	print("Difference:", a - b)
	print("Product:"	, a * b)
	print("Quotient:"	, a / b) // rounds towards zero
	print("Modulus:"	, a % b) // same sign as first operand
	print("Exponent:"	, a ^ b)
}


a: []      ; Empty.
b: ["foo"] ; Pre-initialized.


arr1: []      ;create empty array
arr2: ["apple" "orange" 1 2 3]    ;create an array with data
>> insert arr1 "blue"
>> arr1
== ["blue"]
append append arr1 "black" "green"
>> arr1
== ["blue" "black" "green"]
>> arr1/2
== "black"
>> second arr1
== "black"
>> pick arr1 2
== "black"


procedure main()
writes("Input 1st integer a := ")
a := integer(read())
writes("Input 2nd integer b := ")
b := integer(read())

write(" a + b = ",a+b)
write(" a - b = ",a-b)
write(" a * b = ",a*b)
write(" a / b = ",a/b, " rounds toward 0")
write(" a % b = ",a%b, " remainder sign matches a")
write(" a ^ b = ",a^b)
end


Enter Two Numbers is a room.

Numerically entering is an action applying to one number. Understand "[number]" as numerically entering.

The first number is a number that varies.

After numerically entering for the first time:
	now the first number is the number understood.

After numerically entering for the second time:
	let A be the first number;
	let B be the number understood;
	say "[A] + [B] = [A + B]."; [operator syntax]
	say "[A] - [B] = [A minus B]."; [English syntax]
	let P be given by P = A * B where P is a number; [inline equation]
	say "[A] * [B] = [P].";
	let Q be given by the Division Formula; [named equation]
	say "[A] / [B] = [Q].";
	say "[A] mod [B] = [remainder after dividing A by B].";
	end the story.

Equation - Division Formula
	Q = A / B
where Q is a number, A is a number, and B is a number.


let arr = [1, 2, 3]

let _ = Js.Array2.push(arr, 4)

arr[3] = 5

Js.log(Js.Int.toString(arr[3]))


needs array'

( Create an array with four elements )
^array'new{ 1 2 3 4 } constant a

( Add 10 to each element in an array and update the array with the results )
a [ 10 + ] ^array'map

( Apply a quote to each element in an array; leaves the contents alone )
a [ 10 + putn cr ] ^array'apply

( Display an array )
a ^array'display

( Look for a value in an array )
3 a ^array'in?
6 a ^array'in?

( Look for a string in an array )
"hello" a ^array'stringIn?

( Reverse the order of items in an array )
a ^array'reverse

( Append two arrays and return a new one )
^array'new{ 1 2 3 } constant a
^array'new{ 4 5 6 } constant b
a b ^array'append constant c

( Create an array from the values returned by a quote )
[ 1 2 "hello" "world" ] ^array'fromQuote constant d

( Create a quote from the values in an array )
d ^array'toQuote


calc =:    + , - , * , <[email protected]% , |~ , ^


import java.util.Scanner;

public class IntegerArithmetic {
    public static void main(String[] args) {
        // Get the 2 numbers from command line arguments
        Scanner sc = new Scanner(System.in);
        int a = sc.nextInt();
        int b = sc.nextInt();

        int sum = a + b;        // The result of adding 'a' and 'b' (Note: integer addition is discouraged in print statements due to confusion with string concatenation)
        int difference = a - b; // The result of subtracting 'b' from 'a'
        int product = a * b;    // The result of multiplying 'a' and 'b'
        int division = a / b;   // The result of dividing 'a' by 'b' (Note: 'division' does not contain the fractional result)
        int remainder = a % b;  // The remainder of dividing 'a' by 'b'

        System.out.println("a + b = " + sum);
        System.out.println("a - b = " + difference);
        System.out.println("a * b = " + product);
        System.out.println("quotient of a / b = " + division);   // truncates towards 0
        System.out.println("remainder of a / b = " + remainder);   // same sign as first operand
    }
}


/*REXX program  demonstrates a  simple  array usage.                    */
a.='not found'                         /*value for all  a.xxx  (so far).*/
                do j=1  to 100         /*start at 1, define 100 elements*/
                a.j=-j*1000            /*define as negative J thousand. */
                end   /*j*/            /*the above defines 100 elements.*/

say 'element 50 is:'   a.50
say 'element 3000 is:' a.3000
                                       /*stick a fork in it, we're done.*/


# create an array with one string in it
a = ['foo']

# add items
a + 1         # ["foo", 1]

# set the value at a specific index in the array
a[1] = 2       # [2, 1]

# retrieve an element
see a[1]


var a = parseInt(get_input("Enter an integer"), 10);
var b = parseInt(get_input("Enter an integer"), 10);

WScript.Echo("a = " + a);
WScript.Echo("b = " + b);
WScript.Echo("sum: a + b = "        + (a + b));
WScript.Echo("difference: a - b = " + (a - b));
WScript.Echo("product: a * b = "    + (a * b));
WScript.Echo("quotient: a / b = "   + (a / b | 0)); // "| 0" casts it to an integer
WScript.Echo("remainder: a % b = "  + (a % b));

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


# Lines which do not have two integers are skipped:

def arithmetic:
  split(" ") | select(length > 0) | map(tonumber)
  | if length > 1 then
    .[0] as $a | .[1] as $b
    | "For a = \($a) and b = \($b):\n" +
      "a + b = \($a + $b)\n" +
      "a - b = \($a - $b)\n" +
      "a * b = \($a * $b)\n" +
      "a/b|floor = \($a / $b | floor)\n" +
      "a % b = \($a % $b)\n" +
      "a | exp = \($a | exp)\n"
    else empty
    end ;

arithmetic


// 1-D (row- or column-vectors)
// Static:
// row-vector
x = [1:3];
x = zeros(1,3); x[1]=1; x[2]=2; x[3]=3;
// column-vector
x = [1:3]';  // or
x = [1;2;3]; // or
x = zeros(3,1); x[1]=1; x[2]=2; x[3]=3;
// Dynamic:
x = [];           // create an empty array
x = [x; 1, 2];    // add a row to 'x' containing [1, 2], or
x = [x, [1; 2]];  // add a column to 'x' containing [1; 2]

// 2-D array
// Static:
x = zeros(3,5);        // create an zero-filed matrix of size 3x5
x[1;1] = 1;            // set the x(1,1) element to 1
x[2;]  = [1,2,3,4,5];  // set the second row x(2,) to a row vector
x[3;4:5] = [2,3];      // set x(3,4) to 2 and x(3,5) to 3
// Dynamic
x = [1:5];               // create an row-vector x(1,1)=1, x(1,2)=2, ... x(1,5)=5
x = [x; 2, 3, 4, 6, 7];  // add to 'x' a row.

// Accessing an element of arrays:
// to retrieve/print element of matrix 'x' just put this in a single line in the script
i=1;
j=2;
x[i;j]


set "index" to 0
. "Assign random values to array"
: "loop"
set "array&index&" to random 0 to 99
inc "index" by 1
if "index" < 100 then "loop"

* "Value of index 50 is ('array('50')')."
end


"use strict";
/* Arthimetic/Integer, in Jsish */
var line = console.input();
var nums = line.match(/^\s*([+-]?[0-9]+)\s+([+-]?[0-9]+)\s*/);
var a = Number(nums[1]);
var b = Number(nums[2]);

puts("A is ", a, ", B is ", b);
puts("Sum               A + B is ", a + b);
puts("Difference        A - B is ", a - b);
puts("Product           A * B is ", a * b);
puts("Integer quotient  A / B is ", a / b | 0, " truncates toward 0");
puts("Remainder         A % B is ", a % b, " sign follows first operand");
puts("Exponentiation    A to the power B is ", Math.pow(a, b));

/*
=!INPUTSTART!=
7 4
=!INPUTEND!=
*/

/*
=!EXPECTSTART!=
A is  7 , B is  4
Sum               A + B is  11
Difference        A - B is  3
Product           A * B is  28
Integer quotient  A / B is  1  truncates toward 0
Remainder         A % B is  3  sign follows first operand
Exponentiation    A to the power B is  2401
=!EXPECTEND!=
*/


function arithmetic (a = parse(Int, readline()), b = parse(Int, readline()))
  for op in  [+,-,*,div,rem]
    println("a $op b = $(op(a,b))")
  end
end


      //-Static array
      //--def of 10 el array of integers, initialised to zeros
     D array...
     D                 s             10i 0 dim(10)
     D                                     inz
      //--def an el
     D el_1...
     D                 s             10i 0 inz

      /free

       //-assign first el
       //--first element of RPG array is indexed with 1
       array(1) = 111;

       //-get first el of array
       el_1 = array(1);

       //--display it
       dsply ('First el of array='+%char(el_1));
       //--displays: First el of array=111

       //---or shorter, without "el_1"
       dsply ('First el of array='+%char(array(1)));
       //--displays: First el of array=111

      /end-free


# create an array with one object in it
a = ['foo']

# the Array#new method allows several additional ways to create arrays

# push objects into the array
a << 1         # ["foo", 1]
a.push(3,4,5)  # ["foo", 1, 3, 4, 5]

# set the value at a specific index in the array
a[0] = 2       # [2, 1, 3, 4, 5]

# a couple of ways to set a slice of the array
a[0,3] = 'bar'    # ["bar", 4, 5]
a[1..-1] = 'baz'  # ["bar", "baz"]
a[0] = nil        # [nil, "baz"]
a[0,1] = nil      # ["baz"]

# retrieve an element
puts a[0]


// version 1.1

fun main(args: Array<String>) {
    val r = Regex("""-?\d+[ ]+-?\d+""")
    while(true) {
        print("Enter two integers separated by space(s) or q to quit: ")
        val input: String = readLine()!!.trim()
        if (input == "q" || input == "Q") break
        if (!input.matches(r)) {
            println("Invalid input, try again")
            continue
        }
        val index = input.lastIndexOf(' ')
        val a = input.substring(0, index).trimEnd().toLong()
        val b = input.substring(index + 1).toLong()
        println("$a + $b = ${a + b}")
        println("$a - $b = ${a - b}")
        println("$a * $b = ${a * b}")
        if (b != 0L) {
            println("$a / $b = ${a / b}")  // rounds towards zero
            println("$a % $b = ${a % b}")  // if non-zero, matches sign of first operand
        }
        else {
            println("$a / $b = undefined")
            println("$a % $b = undefined")
        }
        val d = Math.pow(a.toDouble(), b.toDouble())
        print("$a ^ $b = ")
        if (d % 1.0 == 0.0) {
            if (d >= Long.MIN_VALUE.toDouble() && d <= Long.MAX_VALUE.toDouble())
                println("${d.toLong()}")
            else
                println("out of range")
        }
        else if (!d.isFinite())
            println("not finite")
        else
            println("not integral")
        println()
    }
}


print "Enter array 1 greater than 0"; : input a1
print "Enter array 2 greater than 0"; : input a2

dim chrArray$(max(a1,1),max(a2,1))
dim numArray(max(a1,1),max(a2,1))

chrArray$(1,1) = "Hello"
numArray(1,1) = 987.2
print chrArray$(1,1);" ";numArray(1,1)


let a = [1, 2, 3]; // immutable array
let mut m = [1, 2, 3]; // mutable array
let zeroes = [0; 200]; // creates an array of 200 zeroes


{def arithmetic
 {lambda {:x :y}
  {S.map {{lambda {:x :y :op}
                  {br}applying :op on :x & :y returns {:op :x :y}} :x :y}
         + - * / % pow max min = > <}}}
-> arithmetic

{arithmetic 8 12}
->
applying + on 8 & 12 returns 20
applying - on 8 & 12 returns -4
applying * on 8 & 12 returns 96
applying / on 8 & 12 returns 0.6666666666666666
applying % on 8 & 12 returns 8
applying pow on 8 & 12 returns 68719476736
applying max on 8 & 12 returns 12
applying min on 8 & 12 returns 8
applying = on 8 & 12 returns false
applying > on 8 & 12 returns false
applying < on 8 & 12 returns true


-- a is an array of INTs
a :ARRAY{INT};
-- create an array of five "void" elements
a := #ARRAY{INT}(5);
-- static creation of an array with three elements
b :ARRAY{FLT} := |1.2, 1.3, 1.4|;
-- accessing an array element
c ::= b[0]; -- syntactic sugar for b.aget(0)
-- set an array element
b[1] := c; -- syntactic sugar for b.aset(1, c)
-- append another array
b := b.append(|5.5|);


// Create a new integer array with capacity 10
val a = new Array[Int](10)

// Create a new array containing specified items
val b = Array("foo", "bar", "baz")

// Assign a value to element zero
a(0) = 42

// Retrieve item at element 2
val c = b(2)


(defmodule arith
  (export all))

(defun demo-arith ()
  (case (: io fread '"Please enter two integers: " '"~d~d")
    ((tuple 'ok (a b))
      (: io format '"~p + ~p = ~p~n" (list a b (+ a b)))
      (: io format '"~p - ~p = ~p~n" (list a b (- a b)))
      (: io format '"~p * ~p = ~p~n" (list a b (* a b)))
      (: io format '"~p^~p = ~p~n" (list a b (: math pow a b)))
      ; div truncates towards zero
      (: io format '"~p div ~p = ~p~n" (list a b (div a b)))
      ; rem's result takes the same sign as the first operand
      (: io format '"~p rem ~p = ~p~n" (list a b (rem a b))))))


(let ((array #(1 2 3 4 5))     ; vector literal
      (array2 (make-vector 5))  ; default is unspecified
      (array3 (make-vector 5 0))) ; default 0
 (vector-set! array 0 3)
 (vector-ref array 0))    ; 3


$ include "seed7_05.s7i";

const type: charArray is array [char] string;  # Define an array type for arrays with char index.
const type: twoDim is array array char;        # Define an array type for a two dimensional array.

const proc: main is func
  local
    var array integer: array1   is 10 times 0;           # Array with 10 elements of 0.
    var array boolean: array2   is [0 .. 4] times TRUE;  # Array with 5 elements of TRUE.
    var array integer: array3   is [] (1, 2, 3, 4);      # Array with the elements 1, 2, 3, 4.
    var array string: array4    is [] ("foo", "bar");    # Array with string elements.
    var array char: array5      is [0] ('a', 'b', 'c');  # Array with indices starting from 0.
    const array integer: array6 is [] (2, 3, 5, 7, 11);  # Array constant.
    var charArray: array7       is ['1'] ("one", "two"); # Array with char index starting from '1'.
    var twoDim: array8          is [] ([] ('a', 'b'),    # Define two dimensional array.
                                       [] ('A', 'B'));
  begin
    writeln(length(array1));    # Get array length (= number of array elements).
    writeln(length(array2));    # Writes 5, because array2 has 5 array elements.
    writeln(array4[2]);         # Get array element ("bar"). By default array indices start from 1.
    writeln(array5[1]);         # Writes b, because the indices of array5 start from 0.
    writeln(array7['2']);       # Writes two, because the indices of array7 start from '1'.
    writeln(array8[2][2]);      # Writes B, because both indices start from 1.
    writeln(minIdx(array7));    # Get minumum index of array ('1').
    array3[1] := 5;             # Replace element. Now array3 has the elements 5, 2, 3, 4.
    writeln(remove(array3, 3)); # Remove 3rd element. Now array3 has the elements 5, 2, 4.
    array1 := array6;           # Assign a whole array.
    array1 &:= [] (13, 17);     # Append an array.
    array1 &:= 19;              # Append an element.
    array1 := array3[2 ..];     # Assign a slice beginning with the second element.
    array1 := array3[.. 5];     # Assign a slice up to the fifth element.
    array1 := array3[3 .. 4];   # Assign a slice from the third to the fourth element.
    array1 := array3[2 len 4];  # Assign a slice of four elements beginning with the second element.
    array1 := array3 & array6;  # Concatenate two arrays and assign the result to array1.
  end func;