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
if second <>0 then print "The integer quotient is " ; int( first /second); " (rounds towards 0)" else print "Division by zero not allowed."
print "The remainder is " ; first MOD second; " (sign matches first operand)"
print "The first raised to the power of the second is " ; first ^second


# Arithmetic/Integer, in LIL
write "Enter two numbers separated by space: "
if {[canread]} {set line [readline]}
print

set a [index $line 0]
set b [index $line 1]
print "A is $a"", B is $b"
print "Sum               A + B is [expr $a + $b]"
print "Difference        A - B is [expr $a - $b]"
print "Product           A * B is [expr $a * $b]"
print "Integer Quotient  A \\ B is [expr $a \ $b], truncates toward zero"
print "Remainder         A % B is [expr $a % $b], sign follows first operand"
print "LIL has no exponentiation expression operator"


$ 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;


-- X, Y: 2 editable field members, shown as sprites in the current GUI
x = integer(member("X").text)
y = integer(member("Y").text)

put "Sum: "       , x + y
put "Difference: ", x - y
put "Product: "   , x * y
put "Quotient: "  , x / y   -- Truncated towards zero
put "Remainder: " , x mod y -- Result has sign of left operand
put "Exponent: "  , power(x, y)


# Maybe you need to import the mathematical funcions
# from Tcl with:
# eval("namespace path ::tcl::mathfunc");

void main() {
    int a, b;
    puts("Enter two integers:");
    a = (int)(gets(stdin));
    b = (int)(gets(stdin));
    puts("${a} + ${b} = ${a+b}");
    puts("${a} - ${b} = ${a-b}");
    puts("${a} * ${b} = ${a*b}");
    puts("${a} / ${b} = ${a/b}, remainder ${a%b}");
    puts("${a} to the power of ${b} = ${(int)pow(a,b)}");
}


// Initial creation of an array
set a to (1, 2, 3)

// pushing a value to the array
// Both approaches are valid
insert 4 after a
push 5 into a

put a -- (1, 2, 3, 4, 5)

// Treating the array as a stack, using `push` and `pop`
pop a into v1

put a -- (1, 2, 3, 4)
put v1-- 5

// Treating the array as a queue, using `push` and `pull`
push 6 into a
pull a into v2

put a -- (2, 3, 4, 6)
put v2 -- 1

// Referencing the items in the array
put the second item of a -- 3

// Changing the values in the array
set the third item of a to "abc"
put a -- (2, 3, "abc", 6)


# create an empty array
var arr = [];

# push objects into the array
arr << "a";           #: ['a']
arr.append(1,2,3);    #: ['a', 1, 2, 3]

# change an element inside the array
arr[2] = "b";         #: ['a', 1, 'b', 3]

# set the value at a specific index in the array (with autovivification)
arr[5] = "end";       #: ['a', 1, 'b', 3, nil, 'end']

# resize the array
arr.resize_to(-1);    #: []

# slice assignment
arr[0..2] = @|('a'..'c');       #: ['a', 'b', 'c']

# indices as arrays
var indices = [0, -1];
arr[indices] = ("foo", "baz");  #: ['foo', 'b', 'baz']

# retrieve multiple elements
var *elems = arr[0, -1]
say elems                #=> ['foo', 'baz']

# retrieve an element
say arr[-1];             #=> 'baz'


ask "enter 2 numbers (comma separated)"
if it is not empty then
    put item 1 of it into n1
    put item 2 of it into n2
    put sum(n1,n2) into ai["sum"]
    put n1 * n2 into ai["product"]
    put n1 div n2 into ai["quotient"]  -- truncates
    put n1 mod n2 into ai["remainder"]
    put n1^n2 into ai["power"]
    combine ai using comma and colon
    put ai
end if


to operate :a :b
  (print [a =] :a)
  (print [b =] :b)
  (print [a + b =] :a + :b)
  (print [a - b =] :a - :b)
  (print [a * b =] :a * :b)
  (print [a / b =] int :a / :b)
  (print [a mod b =] modulo :a :b)
end


over : 2 pick
2dup : over over

arithmetic : \
  " A=" ,t over , sp " B=" ,t dup , nl \
  " A+B=" ,t 2dup + , nl \
  " A-B=" ,t 2dup - , nl \
  " A*B=" ,t 2dup * , nl \
  " A/B=" ,t 2dup / , nl \
  " A%B=" ,t      % , nl


BEGIN

  PROCEDURE STATIC;
  BEGIN
    INTEGER ARRAY X(0:4);

    X(0) := 10;
    X(1) := 11;
    X(2) := 12;
    X(3) := 13;
    X(4) := X(0);

    OUTTEXT("STATIC AT 4: ");
    OUTINT(X(4), 0);
    OUTIMAGE
  END STATIC;

  PROCEDURE DYNAMIC(N); INTEGER N;
  BEGIN
    INTEGER ARRAY X(0:N-1);

    X(0) := 10;
    X(1) := 11;
    X(2) := 12;
    X(3) := 13;
    X(4) := X(0);

    OUTTEXT("DYNAMIC AT 4: ");
    OUTINT(X(4),0);
    OUTIMAGE
  END DYNAMIC;

  STATIC;
  DYNAMIC(5)
END ARRAYS.


local x = io.read()
local y = io.read()

print ("Sum: "       , (x + y))
print ("Difference: ", (x - y))
print ("Product: "   , (x * y))
print ("Quotient: "  , (x / y)) -- Does not truncate
print ("Remainder: " , (x % y)) -- Result has sign of right operand
print ("Exponent: "  , (x ^ y))


MODULE LikeCommodoreBasic {
      \\ ADDITION: EUCLIDEAN DIV# & MOD# AND ** FOR POWER INCLUDING ^
      10 INPUT "ENTER A NUMBER:"; A%
      20 INPUT "ENTER ANOTHER NUMBER:"; B%
      30 PRINT "ADDITION:";A%;"+";B%;"=";A%+B%
      40 PRINT "SUBTRACTION:";A%;"-";B%;"=";A%-B%
      50 PRINT "MULTIPLICATION:";A%;"*";B%;"=";A%*B%
      60 PRINT "INTEGER DIVISION:";A%;"DIV";B%;"=";A% DIV B%
      65 PRINT "INTEGER EUCLIDEAN DIVISION:";A%;"DIV";B%;"=";A% DIV# B%
      70 PRINT "REMAINDER OR MODULO:";A%;"MOD";B%;"=";A% MOD B%
      75 PRINT "EUCLIDEAN REMAINDER OR MODULO:";A%;"MOD#";B%;"=";A% MOD# B%
      80 PRINT "POWER:";A%;"^";B%;"=";A%^B%
      90 PRINT "POWER:";A%;"**";B%;"=";A%**B%
}
LikeCommodoreBasic

Module IntegerTypes {
      a=12% ' Integer 16 bit
      b=12& ' Long 32 bit
      [email protected]' Decimal (29 digits)
      Def ExpType$(x)=Type$(x)
      Print ExpType$(a+1)="Double"
      Print ExpType$(a+1%)="Integer"
      Print ExpType$(a div 5)="Double"
      Print ExpType$(a div 5%)="Double"
      Print ExpType$(a mod 5)="Double"
      Print ExpType$(a mod 5%)="Double"
      Print ExpType$(a**2)="Double"

      Print ExpType$(b+1)="Double"
      Print ExpType$(b+1&)="Long"
      Print ExpType$(b div 5)="Double"
      Print ExpType$(b div 5&)="Double"
      Print ExpType$(b mod 5)="Double"
      Print ExpType$(b mod 5&)="Double"
      Print ExpType$(b**2)="Double"

      Print ExpType$(c+1)="Decimal"
      Print ExpType$([email protected])="Decimal"
      Print ExpType$(c div 5)="Decimal"
      Print ExpType$(c div [email protected])="Decimal"
      Print ExpType$(c mod 5)="Decimal"
      Print ExpType$(c mod [email protected])="Decimal"
      Print ExpType$(c**2)="Double"
}
IntegerTypes


      ar = ARRAY("3,2")      ;* 3 rows, 2 columns
fill  i = LT(i, 3) i + 1     :F(display)
      ar<i,1> = i
      ar<i,2> = i "-count"   :(fill)

display                      ;* fail on end of array
      j = j + 1
      OUTPUT = "Row " ar<j,1> ": " ar<j,2>
+                            :S(display)
END


eval(A+B)
eval(A-B)
eval(A*B)
eval(A/B)
eval(A%B)


DoIt := proc()
        local a := readstat( "Input an integer: " ):
        local b := readstat( "Input another integer: " ):
        printf( "Sum = %d\n",  a + b ):
        printf( "Difference = %d\n",  a - b ):
        printf( "Product = %d\n",  a * b ):
        printf( "Quotient = %d\n",  iquo( a, b, 'c' ) ):
        printf( "Remainder = %d\n", c ); # or irem( a, b )
        NULL # quiet return
end proc:


a = Input["Give me an integer please!"];
b = Input["Give me another integer please!"];
Print["You gave me ", a, " and ", b];
Print["sum: ", a + b];
Print["difference: ", a - b];
Print["product: ", a b];
Print["integer quotient: ", Quotient[a, b]];
Print["remainder: ", Mod[a, b]];
Print["exponentiation: ", a^b];


        load          register 0,  #0         ; running total
        load          register 1,  #0         ; index
loop:   add           register 0,  array+register 1
        add           register 1,  #1
        compare       register 1,  #4
        branchIfLess  loop


disp("integer a: "); a = scanf("%d", 1);
disp("integer b: "); b = scanf("%d", 1);
a+b
a-b
a*b
floor(a/b)
mod(a,b)
a^b


(* create first array and assign elements *)
-val first = Array.tabulate (10,fn x=>x+10) ;
val first = fromList[10, 11, 12, 13, 14, 15, 16, 17, 18, 19]: int array

(* assign to array 'second' *)
-val second=first ;
val second = fromList[10, 11, 12, 13, 14, 15, 16, 17, 18, 19]: int array

(* retrieve 5th element *)
-Array.sub(second,4);
val it = 14: int


matrix a = 2,9,4\7,5,3\6,1,8
display det(a)
matrix svd u d v = a
matrix b = u*diag(d)*v'
matrix list b
* store the u and v matrices in the current dataset
svmat u
svmat v


block(
   [a: read("a"), b: read("b")],
   print(a + b),
   print(a - b),
   print(a * b),
   print(a / b),
   print(quotient(a, b)),
   print(remainder(a, b)),
   a^b
);


x = getKBValue prompt:"First number"
y = getKBValue prompt:"Second number:"

format "Sum: %\n" (x + y)
format "Difference: %\n" (x - y)
format "Product: %\n" (x * y)
format "Quotient: %\n" (x / y)
format "Remainder: %\n" (mod x y)


:- module arith_int.
:- interface.

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

:- implementation.
:- import_module int, list, string.

main(!IO) :-
    io.command_line_arguments(Args, !IO),
    ( if
        Args = [AStr, BStr],
        string.to_int(AStr, A),
        string.to_int(BStr, B)
      then
        io.format("A + B = %d\n", [i(A + B)], !IO),
        io.format("A - B = %d\n", [i(A - B)], !IO),
        io.format("A * B = %d\n", [i(A * B)], !IO),

        % Division: round towards zero.
        %
        io.format("A / B = %d\n", [i(A / B)], !IO),

        % Division: round towards minus infinity.
        %
        io.format("A div B = %d\n", [i(A div B)], !IO),

        % Modulus: X mod Y = X - (X div Y) * Y.
        %
        io.format("A mod B = %d\n", [i(A mod B)], !IO),

        % Remainder: X rem Y = X - (X / Y) * Y.
        %
        io.format("A rem B = %d\n", [i(A rem B)], !IO),

        % Exponentiation is done using the function int.pow/2.
        %
        io.format("A `pow` B = %d\n", [i(A `pow` B)], !IO)
      else
        io.set_exit_status(1, !IO)
    ).


array = Object('zero', 'one', 'two')
array.Add('three')
array.Add('five', at: 5)
array[4] = 'four'
Print(array[3]) --> 'three'


// Arrays are typed in Swift, however, using the Any object we can add any type. Swift does not support fixed length arrays
var anyArray = [Any]()
anyArray.append("foo") // Adding to an Array
anyArray.append(1) // ["foo", 1]
anyArray.removeAtIndex(1) // Remove object
anyArray[0] = "bar" // ["bar"]


string s[];
message "input number a: ";
s1 := readstring;
message "input number b: ";
s2 := readstring;
a := scantokens s1;
b := scantokens s2;

def outp(expr op) =
  message "a " & op & " b = " & decimal(a scantokens(op) b) enddef;

outp("+");
outp("-");
outp("*");
outp("div");
outp("mod");

end


(concat dup -> ' prepend "$1 -> $2" swap % puts!) :show

("Enter an integer" ask int) 2 times ' prepend
('+ '- '* 'div 'mod) quote-map ('show concat) map cleave


// arrays are created as literals, by simply listing elements, or by a generator expression, or a combination.
def a: [1, 2, 3..7:2, 11];
$a -> !OUT::write
'
' -> !OUT::write

// Natural indexes start at 1
$a(1) -> !OUT::write
'
' -> !OUT::write

// You can select a range
$a(3..last) -> !OUT::write
'
' -> !OUT::write

// Or a permutation/selection
$a([4,1,5]) -> !OUT::write
'
' -> !OUT::write

// Values in Tailspin are generally immutable, but there is a mutable slot in a function/templates.
// A mutable array can be appended
5 -> \(@: [1,2]; $ -> ..|@: $; [email protected] ! \) -> !OUT::write


set ary {}

lappend ary 1
lappend ary 3

lset ary 0 2

puts [lindex $ary 0]


П1	<->	П0
+	С/П
ИП0	ИП1	-	С/П
ИП0	ИП1	*	С/П
ИП0	ИП1	/	[x]	С/П
ИП0	^	ИП1	/	[x]	ИП1	*	-	С/П
ИП1	ИП0	x^y	С/П


MCSKIP "WITH" NL
"" Arithmetic/Integer
"" assumes macros on input stream 1, terminal on stream 2
MCSKIP MT,<>
MCINS %.
MCDEF SL SPACES NL AS <MCSET T1=%A1.
MCSET T2=%A2.
a + b   = %%T1.+%T2..
a - b   = %%T1.-%T2..
a * b   = %%T1.*%T2..
a / b   = %%T1./%T2..
a rem b = %%T1.-%%%T1./%T2..*%T2...
Division is truncated to the greatest integer
that does not exceed the exact result. Remainder matches
the sign of the second operand, if the signs differ.


MODULE ints;

IMPORT  InOut;

VAR     a, b    : INTEGER;

BEGIN
  InOut.WriteString ("Enter two integer numbers : ");   InOut.WriteBf;
  InOut.ReadInt (a);
  InOut.ReadInt (b);
  InOut.WriteString ("a + b   = ");  InOut.WriteInt (a + b, 9);    InOut.WriteLn;
  InOut.WriteString ("a - b   = ");  InOut.WriteInt (a - b, 9);    InOut.WriteLn;
  InOut.WriteString ("a * b   = ");  InOut.WriteInt (a * b, 9);    InOut.WriteLn;
  InOut.WriteString ("a / b   = ");  InOut.WriteInt (a DIV b, 9);  InOut.WriteLn;
  InOut.WriteString ("a MOD b = ");  InOut.WriteInt (a MOD b, 9);  InOut.WriteLn;
  InOut.WriteLn;
END ints.


let list = [1, 22, 3, 24, 35, 6];

for(i in list) {
   println(i);
}


MODULE Arith EXPORTS Main;

IMPORT IO, Fmt;

VAR a, b: INTEGER;

BEGIN
  a := IO.GetInt();
  b := IO.GetInt();
  IO.Put("a+b = " & Fmt.Int(a + b) & "\n");
  IO.Put("a-b = " & Fmt.Int(a - b) & "\n");
  IO.Put("a*b = " & Fmt.Int(a * b) & "\n");
  IO.Put("a DIV b = " & Fmt.Int(a DIV b) & "\n");
  IO.Put("a MOD b = " & Fmt.Int(a MOD b) & "\n");
END Arith.


Arith(first,second)	; Mathematical operators
	Write "Plus",?12,first,"+",second,?25," = ",first+second,!
	Write "Minus",?12,first,"-",second,?25," = ",first-second,!
	Write "Multiply",?12,first,"*",second,?25," = ",first*second,!
	Write "Divide",?12,first,"/",second,?25," = ",first/second,!
	Write "Int Divide",?12,first,"\",second,?25," = ",first\second,!
	Write "Power",?12,first,"**",second,?25," = ",first**second,!
	Write "Modulo",?12,first,"#",second,?25," = ",first#second,!
	Write "And",?12,first,"&",second,?25," = ",first&second,!
	Write "Or",?12,first,"!",second,?25," = ",first!second,!
	Quit

Do Arith(2,3)
Plus        2+3           = 5
Minus       2-3           = -1
Multiply    2*3           = 6
Divide      2/3           = .6666666666666666667
Int Divide  2\3           = 0
Power       2**3          = 8
Modulo      2#3           = 2
And         2&3           = 1
Or          2!3           = 1

Do Arith(16,0.5)
Plus        16+.5         = 16.5
Minus       16-.5         = 15.5
Multiply    16*.5         = 8
Divide      16/.5         = 32
Int Divide  16\.5         = 32
Power       16**.5        = 4
Modulo      16#.5         = 0
And         16&.5         = 1
Or          16!.5         = 1

Do Arith(0,2)
Plus        0+2           = 2
Minus       0-2           = -2
Multiply    0*2           = 0
Divide      0/2           = 0
Int Divide  0\2           = 0
Power       0**2          = 0
Modulo      0#2           = 0
And         0&2           = 0
Or          0!2           = 1


module1 : {
  v1: Vector<Int>(),
  v2: Vector<String>(),
  v3: Vector<Int>([1,2,3,4]),
  v4: Vector<String>(["one","two","three"]),
  // the type of vector values can automaticaly deduced
  v5: [1.0, 2.5, 8.6], // Vector<Double>
  v6: ["one","two","three"] // Vector<String>
}


print "Number 1: "
x = int(input())
print "Number 2: "
y = int(input())

println format("Sum: %d", x + y)
println format("Difference: %d", x - y)
println format("Product: %d", x * y)
println format("Quotient: %f", x / y)

println format("Remainder: %d", x % y)
println format("Power: %d", x ^ y)


using System;

class Program
{
    static Main(args : array[string]) : void
    {
        def a = Convert.ToInt32(args[0]);
        def 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} ** {1} = {2}", a, b, a ** b);
    }
}


/* NetRexx */

options replace format comments java crossref symbols binary

say "enter 2 integer values separated by blanks"
parse ask a b
say a "+" b "=" a + b
say a "-" b "=" a - b
say a "*" b "=" a * b
say a "/" b "=" a % b "remaining" a // b "(sign from first operand)"
say a "^" b "=" a ** b

return


(defvar li (list 1 2 3))      ;; (1 2 3)
(defvar ve (vec 1 2 3)) ;; make vector #(1 2 3)
;; (defvar ve (vector 3)) ;; make #(nil nil nil)

[ve 0]    ;; yields 1
[li 0]    ;; yields 1
[ve -1]   ;; yields 3
[li 5]    ;; yields nil
[li -50]  ;; yields nil
[ve 50]   ;; error

(set [ve 2] 4) ;; changes vector to #(1 2 4).
(set [ve 3] 0) ;; error
(set [ve 3] 0) ;; error


; integer.lsp
; oofoe 2012-01-17

(define (aski msg) (print msg) (int (read-line)))
(setq x (aski "Please type in an integer and press [enter]: "))
(setq y (aski "Please type in another integer             : "))

; Note that +, -, *, / and % are all integer operations.
(println)
(println "Sum: " (+ x y))
(println "Difference: " (- x y))
(println "Product: " (* x y))
(println "Integer quotient (rounds to 0): " (/ x y))
(println "Remainder: " (setq r (% x y)))

(println "Remainder sign matches: "
	 (cond ((= (sgn r) (sgn x) (sgn y)) "both")
	       ((= (sgn r) (sgn x))         "first")
	       ((= (sgn r) (sgn y))         "second")))

(println)
(println "Exponentiation: " (pow x y))

(exit) ; NewLisp normally goes to listener after running script.


arithmetic is OP A B{[first,last,+,-,*,quotient,mod,power] A B}


alist=( item1 item2 item3 )  # creates a 3 item array called "alist"
declare -a list2        # declare an empty list called "list2"
declare -a list3[0]     # empty list called "list3"; the subscript is ignored

# create a 4 item list, with a specific order
list5=([3]=apple [2]=cherry [1]=banana [0]=strawberry)


import parseopt, strutils

var
  opt: OptParser = initOptParser()
  str = opt.cmdLineRest.split
  a: int = 0
  b: int = 0

try:
  a = parseInt(str[0])
  b = parseInt(str[1])
except ValueError:
  quit("Invalid params. Two integers are expected.")

echo("a      : " & $a)
echo("b      : " & $b)
echo("a + b  : " & $(a+b))
echo("a - b  : " & $(a-b))
echo("a * b  : " & $(a*b))
echo("a div b: " & $(a div b)) # div rounds towards zero
echo("a mod b: " & $(a mod b)) # sign(a mod b)==sign(a) if sign(a)!=sign(b)
echo("a ^ b  : " & $(a ^ b))


Function Arithmetic
	Push $0
	Push $1
	Push $2
	StrCpy $0 21
	StrCpy $1 -2

	IntOp $2 $0 + $1
	DetailPrint "$0 + $1 = $2"
	IntOp $2 $0 - $1
	DetailPrint "$0 - $1 = $2"
	IntOp $2 $0 * $1
	DetailPrint "$0 * $1 = $2"
	IntOp $2 $0 / $1
	DetailPrint "$0 / $1 = $2"
	DetailPrint "Rounding is toward negative infinity"
	IntOp $2 $0 % $1
	DetailPrint "$0 % $1 = $2"
	DetailPrint "Sign of remainder matches the first number"

	Pop $2
	Pop $1
	Pop $0
FunctionEnd


int[] array = new int[10];

array[0] = 1;
array[1] = 3;

stdout.printf("%d\n", array[0]);


MODULE Arithmetic;
IMPORT In, Out;
VAR
        x,y:INTEGER;
BEGIN
        Out.String("Give two numbers: ");In.Int(x);In.Int(y);
        Out.String("x + y >");Out.Int(x + y,6);Out.Ln;
        Out.String("x - y >");Out.Int(x - y,6);Out.Ln;
        Out.String("x * y >");Out.Int(x * y,6);Out.Ln;
        Out.String("x / y >");Out.Int(x DIV y,6);Out.Ln;
        Out.String("x MOD y >");Out.Int(x MOD y,6);Out.Ln;
END Arithmetic.


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

    function : native : DoArithmetic() ~ Nil {
      a := IO.Console->GetInstance()->ReadString()->ToInt();
      b := IO.Console->GetInstance()->ReadString()->ToInt();

      IO.Console->GetInstance()->Print("a+b = ")->PrintLine(a+b);
      IO.Console->GetInstance()->Print("a-b = ")->PrintLine(a-b);
      IO.Console->GetInstance()->Print("a*b = ")->PrintLine(a*b);
      IO.Console->GetInstance()->Print("a/b = ")->PrintLine(a/b);
    }
  }
}


'Arrays - VBScript - 08/02/2021

    'create a static array
    Dim a(3)   ' 4 items : a(0), a(1), a(2), a(3)
    'assign a value to elements
    For i = 1 To 3
        a(i) = i * i
    Next
    'and retrieve elements
	buf=""
    For i = 1 To 3
        buf = buf & a(i) & " "
    Next
    WScript.Echo buf

    'create a dynamic array
    Dim d()
    ReDim d(3)   ' 4 items : d(0), d(1), d(2), d(3)
    For i = 1 To 3
        d(i) = i * i
    Next
	buf=""
    For i = 1 To 3
        buf = buf & d(i) & " "
    Next
	WScript.Echo buf

	d(0) = 0
    'expand the array and preserve existing values
    ReDim Preserve d(4)   ' 5 items : d(0), d(1), d(2), d(3), d(4)
    d(4) = 16
	buf=""
    For i = LBound(d) To UBound(d)
        buf = buf & d(i) & " "
    Next
	WScript.Echo buf

	'create and initialize an array dynamicaly
    b = Array(1, 4, 9)
	'and retrieve all elements
	WScript.Echo Join(b,",")

	'Multi-Dimensional arrays
	'The following creates a 5x4 matrix
	Dim mat(4,3)


let _ =
  let a = read_int ()
  and b = read_int () in

  Printf.printf "a + b = %d\n" (a + b);
  Printf.printf "a - b = %d\n" (a - b);
  Printf.printf "a * b = %d\n" (a * b);
  Printf.printf "a / b = %d\n" (a / b);    (* truncates towards 0 *)
  Printf.printf "a mod b = %d\n" (a mod b) (* same sign as first operand *)


: integers (a b -- )
   "a + b ="   . a b + .cr
   "a - b ="   . a b - .cr
   "a * b ="   . a b * .cr
   "a / b ="   . a b / .cr
   "a mod b =" . a b mod .cr
   "a pow b =" . a b pow .cr
;


entity Array_Test is
end entity Array_Test;

architecture Example of Array_test is

   -- Array type have to be defined first
   type Integer_Array is array (Integer range <>) of Integer;

   -- Array index range can be ascending...
   signal A : Integer_Array (1 to 20);

   -- or descending
   signal B : Integer_Array (20 downto 1);

   -- VHDL array index ranges may begin at any value, not just 0 or 1
   signal C : Integer_Array (-37 to 20);

   -- VHDL arrays may be indexed by enumerated types, which are
   -- discrete non-numeric types
   type Days is (Mon, Tue, Wed, Thu, Fri, Sat, Sun);
   type Activities is (Work, Fish);
   type Daily_Activities is array (Days) of Activities;
   signal This_Week : Daily_Activities := (Mon to Fri => Work, Others => Fish);

   type Finger is range 1 to 4; -- exclude thumb
   type Fingers_Extended is array (Finger) of Boolean;
   signal Extended : Fingers_Extended;

   -- Array types may be unconstrained.
   -- Objects of the type must be constrained
   type Arr is array (Integer range <>) of Integer;
   signal Uninitialized : Arr (1 to 10);
   signal Initialized_1 : Arr (1 to 20) := (others => 1);
   constant Initialized_2 : Arr := (1 to 30 => 2);
   constant Const : Arr := (1 to 10 => 1, 11 to 20 => 2, 21 | 22 => 3);
   signal Centered : Arr (-50 to 50) := (0 => 1, others => 0);

   signal Result : Integer;

begin

   A <= (others => 0);           -- Assign whole array
   B <= (1 => 1, 2 => 1,
         3 => 2, others => 0);   -- Assign whole array, different values
   A (1) <= -1;                  -- Assign individual element
   A (2 to 4) <= B (3 downto 1); -- Assign a slice
   A (3 to 5) <= (2, 4, -1);     -- Assign an aggregate
   A (3 to 5) <= A (4 to 6);     -- It is OK to overlap slices when assigned

   -- VHDL arrays does not have 'first' and 'last' elements,
   -- but have 'Left' and 'Right' instead
   Extended (Extended'Left)  <= False; -- Set leftmost element of array
   Extended (Extended'Right) <= False; -- Set rightmost element of array

   Result <= A (A'Low) + B (B'High);

end architecture Example;


(define a 8)
(define b 12)

(print "(+ " a " " b ") => "    (+ a b))
(print "(- " a " " b ") => "    (- a b))
(print "(* " a " " b ") => "    (* a b))
(print "(/ " a " " b ") => "    (/ a b))

(print "(quotient " a " " b ") => "  (quot a b)) ; same as (quotient a b)
(print "(remainder " a " " b ") => " (rem  a b)) ; same as (remainder a b)
(print "(modulo " a " " b ") => "    (mod  a b)) ; same as (modulo a b)

(print "(expt " a " " b ") => " (expt a b))
(print "(gcd " a " " b ") => " (gcd a b))
(print "(lcm " a " " b ") => " (lcm a b))

; you can use more than two arguments for +,-,*,/ functions
(print (+ 1 3 5 7 9))
(print (- 1 3 5 7 9))
(print (* 1 3 5 7 9)) ; same as (1*3*5*7*9)
(print (/ 1 3 5 7 9)) ; same as (((1/3)/5)/7)/9


# Most of this long script is mere presentation.
# All you really need to do is push two integers onto the stack
# and then execute add, sub, mul, idiv, or pow.

$ClearScreen { # Using ANSI terminal control
  `\e[2J\e[1;1H' print flush
} bind def

$Say { # string Say -
  `\n' cat print flush
} bind def

$ShowPreamble {
`To show how integer arithmetic in done in Onyx,' Say
`we\'ll use two numbers of your choice, which' Say
`we\'ll call A and B.\n' Say
} bind def

$Prompt { # stack: string --
  stdout exch write pop flush
} def

$GetInt { # stack: name -- integer
  dup cvs `Enter integer ' exch cat `: ' cat
  Prompt stdin readline pop cvx eval def
} bind def

$Template { # arithmetic_operator_name label_string Template result_string
  A cvs ` ' B cvs ` ' 5 ncat over cvs ` gives ' 3 ncat exch
  A B dn cvx eval cvs `.' 3 ncat Say
} bind def

$ShowResults {
  $add `Addition: ' Template
  $sub `Subtraction: ' Template
  $mul `Multiplication: ' Template
  $idiv `Division: ' Template
  `Note that the result of integer division is rounded toward zero.' Say
  $pow `Exponentiation: ' Template
  `Note that the result of raising to a negative power always gives a real number.' Say
} bind def

ClearScreen ShowPreamble $A GetInt $B GetInt ShowResults


" Creating a dynamic array with some initial values
let array = [3, 4]

" Retrieving an element
let four = array[1]

" Modifying an element
let array[0] = 2

" Appending a new element
call add(array, 5)

" Prepending a new element
call insert(array, 1)

" Inserting a new element before another element
call insert(array, 3, 2)

echo array


'Example of array of 10 int types:
Dim numbers As Integer() = New Integer(9) {}
'Example of array of 4 string types:
Dim words As String() = {"hello", "world", "from", "mars"}
'You can also declare the size of the array and initialize the values at the same time:
Dim more_numbers As Integer() = New Integer(2) {21, 14, 63}

'For Multi-Dimensional arrays you declare them the same except for a comma in the type declaration.
'The following creates a 3x2 int matrix
Dim number_matrix As Integer(,) = New Integer(2, 1) {}

'As with the previous examples you can also initialize the values of the array, the only difference being each row in the matrix must be enclosed in its own braces.
Dim string_matrix As String(,) = {{"I", "swam"}, {"in", "the"}, {"freezing", "water"}}
'or
Dim funny_matrix As String(,) = New String(1, 1) {{"clowns", "are"}, {"not", "funny"}}

Dim array As Integer() = New Integer(9) {}
array(0) = 1
array(1) = 3
Console.WriteLine(array(0))

'Dynamic
Imports System
Imports System.Collections.Generic
Dim list As New List(Of Integer)()
list.Add(1)
list.Add(3)
list(0) = 2
Console.WriteLine(list(0))


echo (a+b);  /* Sum */
echo (a-b);  /* Difference */
echo (a*b);  /* Product */
echo (a/b);  /* Quotient */
echo (a%b);  /* Modulus */


declare
  StdIn = {New class $ from Open.file Open.text end init(name:stdin)}

  fun {ReadInt}
     {String.toInt {StdIn getS($)}}
  end

  A = {ReadInt}
  B = {ReadInt}
in
  {ForAll
   ["A+B = "#A+B
    "A-B = "#A-B
    "A*B = "#A*B
    "A/B = "#A div B  %% truncates towards 0
    "remainder "#A mod B  %% has the same sign as A
    "A^B = "#{Pow A B}
   ]
   System.showInfo}


// Arrays, in V
// Tectonics: v run arrays.v
module main

// A little bit about V variables.  V does not allow uninitialized data.
// If an identifier exists, there is a valid value.  "Empty" arrays have
// values in all positions, and V provides defaults for base types if not
// explicitly specified. E.g. 0 for numbers, `0` for rune, "" for strings.

// V uses := for definition and initialization, and = for assignment

// starts here, V programs start by invoking the "main" function.
pub fn main() {

   // Array definition in source literal form (immutable)
   array := [1,2,3,4]
   // print first element, 0 relative indexing
   println("array: $array")
   println("array[0]: ${array[0]}")
   // immutable arrays cannot be modified after initialization
   // array[1] = 5, would fail to compile with a message it needs mut

   // Dynamic arrays have some property fields
   println("array.len: $array.len")
   println("array.cap: $array.cap")

   // array specs are [n]type{properties}
   // Dynamic array definition, initial default values, "" for string
   mut array2 := []string{}
   // Append an element, using lessless
   array2 << "First"
   println("array2[0]: ${array2[0]}")
   println("array2.len: $array2.len")
   println("array2.cap: $array2.cap")

   // Fixed array definition, capacity is fixed (! suffix), mutable entries
   mut array3 := ["First", "Second", "Third"]!
   println("array3: $array3")
   array3[array3.len-1] = "Last"
   println("array3: $array3")
   println("array3.len: $array3.len")

   // Advanced, array intiailization using non default value
   mut array4 := [4]int{init: 42}
   array4[2] = 21
   println("array4: $array4")

   // Arrays can be sliced, creating a copy
   mut array5 := array4[0..3]
   println("array5: $array5")
   array5[2] = 10
   println("array4: $array4")
   println("array5: $array5")
}


a=3 b=7 func:_bbf__number_number_number =>f.name.<b> '(' a b ')' ' => ' f(a b) nl


arith(a,b)={
  print(a+b);
  print(a-b);
  print(a*b);
  print(a\b);
  print(a%b);
  print(a^b);
};


program arithmetic(input, output)

var
 a, b: integer;

begin
 readln(a, b);
 writeln('a+b = ', a+b);
 writeln('a-b = ', a-b);
 writeln('a*b = ', a*b);
 writeln('a/b = ', a div b, ', remainder ', a mod b);
 writeln('a^b = ',Power(a,b):4:2);    {real power}
 writeln('a^b = ',IntPower(a,b):4:2); {integer power}
end.


dim array$(2)
let array$(1)="Hello!"
let array$(2)="Goodbye!"
print 1 array$(1)


with javascript_semantics
include pGUI.e

Ihandle lab, tab, res, dlg

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

function valuechanged_cb(Ihandle tab)
    string s = IupGetAttribute(tab,"VALUE")
    sequence r = scanf(s,"%d %d")
    if length(r)=1 then
        integer {a,b} = r[1]
        s = sprintf(fmt, {a, b, a+b, a-b, a*b, a/b, remainder(a,b), power(a,b)})
        IupSetStrAttribute(res,"TITLE",s)
        IupRefresh(res)
    end if
    return IUP_DEFAULT
end function

procedure main()
    IupOpen()
    lab = IupLabel("Enter two numbers")
    tab = IupText("VALUECHANGED_CB", Icallback("valuechanged_cb"),"EXPAND=HORIZONTAL")
    res = IupLabel("(separated by a space)\n\n\n\n\n\n\n","EXPAND=BOTH")
    dlg = IupDialog(IupVbox({IupHbox({lab,tab},"GAP=10,NORMALIZESIZE=VERTICAL"),
                             IupHbox({res})},"MARGIN=5x5"),
                            `SIZE=188x112,TITLE="Arithmetic/Integer"`)
    IupShow(dlg)
    if platform()!=JS then
        IupMainLoop()
        IupClose()
    end if
end procedure

main()


section .text
	global _start

	_print:
		mov ebx, 1
		mov eax, 4
		int 0x80
		ret

	_start:
		;print out our byte array. ergo, String.
		mov edx, sLen
		mov ecx, sArray
		call _print
		mov edx, f_len
		mov ecx, f_msg
		call _print
		mov edx, 6			;our array members length.
		xor ecx, ecx
		mov ecx, 4
		;turnicate through the array and print all it's members.
		;At an offset of *4, each array member is referenced
		;at 1,2,3 and so on.
		_out_loops:
			push ecx
			mov ecx, [fArray+esi*4]
			call _print
			inc esi
			pop ecx
		loop _out_loops
		mov edx, u_len
		mov ecx, u_msg
		call _print
		;Let's populate 'uArray' with something from sArray.
		;mov edi, uArray
		mov ecx, 4
		xor esi, esi
		_read_loops:
			push dword [fArray+esi*4]
			pop dword [uArray+esi*4]
			inc esi
		loop _read_loops
		mov ecx, 4
		xor esi, esi
		_out_loops2:
			push ecx
			mov ecx, [uArray+esi*4]
			call _print
			inc esi
			pop ecx
		loop _out_loops2
		push 0x1
		mov eax, 1
		push eax
		int 0x80

section .data
sArray	db 'a','r','r','a','y','s',' ','a','r','e',' ','f','u','n',0xa
sLen		equ $-sArray

crap1		db "crap1",0xa
crap2		db "crap2",0xa
crap3		db "crap3",0xa
crap4		db "crap4",0xa

fArray	dd crap1,crap2
	dd crap3,crap4

f_msg		db "fArray contents",0xa,"----------------------",0xa
f_len		equ $-f_msg
u_msg		db "uArray now holds fArray contents.. dumping..",0xa,"----------------------",0xa
u_len		equ $-u_msg

section .bss
uArray	resd 1
        resd 1
	resd 1
	resd 1


def printOp
    swap print print nl
enddef

8 var a 3 var b
"a = " a printOp
"b = " b printOp

"a + b = " a b + printOp
"a - b = " a b - printOp
"a * b = " a b * printOp
"int(a / b) = " a b / int printOp
"a mod b = " a b mod printOp
"a ^ b = " a b power printOp


module arith;

extern printf;
extern scanf;

@Integer main [
	@Pointer<@Integer> a = alloc(4);
	@Pointer<@Integer> b = alloc(4);
	scanf("%i %i", a, b);

	printf("a + b = %i\n", a::get + b::get);
	printf("a - b = %i\n", a::get - b::get);
	printf("a * b = %i\n", a::get * b::get);
	printf("a / b = %i\n", a::get / b::get);
	printf("a % b = %i\n", a::get % b::get);
	printf("a ** b = %i\n", a::get ** b::get);

	return 0;
]


<?php
$a = fgets(STDIN);
$b = fgets(STDIN);

echo
    "sum:                 ", $a + $b, "\n",
    "difference:          ", $a - $b, "\n",
    "product:             ", $a * $b, "\n",
    "truncating quotient: ", (int)($a / $b), "\n",
    "flooring quotient:   ", floor($a / $b), "\n",
    "remainder:           ", $a % $b, "\n",
    "power:               ", $a ** $b, "\n"; // PHP 5.6+ only
?>


set Array = ["Hello","World"];
log(Array[0]);
Array.push("Test");
log(?Array);
log(Array[?Array-1]);


[1] (define a (make-vector 10)) ; vector of 10 elements initialized to the empty list

A
[2] (define b (make-vector 10 5)) ; vector of 10 elements initialized to 5

B
[3] (define c #(1 2 3 4 5 6 7 8 9 10)) ; vector literal

C
[4] (vector-ref c 3) ; retrieve a value -- NB. indexed from 0

4
[5] (vector-set! a 5 1) ; set a_5 to 1

1
[6] (define d (make-array 5 6 7)) ; 3-dimensional array of size 5 by 6 by 7

D
[7] (array-set! d 1 2 3 10) ; set d_1,2,3 to 10 -- NB. still indexed from 0

10
[8] (array-ref d 1 2 3) ; and get the value of d_1,2,3

10


(de math (A B)
   (prinl "Add      " (+ A B))
   (prinl "Subtract " (- A B))
   (prinl "Multiply " (* A B))
   (prinl "Divide   " (/ A B))        # Trucates towards zero
   (prinl "Div/rnd  " (*/ A B))       # Rounds to next integer
   (prinl "Modulus  " (% A B))        # Sign of the first operand
   (prinl "Power    " (** A B)) )


command   stack
in(int)   A
duplicate AA
duplicate AAA
duplicate AAAA
duplicate AAAAA
in(int)   BAAAAA
duplicate BBAAAAA
duplicate BBBAAAAA
duplicate BBBBAAAAA
duplicate BBBBBAAAAA
push 9    9BBBBBAAAAA
push 1    19BBBBBAAAAA
roll      BBBBAAAABA
push 7    7BBBBAAAABA
push 1    17BBBBAAAABA
roll      BBBAAABABA
push 5    5BBBAAABABA
push 1    15BBBAAABABA
roll      BBAABABABA
push 3    3BBAABABABA
push 1    13BBAABABABA
roll      BABABABABA
add       (A+B)BABABABA
out(int)  BABABABA
sub       (A-B)BABABA
out(int)  BABABA
mult      (A*B)BABA
out(int)  BABA
divide    (A/B)BA
out(int)  BA
mod       (A%B)
out(int)  NULL
push 1    1
exit


get list (a, b);
put skip list (a+b);
put skip list (a-b);
put skip list (a*b);
put skip list (trunc(a/b)); /* truncates towards zero.       */
put skip list (mod(a, b));  /* Remainder is always positive. */
put skip list (rem(a, b));  /* Sign can be negative.         */


include c:\cxpl\codes;
char A(10);             \creates a static array of 10 bytes, pointed to by "A"
char B;                 \declares a variable for a pointer to a dynamic array
[A(3):= 14;
B:= Reserve(10);        \reserve 10 bytes and point to their starting address
B(7):= 28;
IntOut(0, A(3)+B(7));   \displays 42
]


dim a(10)		// create a numeric array with 11 elements, from 0 to 10
				// Indexed at your preference (0 to 9 or 1 to 10)
print arraysize(a(), 1)	// this function return the element's higher number of an array

a(7) = 12.3		// access to an element of the array
redim a(20)		// alias of 'dim'. Grouth size of array

// Yabasic not allow direct downsize an array, but ...

dim a$(20)		// create a textual array with 21 elements

print arraysize(a$(), 1)

void = token("1,2,3,4,5,6,7,8,9,10", a$(), ",")	// populate it. Begun with element 1 (not 0).

print arraysize(a$(), 1)	// hey! the size is down

print a$(5)		// show the content of an element of the array

void = token("", a$())	// "erase" the array content AND redim it to 0 size

print arraysize(a$(), 1)

redim a$(10)	// resize the array

print arraysize(a$(), 1)

print a$(5)		// show the content of an element of the array. Now is empty


To run:
Start up.
Demonstrate integer arithmetic.
Wait for the escape key.
Shut down.

To demonstrate integer arithmetic:
Write "Enter a number: " to the console without advancing.
Read a number from the console.
Write "Enter another number: " to the console without advancing.
Read another number from the console.
Show the arithmetic operations between the number and the other number.

To show the arithmetic operations between a number and another number:
Write the number plus the other number then " is the sum." to the console.
Write the number minus the other number then " is the difference." to the console.
Write the number times the other number then " is the product." to the console.
Show the division of the number by the other number.
Raise the number to the other number.
Write the number then " is the power." to the console.

To show the division of a number by another number:
Privatize the number.
Divide the number by the other number giving a quotient [rounding toward zero] and a remainder [with the same sign as the dividend].
Write the quotient then " is the quotient." to the console.
Write the remainder then " is the remainder." to the console.


;;; Setup token reader
vars itemrep;
incharitem(charin) -> itemrep;
;;; read the numbers
lvars a = itemrep(), b = itemrep();
;;; Print results
printf(a + b, 'a + b = %p\n');
printf(a - b, 'a - b = %p\n');
printf(a * b, 'a * b = %p\n');
printf(a div b, 'a div b = %p\n');
printf(a mod b, 'a mod b = %p\n');


/arithInteger {
   /x exch def
   /y exch def
   x y add =
   x y sub =
   x y mul =
   x y idiv =
   x y mod =
   x y exp =
} def


Array:        ;an array located in RAM. Its values can be updated freely.
     byte 0,0,0,0,0
     byte 0,0,0,0,0
     byte 0,0,0,0,0
     byte 0,0,0,0,0


var array=List();  // array of size 0
array=(0).pump(10,List().write,5).copy(); // [writable] array of size 10 filled with 5
array[3]=4;
array[3] //-->4
array+9; //append a 9 to the end, same as array.append(9)


$a = [int] (Read-Host First Number)
$b = [int] (Read-Host Second Number)

Write-Host "Sum:                              $($a + $b)"
Write-Host "Difference:                       $($a - $b)"
Write-Host "Product:                          $($a * $b)"
Write-Host "Quotient:                         $($a / $b)"
Write-Host "Quotient, round to even:          $([Math]::Round($a / $b))"
Write-Host "Remainder, sign follows first:    $($a % $b)"


int a = 7, b = 5;

println(a + " + " + b + " = " + (a + b));
println(a + " - " + b + " = " + (a - b));
println(a + " * " + b + " = " + (a * b));
println(a + " / " + b + " = " + (a / b)); //Rounds towards zero
println(a + " % " + b + " = " + (a % b)); //Same sign as first operand


var
  a: array 10 of integer;
  da: array * of cardinal;


IGNORELINE Note: This example includes the math module.
include arithmeticmodule
:a
editvar /newvar /value=a /title=Enter first integer:
editvar /newvar /value=b /title=Enter second integer:
editvar /newvar /value=c
do add -a-,-b-=-c-
printline -c-
do subtract a,b
printline -c-
do multiply a,b
printline -c-
do divide a,b
printline -c-
do modulus a,b
printline -c-
editvar /newvar /value=d /title=Do you want to calculate more numbers?
if -d- /hasvalue yes goto :a else goto :end
:end


print_expression_and_result(M, N, Operator) :-
    Expression =.. [Operator, M, N],
    Result is Expression,
    format('~w ~8|is ~d~n', [Expression, Result]).

arithmetic_integer :-
    read(M),
    read(N),
    maplist( print_expression_and_result(M, N), [+,-,*,//,rem,^] ).


OpenConsole()

Define a, b

Print("Number 1: "): a = Val(Input())
Print("Number 2: "): b = Val(Input())

PrintN("Sum:        " + Str(a + b))
PrintN("Difference: " + Str(a - b))
PrintN("Product:    " + Str(a * b))
PrintN("Quotient:   " + Str(a / b)) ; Integer division (rounding mode=truncate)
PrintN("Remainder: " + Str(a % b))
PrintN("Power:      " + Str(Pow(a, b)))

Input()

CloseConsole()


x = int(raw_input("Number 1: "))
y = int(raw_input("Number 2: "))

print "Sum: %d" % (x + y)
print "Difference: %d" % (x - y)
print "Product: %d" % (x * y)
print "Quotient: %d" % (x / y)     #  or x // y  for newer python versions.
                                   # truncates towards negative infinity
print "Remainder: %d" % (x % y)    # same sign as second operand
print "Quotient: %d with Remainder: %d" % divmod(x, y)
print "Power: %d" % x**y

## Only used to keep the display up when the program ends
raw_input( )


input1 = 18
# input1 = input()
input2 = 7
# input2 = input()

qq = input1 + input2
print("Sum: 		  " + str(qq))
ww = input1 - input2
print("Difference: 	  " + str(ww))
ee = input1 * input2
print("Product: 	  " + str(ee))
rr = input1 / input2
print("Integer quotient: " + str(int(rr)))
print("Float quotient:   " + str(float(rr)))
tt = float(input1 / input2)
uu = (int(tt) - float(tt))*-10
#print(tt)
print("Whole Remainder:  " + str(int(uu)))
print("Actual Remainder: " + str(uu))
yy = input1 ** input2
print("Exponentiation:   " + str(yy))


START:
INPUT "Enter two integers (a,b):"; a!, b!
IF a = 0 THEN END
IF b = 0 THEN
    PRINT "Second integer is zero. Zero not allowed for Quotient or Remainder."
    GOTO START
END IF
PRINT
PRINT "             Sum = "; a + b
PRINT "      Difference = "; a - b
PRINT "         Product = "; a * b
' Notice the use of the INTEGER Divisor "\" as opposed to the regular divisor "/".
PRINT "Integer Quotient = "; a \ b, , "* Rounds toward 0."
PRINT "       Remainder = "; a MOD b, , "* Sign matches first operand."
PRINT "  Exponentiation = "; a ^ b
PRINT
INPUT "Again? (y/N)"; a$
IF UCASE$(a$) = "Y" THEN CLS: GOTO START
CLS
END


  $ "Please enter two integers separated by a space. "
  input quackery
  2dup say "Their sum is:              " +    echo cr
  2dup say "Their difference is:       " -    echo cr
  2dup say "Their product is: "        " *    echo cr
  2dup say "Their integer quotient is: " /    echo cr
  2dup say "Their remainder is:        " mod  echo cr
       say "Their exponentiation is:   " **   echo cr
  cr
  say "Quotient rounds towards negative infinity." cr
  say "Remainder matches the sign of the second argument."


cat("insert number ")
a <- scan(nmax=1, quiet=TRUE)
cat("insert number ")
b <- scan(nmax=1, quiet=TRUE)
print(paste('a+b=', a+b))
print(paste('a-b=', a-b))
print(paste('a*b=', a*b))
print(paste('a%/%b=', a%/%b))
print(paste('a%%b=', a%%b))
print(paste('a^b=', a^b))


#lang racket/base

(define (arithmetic x y)
  (for ([op (list + - * / quotient remainder modulo max min gcd lcm)])
    (printf "~s => ~s\n" `(,(object-name op) ,x ,y) (op x y))))

(arithmetic 8 12)


my Int $a = get.floor;
my Int $b = get.floor;

say 'sum:              ', $a + $b;
say 'difference:       ', $a - $b;
say 'product:          ', $a * $b;
say 'integer quotient: ', $a div $b;
say 'remainder:        ', $a % $b;
say 'exponentiation:   ', $a**$b;


'  Number 1: ' print expect 0 prefer as x
'  Number 2: ' print expect 0 prefer as y

x y + "       sum: %d\n" print
x y - "difference: %d\n" print
x y * "   product: %d\n" print
x y / "  quotient: %d\n" print
x y % " remainder: %d\n" print


rebol [
	Title: "Integer"
	URL: http://rosettacode.org/wiki/Arithmetic/Integer
]

x: to-integer ask "Please type in an integer, and press [enter]: "
y: to-integer ask "Please enter another integer: "
print ""

print ["Sum:"  x + y]
print ["Difference:"  x - y]
print ["Product:" x * y]

print ["Integer quotient (coercion)                          :"  to-integer x / y]
print ["Integer quotient (away from zero)                    :"  round x / y]
print ["Integer quotient (halves round towards even digits)  :"  round/even x / y]
print ["Integer quotient (halves round towards zero)         :"  round/half-down x / y]
print ["Integer quotient (round in negative direction)       :"  round/floor x / y]
print ["Integer quotient (round in positive direction)       :"  round/ceiling x / y]
print ["Integer quotient (halves round in positive direction):"  round/half-ceiling x / y]

print ["Remainder:"  r: x // y]

; REBOL evaluates infix expressions from left to right. There are no
; precedence rules -- whatever is first gets evaluated. Therefore when
; performing this comparison, I put parens around the first term
; ("sign? a") of the expression so that the value of /a/ isn't
; compared to the sign of /b/. To make up for it, notice that I don't
; have to use a specific return keyword. The final value in the
; function is returned automatically.

match?: func [a b][(sign? a) = sign? b]

result: copy []
if match? r x [append result "first"]
if match? r y [append result "second"]

; You can evaluate arbitrary expressions in the middle of a print, so
; I use a "switch" to provide a more readable result based on the
; length of the /results/ list.

print [
	"Remainder sign matches:"
	switch length? result [
		0 ["neither"]
		1 [result/1]
		2 ["both"]
	]
]

print ["Exponentiation:" x ** y]


set a = -17
set b = 4
echo "a+b = ".format(a+b,"%1d")
echo "a-b = ".format(a-b,"%1d")
echo "a*b = ".format(a*b,"%1d")
echo "a DIV b = ".format(floor(a/b),"%1d")
echo "a MOD b = ".format(a mod b,"%1d")
echo "a^b = ".format(pow(a,b),"%1d")


let a = int_of_string(Sys.argv[2])
let b = int_of_string(Sys.argv[3])

let sum = a + b
let difference = a - b
let product = a * b
let division = a / b
let remainder = mod(a, b)

Js.log("a + b = " ++ string_of_int(sum))
Js.log("a - b = " ++ string_of_int(difference))
Js.log("a * b = " ++ string_of_int(product))
Js.log("a / b = " ++ string_of_int(division))
Js.log("a % b = " ++ string_of_int(remainder))


:arithmetic (ab-)
  over       '\na_______=_%n s:put
  dup        '\nb_______=_%n s:put
  dup-pair + '\na_+_b___=_%n s:put
  dup-pair - '\na_-_b___=_%n s:put
  dup-pair * '\na_*_b___=_%n s:put
  /mod       '\na_/_b___=_%n s:put
             '\na_mod_b_=_%n\n" s:put ;


/*REXX program obtains two integers from the C.L. (a prompt);  displays some operations.*/
numeric digits 20                                /*#s are round at 20th significant dig.*/
parse arg x y .                                  /*maybe the integers are on the  C.L.  */

  do while \datatype(x,'W') | \datatype(y,'W')   /*both   X  and  Y   must be integers. */
  say "─────Enter two integer values  (separated by blanks):"
  parse pull x y .                               /*accept two thingys from command line.*/
  end   /*while*/
                                                 /* [↓]  perform this  DO  loop twice.  */
     do j=1  for 2                               /*show  A  oper  B,   then  B  oper  A.*/
     call show 'addition'          ,  "+",   x+y
     call show 'subtraction'       ,  "-",   x-y
     call show 'multiplication'    ,  "*",   x*y
     call show 'int  division'     ,  "%",   x%y,  '    [rounds down]'
     call show 'real division'     ,  "/",   x/y
     call show 'division remainder',  "//",  x//y, '    [sign from 1st operand]'
     call show 'power'             ,  "**",  x**y

     parse value  x  y    with    y  x           /*swap the two values and perform again*/
     if j==1  then say copies('═', 79)           /*display a fence after the 1st round. */
     end   /*j*/
exit                                             /*stick a fork in it,  we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
show: parse arg c,o,#,?;   say right(c,25)' '  x  center(o,4)  y  " ───► "  #  ?;   return


func Test a,b
   see "a+b" + ( a + b ) + nl
   see "a-b" + ( a - b ) + nl
   see "a*b" + ( a * b ) + nl
   // The quotient isn't integer, so we use the Ceil() function, which truncates it downward.
   see "a/b" + Ceil( a / b ) + nl
   // Remainder:
   see "a%b" + ( a % b ) + nl
   see "a**b" +  pow(a,b )  + nl


input string "Enter number 1:"
set "a" to "input"
input string "Enter number 2:"
set "b" to "input"

[ "Sum: ('a' + 'b')"
[ "Difference: ('a' - 'b')"
[ "Product: ('a' * 'b')"
[ "Integer Quotient: ('a' / 'b')"
[ "Remainder: ('a' % 'b')"
[ "Exponentiation: ('a'^'b')"


puts 'Enter x and y'
x = gets.to_i  # to check errors, use x=Integer(gets)
y = gets.to_i

puts "Sum: #{x+y}",
     "Difference: #{x-y}",
     "Product: #{x*y}",
     "Quotient: #{x/y}",       # truncates towards negative infinity
     "Quotient: #{x.fdiv(y)}", # float
     "Remainder: #{x%y}",      # same sign as second operand
     "Exponentiation: #{x**y}"


input "1st integer: "; i1
input "2nd integer: "; i2

print "      Sum"; i1 + i2
print "     Diff"; i1 - i2
print "  Product"; i1 * i2
if i2 <>0 then print "  Quotent "; int( i1 / i2); else print "Cannot divide by zero."
print "Remainder"; i1 MOD i2
print "1st raised to power of 2nd"; i1 ^ i2


use std::env;

fn main() {
    let args: Vec<_> = env::args().collect();
    let a = args[1].parse::<i32>().unwrap();
    let b = args[2].parse::<i32>().unwrap();

    println!("sum:              {}", a + b);
    println!("difference:       {}", a - b);
    println!("product:          {}", a * b);
    println!("integer quotient: {}", a / b); // truncates towards zero
    println!("remainder:        {}", a % b); // same sign as first operand
}


@function arithmetic($a,$b) {
	@return $a + $b, $a - $b, $a * $b, ($a - ($a % $b))/$b, $a % $b;
}


val a = Console.readInt
val b = Console.readInt

val sum = a + b //integer addition is discouraged in print statements due to confusion with String concatenation
println("a + b = " + sum)
println("a - b = " + (a - b))
println("a * b = " + (a * b))
println("quotient of a / b = " + (a / b)) // truncates towards 0
println("remainder of a / b = " + (a % b)) // same sign as first operand


(define (arithmetic x y)
  (for-each (lambda (op)
              (write  (list op x y))
              (display " => ")
              (write ((eval op) x y))
              (newline))
            '(+ - * / quotient remainder modulo max min gcd lcm)))

(arithmetic 8 12)


$ include "seed7_05.s7i";

const proc: main is func
  local
    var integer: a is 0;
    var integer: b is 0;
  begin
    write("a = ");
    readln(a);
    write("b = ");
    readln(b);

    writeln("a + b = " <& a + b);
    writeln("a - b = " <& a - b);
    writeln("a * b = " <& a * b);
    writeln("a div b = " <& a div b);    # Rounds towards zero
    writeln("a rem b = " <& a rem b);    # Sign of the first operand
    writeln("a mdiv b = " <& a mdiv b);  # Rounds towards negative infinity
    writeln("a mod b = " <& a mod b);    # Sign of the second operand
  end func;


ask "Enter the first number:"
put it into number1

ask "Enter the second number:"
put it into number2

put "Sum: " & number1 plus number2
put "Difference: " & number1 minus number2
put "Product: " & number1 multiplied by number2
put "Integer quotient: " & number1 div number2 -- Rounding towards 0
put "Remainder: " & number1 rem number2
put "Exponentiation: " & number1 to the power of number2


var a = Sys.scanln("First number: ").to_i;
var b = Sys.scanln("Second number: ").to_i;

%w'+ - * // % ** ^ | & << >>'.each { |op|
    "#{a} #{op} #{b} = #{a.$op(b)}".say;
}


[| :a :b |
inform: (a + b) printString.
inform: (a - b) printString.
inform: (a * b) printString.
inform: (a / b) printString.
inform: (a // b) printString.
inform: (a \\ b) printString.

] applyTo: {Integer readFrom: (query: 'Enter a: '). Integer readFrom: (query: 'Enter b: ')}.


| a b |
'Input number a: ' display.
a := (stdin nextLine) asInteger.
'Input number b: ' display.
b := (stdin nextLine) asInteger.
('a+b=%1' % { a + b }) displayNl.
('a-b=%1' % { a - b }) displayNl.
('a*b=%1' % { a * b }) displayNl.
('a/b=%1' % { a // b }) displayNl.
('a%%b=%1' % { a \\ b }) displayNl.


INPUT "Enter first number.":first
INPUT "Enter second number.":second
PRINT "The sum of";first;"and";second;"is ";first+second&"."
PRINT "The difference between";first;"and";second;"is ";ABS(first-second)&"."
PRINT "The product of";first;"and";second;"is ";first*second&"."
IF second THEN
    PRINT "The integer quotient of";first;"and";second;"is ";INTEG(first/second)&"."
ELSE
    PRINT "Division by zero not cool."
ENDIF
PRINT "The remainder being...";first%second&"."
PRINT STR$(first);"raised to the power of";second;"is ";first^second&"."


        output = "Enter first integer:"
  	first = input
	output = "Enter second integer:"
	second = input
	output = "sum  = " first + second
	output = "diff = " first - second
	output = "prod = " first * second
	output = "quot = " (qout = first / second)
	output = "rem  = " first - (qout * second)
	output = "expo  = " first ** second
end


-- test.sql
-- Tested in SQL*plus

DROP TABLE test;

CREATE TABLE test (a INTEGER, b INTEGER);

INSERT INTO test VALUES ('&&A','&&B');

commit;

SELECT a-b difference FROM test;

SELECT a*b product FROM test;

SELECT trunc(a/b) integer_quotient FROM test;

SELECT MOD(a,b) remainder FROM test;

SELECT POWER(a,b) exponentiation FROM test;


val () = let
  val a = valOf (Int.fromString (valOf (TextIO.inputLine TextIO.stdIn)))
  val b = valOf (Int.fromString (valOf (TextIO.inputLine TextIO.stdIn)))
in
  print ("a + b = "   ^ Int.toString (a + b)   ^ "\n");
  print ("a - b = "   ^ Int.toString (a - b)   ^ "\n");
  print ("a * b = "   ^ Int.toString (a * b)   ^ "\n");
  print ("a div b = " ^ Int.toString (a div b) ^ "\n");         (* truncates towards negative infinity *)
  print ("a mod b = " ^ Int.toString (a mod b) ^ "\n");         (* same sign as second operand *)
  print ("a quot b = " ^ Int.toString (Int.quot (a, b)) ^ "\n");(* truncates towards 0 *)
  print ("a rem b = " ^ Int.toString (Int.rem (a, b)) ^ "\n");  (* same sign as first operand *)
  print ("~a = "      ^ Int.toString (~a)      ^ "\n")          (* unary negation, unusual notation compared to other languages *)
end


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)")
print("No operator for Exponential")


puts "Please enter two numbers:"

set x [expr {int([gets stdin])}]; # Force integer interpretation
set y [expr {int([gets stdin])}]; # Force integer interpretation

puts "$x + $y = [expr {$x + $y}]"
puts "$x - $y = [expr {$x - $y}]"
puts "$x * $y = [expr {$x * $y}]"
puts "$x / $y = [expr {$x / $y}]"
puts "$x mod $y = [expr {$x % $y}]"
puts "$x 'to the' $y = [expr {$x ** $y}]"


Prompt A,B
Disp "SUM"
Pause A+B
Disp "DIFFERENCE"
Pause A-B
Disp "PRODUCT"
Pause AB
Disp "INTEGER QUOTIENT"
Pause int(A/B)
Disp "REMAINDER"
Pause A-B*int(A/B)


Local a, b
Prompt a, b
Disp "Sum: " & string(a + b)
Disp "Difference: " & string(a - b)
Disp "Product: " & string(a * b)
Disp "Integer quotient: " & string(intDiv(a, b))
Disp "Remainder: " & string(remain(a, b))


[ ( a b -- )
  2dup ." a+b = " + . cr
  2dup ." a-b = " - . cr
  2dup ." a*b = " * . cr
  2dup ." a/b = " / . ." remainder " mod . cr
] is mathops


$$ MODE TUSCRIPT
a=5
b=3
c=a+b
c=a-b
c=a*b
c=a/b
c=a%b


#!/bin/sh
read a; read b;
echo "a+b     = "  `expr $a  +  $b`
echo "a-b     = "  `expr $a  -  $b`
echo "a*b     = "  `expr $a \*  $b`
echo "a/b     = "  `expr $a  /  $b` # truncates towards 0
echo "a mod b = "  `expr $a  %  $b` # same sign as first operand


#
# integer arithmetic
#

decl int x y
out "number 1: " console
set x (in int console)
out "number 2: " console
set y (in int console)

out "\nsum:\t" (int (+ x y)) endl console
out "diff:\t" (int (- x y)) endl console
out "prod:\t" (int (* x y)) endl console
# quotient doesn't round at all, but the int function rounds up
out "quot:\t" (int (/ x y)) endl console
# mod takes the sign of x
out "mod:\t" (int (mod x y)) endl console


'Arithmetic - Integer
Sub RosettaArithmeticInt()
Dim opr As Variant, a As Integer, b As Integer
On Error Resume Next

a = CInt(InputBox("Enter first integer", "XLSM | Arithmetic"))
b = CInt(InputBox("Enter second integer", "XLSM | Arithmetic"))

Debug.Print "a ="; a, "b="; b, vbCr
For Each opr In Split("+ - * / \ mod ^", " ")
    Select Case opr
        Case "mod":     Debug.Print "a mod b", a; "mod"; b, a Mod b
        Case "\":       Debug.Print "a \ b", a; "\"; b, a \ b
        Case Else:      Debug.Print "a "; opr; " b", a; opr; b, Evaluate(a & opr & b)
    End Select
Next opr
End Sub


option explicit
dim a, b
wscript.stdout.write "A? "
a = wscript.stdin.readline
wscript.stdout.write "B? "
b = wscript.stdin.readline

a = int( a )
b = int( b )

wscript.echo "a + b=", a + b
wscript.echo "a - b=", a - b
wscript.echo "a * b=", a * b
wscript.echo "a / b=", a / b
wscript.echo "a \ b=", a \ b
wscript.echo "a mod b=", a mod b
wscript.echo "a ^ b=", a ^ b


#1 = Get_Num("Give number a: ")
#2 = Get_Num("Give number b: ")
Message("a + b = ") Num_Type(#1 + #2)
Message("a - b = ") Num_Type(#1 - #2)
Message("a * b = ") Num_Type(#1 * #2)
Message("a / b = ") Num_Type(#1 / #2)
Message("a % b = ") Num_Type(#1 % #2)


module main;
  integer a, b;
  integer suma, resta, producto;
  integer division, resto, expo;

  initial begin
    a = -12;
    b = 7;

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

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


let a = float2nr(input("Number 1: ") + 0)
let b = float2nr(input("Number 2: ") + 0)
echo "\nSum: " . (a + b)
echo "Difference: " . (a - b)
echo "Product: " . (a * b)
" The result of an integer division is truncated
echo "Quotient: " . (a / b)
" The sign of the result of the remainder operation matches the sign of
" the first operand
echo "Remainder: " . (a % b)


Imports System.Console
Module Module1
  Sub Main
    Dim a = CInt(ReadLine)
    Dim b = CInt(ReadLine)
    WriteLine("Sum " & a + b)
    WriteLine("Difference " & a - b)
    WriteLine("Product " & a - b)
    WriteLine("Quotient " & a / b)
    WriteLine("Integer Quotient " & a \ b)
    WriteLine("Remainder " & a Mod b)
    WriteLine("Exponent " & a ^ b)
  End Sub
End Module


// Arithmetic-integer in V
// Tectonics: v run arithmetic-integer.v
module main
import math
import os

// starts here
pub fn main() {
    mut a := 0
    mut b := 0

    // get numbers from console
    print("Enter two integer numbers, separated by a space: ")
    text := os.get_raw_line()
    values := text.split(' ')
    a = values[0].int()
    b = values[1].int()

    // 4 basics, remainder, no exponentiation operator
    println("values:           a $a, b $b")
    println("sum:              a + b = ${a + b}")
    println("difference:       a - b = ${a - b}")
    println("product:          a * b = ${a * b}")
    println("integer quotient: a / b = ${a / b}, truncation")
    println("remainder:        a % b = ${a % b}, sign follows dividend")

    println("no exponentiation operator")
    println("  math.pow:    pow(a,b) = ${math.pow(a,b)}")
}


a <- (read)
b <- (read)
prn "sum: " a+b
prn "difference: " a-b
prn "product: " a*b
prn "quotient: " a/b
prn "integer quotient: " (int a/b)
prn "remainder: " a%b
prn "exponent: " a^b


import "io" for Stdin, Stdout
System.write("first number:     ")
Stdout.flush()
var a = Num.fromString(Stdin.readLine())
System.write("second number:    ")
Stdout.flush()
var b = Num.fromString(Stdin.readLine())
System.print("sum:              %(a + b)")
System.print("difference:       %(a - b)")
System.print("product:          %(a * b)")
System.print("integer quotient: %((a / b).floor)")
System.print("remainder:        %(a % b)")
System.print("exponentiation:   %(a.pow(b))")


arithm: mov      cx,          a
        mov      bx,          b
        xor      dx,          dx

        mov      ax,          cx
        add      ax,          bx
        mov      sum,         ax

        mov      ax,          cx
        imul     bx
        mov      product,     ax

        mov      ax,          cx
        sub      ax,          bx
        mov      difference,  ax

        mov      ax,          cx
        idiv     bx
        mov      quotient,    ax
        mov      remainder,   dx

        ret


(DEFUN INTEGER-ARITHMETIC ()
    (DISPLAY "Enter two integers separated by a space.")
    (NEWLINE)
    (DISPLAY "> ")
    (DEFINE A (READ))
    (DEFINE B (READ))
    (DISPLAY `(SUM ,(+ A B)))
    (NEWLINE)
    (DISPLAY `(DIFFERENCE ,(- A B)))
    (NEWLINE)
    (DISPLAY `(PRODUCT ,(* A B)))
    (NEWLINE)
    (DISPLAY `(QUOTIENT ,(QUOTIENT A B))) ; truncates towards zero
    (NEWLINE)
    (DISPLAY `(REMAINDER ,(REM A B))) ; takes sign of first operand
    (NEWLINE)
    (DISPLAY `(EXPONENTIATION ,(EXPT A B))))


include c:\cxpl\codes;
int A, B;
[A:= IntIn(0);
 B:= IntIn(0);
IntOut(0, A+B); CrLf(0);
IntOut(0, A-B); CrLf(0);
IntOut(0, A*B); CrLf(0);
IntOut(0, A/B); CrLf(0);        \truncates toward zero
IntOut(0, rem(0)); CrLf(0);     \remainder's sign matches first operand (A)
]


<xsl:template name="arithmetic">
  <xsl:param name="a">5</xsl:param>
  <xsl:param name="b">2</xsl:param>
  <fo:block>a + b = <xsl:value-of select="$a + $b"/></fo:block>
  <fo:block>a - b = <xsl:value-of select="$a - $b"/></fo:block>
  <fo:block>a * b = <xsl:value-of select="$a * $b"/></fo:block>
  <fo:block>a / b = <xsl:value-of select="round($a div $b)"/></fo:block>
  <fo:block>a mod b = <xsl:value-of select="$a mod $b"/></fo:block>
 </xsl:template>


input "ingrese un numero? " a
input "ingrese otro numero? " b

print "suma      ", a, " + ", b, " = ", (a + b)
print "resta     ", a, " - ", b, " = ", (a - b)
print "producto  ", a, " * ", b, " = ", (a * b)
print "division  ", a, " \ ", b, " = ", int(a / b)
print "modulo    ", a, " % ", b, " = ", mod(a, b)
print "potencia  ", a, " ^ ", b, " = ", (a ^ b)
end


x = y = 0;
read, x, y;
write, "x + y =", x + y;
write, "x - y =", x - y;
write, "x * y =", x * y;
write, "x / y =", x / y; // rounds toward zero
write, "x % y =", x % y; // remainder; matches sign of first operand when operands' signs differ
write, "x ^ y =", x ^ y; // exponentiation


x,y:=ask("Two ints: ").split(" ").apply("toInt");
println("x+y = ",x + y);
println("x-y = ",x - y);
println("x*y = ",x * y);
println("x/y = ",x / y); // rounds toward zero
println("x%y = ",x % y); // remainder; matches sign of first operand when operands' signs differ
println("x.divr(y) = ",x.divr(y)); // (x/y,remainder); sign as above


module Main;
var
	i,j: integer;
begin
	write("A integer?:");readln(i);
	write("another?: ");readln(j);
	writeln("sum: ",i + j);
	writeln("difference: ", i - j);
	writeln("product: ", i * j);
	writeln("quotient: ", i div j);
	writeln("remainder: ", i mod j);
end Main.


type My_Pointer is access My_Object;
for My_Pointer'Storage_Pool use My_Pool;


program Arena_storage_pool;

{$APPTYPE CONSOLE}

uses
  Winapi.Windows,
  System.SysUtils,
  system.generics.collections;

type
  TPool = class
  private
    FStorage: TList<Pointer>;
  public
    constructor Create;
    destructor Destroy; override;
    function Allocate(aSize: Integer): Pointer;
    function Release(P: Pointer): Integer;
  end;

{ TPool }

function TPool.Allocate(aSize: Integer): Pointer;
begin
  Result := GetMemory(aSize);
  if Assigned(Result) then
    FStorage.Add(Result);
end;

constructor TPool.Create;
begin
  FStorage := TList<Pointer>.Create;
end;

destructor TPool.Destroy;
var
  p: Pointer;
begin
  while FStorage.Count > 0 do
  begin
    p := FStorage[0];
    Release(p);
  end;
  FStorage.Free;
  inherited;
end;

function TPool.Release(P: Pointer): Integer;
var
  index: Integer;
begin
  index := FStorage.IndexOf(P);
  if index > -1 then
    FStorage.Delete(index);
  FreeMemory(P)
end;

var
  Manager: TPool;
  int1, int2: PInteger;
  str: PChar;

begin
  Manager := TPool.Create;
  int1 := Manager.Allocate(sizeof(Integer));
  int1^ := 5;

  int2 := Manager.Allocate(sizeof(Integer));
  int2^ := 3;

  writeln('Allocate at addres ', cardinal(int1).ToHexString, ' with value of ', int1^);
  writeln('Allocate at addres ', cardinal(int2).ToHexString, ' with value of ', int2^);

  Manager.Free;
  readln;
end.


-module( arena_storage_pool ).

-export( [task/0] ).

task() ->
      Pid = erlang:spawn_opt( fun() -> loop([]) end, [{min_heap_size, 10000}] ),
      set( Pid, 1, ett ),
      set( Pid, "kalle", "hobbe" ),
      V1 = get( Pid, 1 ),
      V2 = get( Pid, "kalle" ),
      true = (V1 =:= ett) and (V2	=:= "hobbe"),
      erlang:exit( Pid, normal ).

get( Pid, Key ) ->
     Pid ! {get, Key, erlang:self()},
     receive
	{value, Value, Pid} -> Value
     end.

loop( List ) ->
      receive
	{set, Key, Value} -> loop( [{Key, Value} | proplists:delete(Key, List)] );
	{get, Key, Pid} ->
	      Pid ! {value, proplists:get_value(Key, List), erlang:self()},
	      loop( List )
	end.

set( Pid, Key, Value ) -> Pid ! {set, Key, Value}.


      SUBROUTINE CHECK(A,N)	!Inspect matrix A.
       REAL A(:,:)	!The matrix, whatever size it is.
       INTEGER N	!The order.
       REAL B(N,N)	!A scratchpad, size known on entry..
       INTEGER, ALLOCATABLE::TROUBLE(:)	!But for this, I'll decide later.
       INTEGER M

        M = COUNT(A(1:N,1:N).LE.0)	!Some maximum number of troublemakers.

        ALLOCATE (TROUBLE(1:M**3))	!Just enough.

        DEALLOCATE(TROUBLE)		!Not necessary.
      END SUBROUTINE CHECK		!As TROUBLE is declared within CHECK.


/' FreeBASIC admite tres tipos básicos de asignación de memoria:
- La asignación estática se produce para variables estáticas y globales.
La memoria se asigna una vez cuando el programa se ejecuta y persiste durante
toda la vida del programa.
- La asignación de pila se produce para parámetros de procedimiento y variables
locales. La memoria se asigna cuando se ingresa el bloque correspondiente y se
libera cuando se deja el bloque, tantas veces como sea necesario.
- La asignación dinámica es el tema de este artículo.

La asignación estática y la asignación de pila tienen dos cosas en común:
- El tamaño de la variable debe conocerse en el momento de la compilación.
- La asignación y desasignación de memoria ocurren automáticamente (cuando se
crea una instancia de la variable y luego se destruye). El usuario no puede
anticipar la destrucción de dicha variable.

La mayoría de las veces, eso está bien. Sin embargo, hay situaciones en las que
una u otra de estas restricciones causan problemas (cuando la memoria necesaria
depende de la entrada del usuario, el tamaño solo se puede determinar durante el
tiempo de ejecución).

1) Palabras clave para la asignación de memoria dinámica:
Hay dos conjuntos de palabras clave para la asignación / desasignación dinámica:
*  Allocate / Callocate / Reallocate / Deallocate: para la asignación de
memoria bruta y luego la desasignación, para tipos simples predefinidos
o búferes de usuario.
*  New / Delete: para asignación de memoria + construcción, luego
destrucción + desasignación.
Se desaconseja encarecidamente mezclar palabras clave entre estos dos
conjuntos cuando se gestiona un mismo bloque de memoria.

2) Variante usando Redim / Erase:
FreeBASIC también admite matrices dinámicas (matrices de longitud variable).
La memoria utilizada por una matriz dinámica para almacenar sus elementos se
asigna en tiempo de ejecución en el montón. Las matrices dinámicas pueden
contener tipos simples y objetos complejos.
Al usar Redim, el usuario no necesita llamar al Constructor / Destructor
porque Redim lo hace automáticamente cuando agrega / elimina un elemento.
Erase luego destruye todos los elementos restantes para liberar completamente
la memoria asignada a ellos.

'/

Type UDT
    Dim As String S = "FreeBASIC"              '' induce an implicit constructor and destructor
End Type

' 3 then 4 objects: Callocate, Reallocate, Deallocate, (+ .constructor + .destructor)
Dim As UDT Ptr p1 = Callocate(3, Sizeof(UDT))  '' allocate cleared memory for 3 elements (string descriptors cleared,
''     but maybe useless because of the constructor's call right behind)
For I As Integer = 0 To 2
    p1[I].Constructor()                        '' call the constructor on each element
Next I
For I As Integer = 0 To 2
    p1[I].S &= Str(I)                          '' add the element number to the string of each element
Next I
For I As Integer = 0 To 2
    Print "'" & p1[I].S & "'",                 '' print each element string
Next I
Print
p1 = Reallocate(p1, 4 * Sizeof(UDT))           '' reallocate memory for one additional element
Clear p1[3], 0, 3 * Sizeof(Integer)            '' clear the descriptor of the additional element,
''     but maybe useless because of the constructor's call right behind
p1[3].Constructor()                            '' call the constructor on the additional element
p1[3].S &= Str(3)                              '' add the element number to the string of the additional element
For I As Integer = 0 To 3
    Print "'" & p1[I].S & "'",                 '' print each element string
Next I
Print
For I As Integer = 0 To 3
    p1[I].Destructor()                         '' call the destructor on each element
Next I
Deallocate(p1)                                 '' deallocate the memory
Print

' 3 objects: New, Delete
Dim As UDT Ptr p2 = New UDT[3]                 '' allocate memory and construct 3 elements
For I As Integer = 0 To 2
    p2[I].S &= Str(I)                          '' add the element number to the string of each element
Next I
For I As Integer = 0 To 2
    Print "'" & p2[I].S & "'",                 '' print each element string
Next I
Print
Delete [] p2                                   '' destroy the 3 element and deallocate the memory
Print

' 3 objects: Placement New, (+ .destructor)
Redim As Byte array(0 To 3 * Sizeof(UDT) - 1)  '' allocate buffer for 3 elements
Dim As Any Ptr p = @array(0)
Dim As UDT Ptr p3 = New(p) UDT[3]              '' only construct the 3 elements in the buffer (placement New)
For I As Integer = 0 To 2
    p3[I].S &= Str(I)                          '' add the element number to the string of each element
Next I
For I As Integer = 0 To 2
    Print "'" & p3[I].S & "'",                 '' print each element string
Next I
Print
For I As Integer = 0 To 2
    p3[I].Destructor()                         '' call the destructor on each element
Next I
Erase array                                    '' deallocate the buffer
Print

' 3 then 4 objects: Redim, Erase
Redim As UDT p4(0 To 2)                        '' define a dynamic array of 3 elements
For I As Integer = 0 To 2
    p4(I).S &= Str(I)                          '' add the element number to the string of each element
Next I
For I As Integer = 0 To 2
    Print "'" & p4(I).S & "'",                 '' print each element string
Next I
Print
Redim Preserve p4(0 To 3)                      '' resize the dynamic array for one additional element
p4(3).S &= Str(3)                              '' add the element number to the string of the additional element
For I As Integer = 0 To 3
    Print "'" & p4(I).S & "'",                 '' print each element string
Next I
Print
Erase p4                                       '' erase the dynamic array
Print
Sleep


package main

import (
    "fmt"
    "runtime"
    "sync"
)

// New to Go 1.3 are sync.Pools, basically goroutine-safe free lists.
// There is overhead in the goroutine-safety and if you do not need this
// you might do better by implementing your own free list.

func main() {
    // Task 1:  Define a pool (of ints).  Just as the task says, a sync.Pool
    // allocates individually and can free as a group.
    p := sync.Pool{New: func() interface{} {
        fmt.Println("pool empty")
        return new(int)
    }}
    // Task 2: Allocate some ints.
    i := new(int)
    j := new(int)
    // Show that they're usable.
    *i = 1
    *j = 2
    fmt.Println(*i + *j) // prints 3
    // Task 2 continued:  Put allocated ints in pool p.
    // Task explanation:  Variable p has a pool as its value.  Another pool
    // could be be created and assigned to a different variable.  You choose
    // a pool simply by using the appropriate variable, p here.
    p.Put(i)
    p.Put(j)
    // Drop references to i and j.  This allows them to be garbage collected;
    // that is, freed as a group.
    i = nil
    j = nil
    // Get ints for i and j again, this time from the pool.  P.Get may reuse
    // an object allocated above as long as objects haven't been garbage
    // collected yet; otherwise p.Get will allocate a new object.
    i = p.Get().(*int)
    j = p.Get().(*int)
    *i = 4
    *j = 5
    fmt.Println(*i + *j) // prints 9
    // One more test, this time forcing a garbage collection.
    p.Put(i)
    p.Put(j)
    i = nil
    j = nil
    runtime.GC()
    i = p.Get().(*int)
    j = p.Get().(*int)
    *i = 7
    *j = 8
    fmt.Println(*i + *j) // prints 15
}


coclass 'integerPool'
require 'jmf'
create=: monad define
  Lim=: y*SZI_jmf_
  Next=: -SZI_jmf_
  Pool=: mema Lim
)

destroy=: monad define
  memf Pool
  codestroy''
)

alloc=: monad define
  assert.Lim >: Next=: Next+SZI_jmf_
  r=.Pool,Next,1,JINT
  r set y
  r
)

get=: adverb define
  memr m
)

set=: adverb define
  y memw m
)


matrix = zeros(Float64, (1000,1000,1000))
# use matrix, then when done set variable to 0 to garbage collect the matrix:
matrix = 0 # large memory pool will now be collected when needed


// Kotlin Native v0.5

import kotlinx.cinterop.*

fun main(args: Array<String>) {
    memScoped {
        val intVar1 = alloc<IntVar>()
        intVar1.value = 1
        val intVar2 = alloc<IntVar>()
        intVar2.value = 2
        println("${intVar1.value} + ${intVar2.value} = ${intVar1.value + intVar2.value}")
    }
    // native memory used by intVar1 & intVar2 is automatically freed when memScoped block ends
}


pool = {} -- create an "arena" for the variables a,b,c,d
pool.a = 1 -- individually allocated..
pool.b = "hello"
pool.c = true
pool.d = { 1,2,3 }
pool = nil -- release reference allowing garbage collection of entire structure


####################################################################################################
# Pool management.

# Pool of objects.
type
  Block[Size: static Positive, T] = ref array[Size, T]
  Pool[BlockSize: static Positive, T] = ref object
    blocks: seq[Block[BlockSize, T]]        # List of blocks.
    lastindex: int                          # Last object index in the last block.

#---------------------------------------------------------------------------------------------------

proc newPool(S: static Positive; T: typedesc): Pool[S, T] =
  ## Create a pool with blocks of "S" type "T" objects.

  new(result)
  result.blocks = @[new(Block[S, T])]
  result.lastindex = -1

#---------------------------------------------------------------------------------------------------

proc getItem(pool: Pool): ptr pool.T =
  ## Return a pointer on a node from the pool.

  inc pool.lastindex
  if pool.lastindex == pool.BlockSize:
    # Allocate a new block. It is initialized with zeroes.
    pool.blocks.add(new(Block[pool.BlockSize, pool.T]))
    pool.lastindex = 0
  result = cast[ptr pool.T](addr(pool.blocks[^1][pool.lastindex]))

####################################################################################################
# Example: use the pool to allocate nodes.

type

  # Node description.
  NodePtr = ptr Node
  Node = object
    value: int
    prev: NodePtr
    next: NodePtr

type NodePool = Pool[5000, Node]

proc newNode(pool: NodePool; value: int): NodePtr =
  ## Create a new node.

  result = pool.getItem()
  result.value = value
  result.prev = nil     # Not needed, allocated memory being initialized to 0.
  result.next = nil

proc test() =
  ## Build a circular list of nodes managed in a pool.

  let pool = newPool(NodePool.BlockSize, Node)
  var head = pool.newNode(0)
  var prev = head
  for i in 1..11999:
    let node = pool.newNode(i)
    node.prev = prev
    prev.next = node
  # Display information about the pool state.
  echo "Number of allocated blocks: ", pool.blocks.len
  echo "Number of nodes in the last block: ", pool.lastindex + 1

test()

# No need to free the pool. This is done automatically as it has been allocated by "new".


Object Class new: MyClass(a, b, c)
MyClass new


'==============
Class ArenaPool
'==============

string buf
sys    pb,ii

method Setup(sys n) as sys {buf=nuls n : pb=strptr buf : ii=0 : return pb}
method Alloc(sys n) as sys {method=pb+ii : ii+=n}
method Empty()             {buf="" : pb=0 : ii=0}

end class

macro Create(type,name,qty,pool)
  type name[qty] at (pool##.alloc qty * sizeof type)
end macro

'====
'DEMO
'====

ArenaPool pool : pool.setup 1000 * sizeof int

Create int,i,100,pool
Create int,j,100,pool

j[51] <= 1,2,3,4,5

print j[51] j[52] j[53] j[54] j[55] 'result 15

pool.empty


pari_init(1<<20, 0); // Initialize PARI with a stack size of 1 MB.
GEN four = addii(gen_2, gen_2); // On the stack
GEN persist = gclone(four); // On the heap


without js
atom mem = allocate(size,true)


(malloc 1000 'raw)             ; raw allocation, bypass the GC, requires free()-ing
(malloc 1000 'uncollectable)   ; no GC, for use with other GCs that Racket can be configured with
(malloc 1000 'atomic)          ; a block of memory without internal pointers
(malloc 1000 'nonatomic)       ; a block of pointers
(malloc 1000 'eternal)         ; uncollectable & atomic, similar to raw malloc but no freeing
(malloc 1000 'stubborn)        ; can be declared immutable when mutation is done
(malloc 1000 'interior)        ; allocate an immovable block with possible pointers into it
(malloc 1000 'atomic-interior) ; same for atomic chunks
(malloc-immobile-cell v)       ; allocates a single cell that the GC will not move


/*REXX doesn't have declarations/allocations of variables, */
/*     but this is the closest to an allocation:           */

stemmed_array.= 0    /*any undefined element will have this value. */

stemmed_array.1    = '1st entry'
stemmed_array.2    = '2nd entry'
stemmed_array.6000 = 12 ** 2
stemmed_array.dog  = stemmed_array.6000 / 2

drop stemmed_array.


#![feature(rustc_private)]

extern crate arena;

use arena::TypedArena;

fn main() {
    // Memory is allocated using the default allocator (currently jemalloc).  The memory is
    // allocated in chunks, and when one chunk is full another is allocated.  This ensures that
    // references to an arena don't become invalid when the original chunk runs out of space.  The
    // chunk size is configurable as an argument to TypedArena::with_capacity if necessary.
    let arena = TypedArena::new();

    // The arena crate contains two types of arenas: TypedArena and Arena.  Arena is
    // reflection-basd and slower, but can allocate objects of any type.  TypedArena is faster, and
    // can allocate only objects of one type.  The type is determined by type inference--if you try
    // to allocate an integer, then Rust's compiler knows it is an integer arena.
    let v1 = arena.alloc(1i32);

    // TypedArena returns a mutable reference
    let v2 = arena.alloc(3);
    *v2 += 38;
    println!("{}", *v1 + *v2);

    // The arena's destructor is called as it goes out of scope, at which point it deallocates
    // everything stored within it at once.
}


package require Tcl 8.6
oo::class create Pool {
    superclass oo::class
    variable capacity pool busy
    unexport create
    constructor args {
	next {*}$args
	set capacity 100
	set pool [set busy {}]
    }
    method new {args} {
	if {[llength $pool]} {
	    set pool [lassign $pool obj]
	} else {
	    if {[llength $busy] >= $capacity} {
		throw {POOL CAPACITY} "exceeded capacity: $capacity"
	    }
	    set obj [next]
	    set newobj [namespace current]::[namespace tail $obj]
	    rename $obj $newobj
	    set obj $newobj
	}
	try {
	    [info object namespace $obj]::my Init {*}$args
	} on error {msg opt} {
	    lappend pool $obj
	    return -options $opt $msg
	}
	lappend busy $obj
	return $obj
    }
    method ReturnToPool obj {
	try {
	    if {"Finalize" in [info object methods $obj -all -private]} {
		[info object namespace $obj]::my Finalize
	    }
	} on error {msg opt} {
	    after 0 [list return -options $opt $msg]
	    return false
	}
	set idx [lsearch -exact $busy $obj]
	set busy [lreplace $busy $idx $idx]
	if {[llength $pool] + [llength $busy] + 1 <= $capacity} {
	    lappend pool $obj
	    return true
	} else {
	    return false
	}
    }
    method capacity {{value {}}} {
	if {[llength [info level 0]] == 3} {
	    if {$value < $capacity} {
		while {[llength $pool] > 0 && [llength $pool] + [llength $busy] > $value} {
		    set pool [lassign $pool obj]
		    rename $obj {}
		}
	    }
	    set capacity [expr {$value >> 0}]
	} else {
	    return $capacity
	}
    }
    method clearPool {} {
	foreach obj $busy {
	    $obj destroy
	}
    }
    method destroy {} {
	my clearPool
	next
    }
    self method create {class {definition {}}} {
	set cls [next $class $definition]
	oo::define $cls method destroy {} {
	    if {![[info object namespace [self class]]::my ReturnToPool [self]]} {
		next
	    }
	}
	return $cls
    }
}


var arena = List.filled(5, 0)  // allocate memory for 5 integers
for (i in 0..4) arena[i] = i   // insert some integers
System.print(arena)            // print them
arena = null                   // make arena eligible for garbage collection
System.gc()                    // request immediate garbage collection


var pool=List();  // pool could be any mutable container
pool.append(Data(0,1234));   // allocate mem blob and add to pool
pool=Void; // free the pool and everything in it.


V z1 = 1.5 + 3i
V z2 = 1.5 + 1.5i
print(z1 + z2)
print(z1 - z2)
print(z1 * z2)
print(z1 / z2)
print(-z1)
print(conjugate(z1))
print(abs(z1))
print(z1 ^ z2)
print(z1.real)
print(z1.imag)


INCLUDE "D2:REAL.ACT" ;from the Action! Tool Kit

DEFINE R_="+0"
DEFINE I_="+6"
TYPE Complex=[CARD cr1,cr2,cr3,ci1,ci2,ci3]

BYTE FUNC Positive(REAL POINTER x)
  BYTE ARRAY tmp

  tmp=x
  IF (tmp(0)&$80)=$00 THEN
    RETURN (1)
  FI
RETURN (0)

PROC PrintComplex(Complex POINTER x)
  PrintR(x R_)
  IF Positive(x I_) THEN
    Put('+)
  FI
  PrintR(x I_) Put('i)
RETURN

PROC PrintComplexXYZ(Complex POINTER x,y,z CHAR ARRAY s)
  Print("(") PrintComplex(x)
  Print(") ") Print(s)
  Print(" (") PrintComplex(y)
  Print(") = ") PrintComplex(z)
  PutE()
RETURN

PROC PrintComplexXY(Complex POINTER x,y CHAR ARRAY s)
  Print(s)
  Print("(") PrintComplex(x)
  Print(") = ") PrintComplex(y)
  PutE()
RETURN

PROC ComplexAdd(Complex POINTER x,y,res)
  RealAdd(x R_,y R_,res R_) ;res.r=x.r+y.r
  RealAdd(x I_,y I_,res I_) ;res.i=x.i+y.i
RETURN

PROC ComplexSub(Complex POINTER x,y,res)
  RealSub(x R_,y R_,res R_) ;res.r=x.r-y.r
  RealSub(x I_,y I_,res I_) ;res.i=x.i-y.i
RETURN

PROC ComplexMult(Complex POINTER x,y,res)
  REAL tmp1,tmp2

  RealMult(x R_,y R_,tmp1)  ;tmp1=x.r*y.r
  RealMult(x I_,y I_,tmp2)  ;tmp2=x.i*y.i
  RealSub(tmp1,tmp2,res R_) ;res.r=x.r*y.r-x.i*y.i

  RealMult(x R_,y I_,tmp1)  ;tmp1=x.r*y.i
  RealMult(x I_,y R_,tmp2)  ;tmp2=x.i*y.r
  RealAdd(tmp1,tmp2,res I_) ;res.i=x.r*y.i+x.i*y.r
RETURN

PROC ComplexDiv(Complex POINTER x,y,res)
  REAL tmp1,tmp2,tmp3,tmp4

  RealMult(x R_,y R_,tmp1)  ;tmp1=x.r*y.r
  RealMult(x I_,y I_,tmp2)  ;tmp2=x.i*y.i
  RealAdd(tmp1,tmp2,tmp3)   ;tmp3=x.r*y.r+x.i*y.i
  RealMult(y R_,y R_,tmp1)  ;tmp1=y.r^2
  RealMult(y I_,y I_,tmp2)  ;tmp2=y.i^2
  RealAdd(tmp1,tmp2,tmp4)   ;tmp4=y.r^2+y.i^2
  RealDiv(tmp3,tmp4,res R_) ;res.r=(x.r*y.r+x.i*y.i)/(y.r^2+y.i^2)

  RealMult(x I_,y R_,tmp1)  ;tmp1=x.i*y.r
  RealMult(x R_,y I_,tmp2)  ;tmp2=x.r*y.i
  RealSub(tmp1,tmp2,tmp3)   ;tmp3=x.i*y.r-x.r*y.i
  RealDiv(tmp3,tmp4,res I_) ;res.i=(x.i*y.r-x.r*y.i)/(y.r^2+y.i^2)
RETURN

PROC ComplexNeg(Complex POINTER x,res)
  REAL neg

  ValR("-1",neg)            ;neg=-1
  RealMult(x R_,neg,res R_) ;res.r=-x.r
  RealMult(x I_,neg,res I_) ;res.r=-x.r
RETURN

PROC ComplexInv(Complex POINTER x,res)
  REAL tmp1,tmp2,tmp3

  RealMult(x R_,x R_,tmp1)  ;tmp1=x.r^2
  RealMult(x I_,x I_,tmp2)  ;tmp2=x.i^2
  RealAdd(tmp1,tmp2,tmp3)   ;tmp3=x.r^2+x.i^2
  RealDiv(x R_,tmp3,res R_) ;res.r=x.r/(x.r^2+x.i^2)

  ValR("-1",tmp1)           ;tmp1=-1
  RealMult(x I_,tmp1,tmp2)  ;tmp2=-x.i
  RealDiv(tmp2,tmp3,res I_) ;res.i=-x.i/(x.r^2+x.i^2)
RETURN

PROC ComplexConj(Complex POINTER x,res)
  REAL neg

  ValR("-1",neg)            ;neg=-1
  RealAssign(x R_,res R_)   ;res.r=x.r
  RealMult(x I_,neg,res I_) ;res.i=-x.i
RETURN

PROC Main()
  Complex x,y,res

  IntToReal(5,x R_) IntToReal(3,x I_)
  IntToReal(4,y R_) ValR("-3",y I_)

  Put(125) PutE() ;clear screen

  ComplexAdd(x,y,res)
  PrintComplexXYZ(x,y,res,"+")

  ComplexSub(x,y,res)
  PrintComplexXYZ(x,y,res,"-")

  ComplexMult(x,y,res)
  PrintComplexXYZ(x,y,res,"*")

  ComplexDiv(x,y,res)
  PrintComplexXYZ(x,y,res,"/")

  ComplexNeg(y,res)
  PrintComplexXY(y,res,"        -")

  ComplexInv(y,res)
  PrintComplexXY(y,res,"     1 / ")

  ComplexConj(y,res)
  PrintComplexXY(y,res,"     conj")
RETURN


with Ada.Numerics.Generic_Complex_Types;
with Ada.Text_IO.Complex_IO;

procedure Complex_Operations is
   -- Ada provides a pre-defined generic package for complex types
   -- That package contains definitions for composition,
   -- negation, addition, subtraction, multiplication, division,
   -- conjugation, exponentiation, and absolute value, as well as
   -- basic comparison operations.
   -- Ada provides a second pre-defined package for sin, cos, tan, cot,
   -- arcsin, arccos, arctan, arccot, and the hyperbolic versions of
   -- those trigonometric functions.

   -- The package Ada.Numerics.Generic_Complex_Types requires definition
   -- with the real type to be used in the complex type definition.

   package Complex_Types is new Ada.Numerics.Generic_Complex_Types (Long_Float);
   use Complex_Types;
   package Complex_IO is new Ada.Text_IO.Complex_IO (Complex_Types);
   use Complex_IO;
   use Ada.Text_IO;

   A : Complex := Compose_From_Cartesian (Re => 1.0, Im => 1.0);
   B : Complex := Compose_From_Polar (Modulus => 1.0, Argument => 3.14159);
   C : Complex;

begin
   -- Addition
   C := A + B;
   Put("A + B = "); Put(C);
   New_Line;
   -- Multiplication
   C := A * B;
   Put("A * B = "); Put(C);
   New_Line;
   -- Inversion
   C := 1.0 / A;
   Put("1.0 / A = "); Put(C);
   New_Line;
   -- Negation
   C := -A;
   Put("-A = "); Put(C);
   New_Line;
   -- Conjugation
   Put("Conjugate(-A) = ");
   C := Conjugate (C); Put(C);
end Complex_Operations;


main:(
  FORMAT compl fmt = $g(-7,5)"⊥"g(-7,5)$;

  PROC compl operations = VOID: (
    LONG COMPL a = 1.0 ⊥ 1.0;
    LONG COMPL b = 3.14159 ⊥ 1.2;

    LONG COMPL c;

    printf(($x"a="f(compl fmt)l$,a));
    printf(($x"b="f(compl fmt)l$,b));

    # addition #
    c := a + b;
    printf(($x"a+b="f(compl fmt)l$,c));
    # multiplication #
    c := a * b;
    printf(($x"a*b="f(compl fmt)l$,c));
    # inversion #
    c := 1.0 / a;
    printf(($x"1/c="f(compl fmt)l$,c));
    # negation #
    c := -a;
    printf(($x"-a="f(compl fmt)l$,c))
  );
  compl operations
)


begin
    % show some complex arithmetic                                          %
    % returns c + d, using the builtin complex + operator                   %
    complex procedure cAdd ( complex value c, d ) ; c + d;
    % returns c * d, using the builtin complex * operator                   %
    complex procedure cMul ( complex value c, d ) ; c * d;
    % returns the negation of c, using the builtin complex unary - operator %
    complex procedure cNeg ( complex value c ) ; - c;
    % returns the inverse of c, using the builtin complex / operatror       %
    complex procedure cInv ( complex value c ) ; 1 / c;
    % returns the conjugate of c                                            %
    complex procedure cConj ( complex value c ) ; realpart( c ) - imag( imagpart( c ) );
    complex c, d;
    c := 1 + 2i;
    d := 3 + 4i;
    % set I/O format for real aand complex numbers                          %
    r_format := "A"; s_w := 0; r_w := 6; r_d := 2;
    write( "c      : ",        c      );
    write( "d      : ",           d   );
    write( "c + d  : ", cAdd(  c, d ) );
    write( "c * d  : ", cMul(  c, d ) );
    write( "-c     : ", cNeg(  c    ) );
    write( "1/c    : ", cInv(  c    ) );
    write( "conj c : ", cConj( c    ) )
end.


   x←1j1                ⍝assignment
   y←5.25j1.5
   x+y                  ⍝addition
6.25J2.5
   x×y                  ⍝multiplication
3.75J6.75
    ⌹x                  ⍝inversion
0.5j_0.5
    -x                  ⍝negation
¯1J¯1


a: to :complex [1 1]
b: to :complex @[pi 1.2]

print ["a:" a]
print ["b:" b]

print ["a + b:" a + b]
print ["a * b:" a * b]
print ["1 / a:" 1 / a]
print ["neg a:" neg a]
print ["conj a:" conj a]


Cset(C,1,1)
MsgBox % Cstr(C)  ; 1 + i*1
Cneg(C,C)
MsgBox % Cstr(C)  ; -1 - i*1
Cadd(C,C,C)
MsgBox % Cstr(C)  ; -2 - i*2
Cinv(D,C)
MsgBox % Cstr(D)  ; -0.25 + 0.25*i
Cmul(C,C,D)
MsgBox % Cstr(C)  ; 1 + i*0

Cset(ByRef C, re, im) {
   VarSetCapacity(C,16)
   NumPut(re,C,0,"double")
   NumPut(im,C,8,"double")
}
Cre(ByRef C) {
   Return NumGet(C,0,"double")
}
Cim(ByRef C) {
   Return NumGet(C,8,"double")
}
Cstr(ByRef C) {
   Return Cre(C) ((i:=Cim(C))<0 ? " - i*" . -i : " + i*" . i)
}
Cadd(ByRef C, ByRef A, ByRef B) {
   VarSetCapacity(C,16)
   NumPut(Cre(A)+Cre(B),C,0,"double")
   NumPut(Cim(A)+Cim(B),C,8,"double")
}
Cmul(ByRef C, ByRef A, ByRef B) {
   VarSetCapacity(C,16)
   t := Cre(A)*Cim(B)+Cim(A)*Cre(B)
   NumPut(Cre(A)*Cre(B)-Cim(A)*Cim(B),C,0,"double")
   NumPut(t,C,8,"double") ; A or B can be C!
}
Cneg(ByRef C, ByRef A) {
   VarSetCapacity(C,16)
   NumPut(-Cre(A),C,0,"double")
   NumPut(-Cim(A),C,8,"double")
}
Cinv(ByRef C, ByRef A) {
   VarSetCapacity(C,16)
   d := Cre(A)**2 + Cim(A)**2
   NumPut( Cre(A)/d,C,0,"double")
   NumPut(-Cim(A)/d,C,8,"double")
}


# simulate a struct using associative arrays
function complex(arr, re, im) {
    arr["re"] = re
    arr["im"] = im
}

function re(cmplx) {
    return cmplx["re"]
}

function im(cmplx) {
    return cmplx["im"]
}

function printComplex(cmplx) {
    print re(cmplx), im(cmplx)
}

function abs2(cmplx) {
    return re(cmplx) * re(cmplx) + im(cmplx) * im(cmplx)
}

function abs(cmplx) {
    return sqrt(abs2(cmplx))
}

function add(res, cmplx1, cmplx2) {
    complex(res, re(cmplx1) + re(cmplx2), im(cmplx1) + im(cmplx2))
}

function mult(res, cmplx1, cmplx2) {
    complex(res, re(cmplx1) * re(cmplx2) - im(cmplx1) * im(cmplx2), re(cmplx1) * im(cmplx2) + im(cmplx1) * re(cmplx2))
}

function scale(res, cmplx, scalar) {
    complex(res, re(cmplx) * scalar, im(cmplx) * scalar)
}

function negate(res, cmplx) {
    scale(res, cmplx, -1)
}

function conjugate(res, cmplx) {
    complex(res, re(cmplx), -im(cmplx))
}

function invert(res, cmplx) {
    conjugate(res, cmplx)
    scale(res, res, 1 / abs(cmplx))
}

BEGIN {
    complex(i, 0, 1)
    mult(i, i, i)
    printComplex(i)
}


TYPE complex
        real AS DOUBLE
        imag AS DOUBLE
END TYPE

DECLARE SUB suma (a AS complex, b AS complex, c AS complex)
DECLARE SUB rest (a AS complex, b AS complex, c AS complex)
DECLARE SUB mult (a AS complex, b AS complex, c AS complex)
DECLARE SUB divi (a AS complex, b AS complex, c AS complex)
DECLARE SUB neg (a AS complex, b AS complex)
DECLARE SUB inv (a AS complex, b AS complex)
DECLARE SUB conj (a AS complex, b AS complex)

CLS
DIM x AS complex
DIM y AS complex
DIM z AS complex
x.real = 1
x.imag = 1
y.real = 2
y.imag = 2

PRINT "Siendo x = "; x.real; "+"; x.imag; "i"
PRINT "     e y = "; y.real; "+"; y.imag; "i"
PRINT
CALL suma(x, y, z)
PRINT "x + y = "; z.real; "+"; z.imag; "i"
CALL rest(x, y, z)
PRINT "x - y = "; z.real; "+"; z.imag; "i"
CALL mult(x, y, z)
PRINT "x * y = "; z.real; "+"; z.imag; "i"
CALL divi(x, y, z)
PRINT "x / y = "; z.real; "+"; z.imag; "i"
CALL neg(x, z)
PRINT "   -x = "; z.real; "+"; z.imag; "i"
CALL inv(x, z)
PRINT "1 / x = "; z.real; "+"; z.imag; "i"
CALL conj(x, z)
PRINT "   x* = "; z.real; "+"; z.imag; "i"
END

SUB suma (a AS complex, b AS complex, c AS complex)
        c.real = a.real + b.real
        c.imag = a.imag + b.imag
END SUB

SUB inv (a AS complex, b AS complex)
        denom = a.real ^ 2 + a.imag ^ 2
        b.real = a.real / denom
        b.imag = -a.imag / denom
END SUB

SUB mult (a AS complex, b AS complex, c AS complex)
        c.real = a.real * b.real - a.imag * b.imag
        c.imag = a.real * b.imag + a.imag * b.real
END SUB

SUB neg (a AS complex, b AS complex)
        b.real = -a.real
        b.imag = -a.imag
END SUB

SUB conj (a AS complex, b AS complex)
    b.real =  a.real
    b.imag = -a.imag
END SUB

SUB divi (a AS complex, b AS complex, c AS complex)
    c.real = ((a.real * b.real + b.imag * a.imag) / (b.real ^ 2 + b.imag ^ 2))
    c.imag = ((a.imag * b.real - a.real * b.imag) / (b.real ^ 2 + b.imag ^ 2))
END SUB

SUB rest (a AS complex, b AS complex, c AS complex)
    c.real = a.real - b.real
    c.imag = a.imag - b.imag
END SUB


      DIM Complex{r, i}

      DIM a{} = Complex{} : a.r = 1.0 : a.i = 1.0
      DIM b{} = Complex{} : b.r = PI# : b.i = 1.2
      DIM o{} = Complex{}

      PROCcomplexadd(o{}, a{}, b{})
      PRINT "Result of addition is " FNcomplexshow(o{})
      PROCcomplexmul(o{}, a{}, b{})
      PRINT "Result of multiplication is " ; FNcomplexshow(o{})
      PROCcomplexneg(o{}, a{})
      PRINT "Result of negation is " ; FNcomplexshow(o{})
      PROCcomplexinv(o{}, a{})
      PRINT "Result of inversion is " ; FNcomplexshow(o{})
      END

      DEF PROCcomplexadd(dst{}, one{}, two{})
      dst.r = one.r + two.r
      dst.i = one.i + two.i
      ENDPROC

      DEF PROCcomplexmul(dst{}, one{}, two{})
      dst.r = one.r*two.r - one.i*two.i
      dst.i = one.i*two.r + one.r*two.i
      ENDPROC

      DEF PROCcomplexneg(dst{}, src{})
      dst.r = -src.r
      dst.i = -src.i
      ENDPROC

      DEF PROCcomplexinv(dst{}, src{})
      LOCAL denom : denom = src.r^2 + src.i^ 2
      dst.r = src.r / denom
      dst.i = -src.i / denom
      ENDPROC

      DEF FNcomplexshow(src{})
      IF src.i >= 0 THEN = STR$(src.r) + " + " +STR$(src.i) + "i"
      = STR$(src.r) + " - " + STR$(-src.i) + "i"


  (add=a b.!arg:(?a,?b)&!a+!b)
& ( multiply
  = a b.!arg:(?a,?b)&1+!a*!b+-1
  )
& (negate=.1+-1*!arg+-1)
& ( conjugate
  =   a b
    .   !arg:i&-i
      | !arg:-i&i
      | !arg:?a_?b&(conjugate$!a)_(conjugate$!b)
      | !arg
  )
& ( invert
  =   conjugated
    .   conjugate$!arg:?conjugated
      & multiply$(!arg,!conjugated)^-1*!conjugated
  )
& out$("(a+i*b)+(a+i*b) =" add$(a+i*b,a+i*b))
& out$("(a+i*b)+(a+-i*b) =" add$(a+i*b,a+-i*b))
& out$("(a+i*b)*(a+i*b) =" multiply$(a+i*b,a+i*b))
& out$("(a+i*b)*(a+-i*b) =" multiply$(a+i*b,a+-i*b))
& out$("-1*(a+i*b) =" negate$(a+i*b))
& out$("-1*(a+-i*b) =" negate$(a+-i*b))
& out$("sin$x = " sin$x)
& out$("conjugate sin$x  =" conjugate$(sin$x))
&   out
  $ ("sin$x minus conjugate sin$x =" sin$x+negate$(conjugate$(sin$x)))
& done;


#include <complex.h>
#include <stdio.h>

void cprint(double complex c)
{
  printf("%f%+fI", creal(c), cimag(c));
}
void complex_operations() {
  double complex a = 1.0 + 1.0I;
  double complex b = 3.14159 + 1.2I;

  double complex c;

  printf("\na="); cprint(a);
  printf("\nb="); cprint(b);

  // addition
  c = a + b;
  printf("\na+b="); cprint(c);
  // multiplication
  c = a * b;
  printf("\na*b="); cprint(c);
  // inversion
  c = 1.0 / a;
  printf("\n1/c="); cprint(c);
  // negation
  c = -a;
  printf("\n-a="); cprint(c);
  // conjugate
  c = conj(a);
  printf("\nconj a="); cprint(c); printf("\n");
}


namespace RosettaCode.Arithmetic.Complex
{
    using System;
    using System.Numerics;

    internal static class Program
    {
        private static void Main()
        {
            var number = Complex.ImaginaryOne;
            foreach (var result in new[] { number + number, number * number, -number, 1 / number, Complex.Conjugate(number) })
            {
                Console.WriteLine(result);
            }
        }
    }
}


#include <iostream>
#include <complex>
using std::complex;

void complex_operations() {
  complex<double> a(1.0, 1.0);
  complex<double> b(3.14159, 1.25);

  // addition
  std::cout << a + b << std::endl;
  // multiplication
  std::cout << a * b << std::endl;
  // inversion
  std::cout << 1.0 / a << std::endl;
  // negation
  std::cout << -a << std::endl;
  // conjugate
  std::cout << std::conj(a) << std::endl;
}