Arithmetic/Integer: Difference between revisions

m
m (syntax highlighting fixup automation)
imported>Arakov
 
(22 intermediate revisions by 16 users not shown)
Line 1:
{{Task|Basic language learning}}
[[Category:Arithmetic operations]]
[[Category:Arithmetic]]
{{basic data operation}} [[Category:Simple]]
{{Task|Basic language learning}}
 
{{basic data operation}}
;Task:
Get two integers from the user,   and then (for those two integers), display their:
Line 24:
 
=={{header|0815}}==
<syntaxhighlight lang="0815">
|~>|~#:end:>
<:61:x<:3d:=<:20:$==$~$=${~>%<:2c:~$<:20:~$
Line 52:
 
=={{header|11l}}==
<syntaxhighlight lang="11l">V a = Int(input())
V b = Int(input())
 
Line 78:
The sign of the quotient is determined by the rules of algebra.
The remainder has the same sign as the dividend.
<syntaxhighlight lang="360asm">* Arithmetic/Integer 04/09/2015
ARITHINT CSECT
USING ARITHINT,R12
Line 129:
=={{header|6502 Assembly}}==
Code is called as a subroutine (i.e. JSR Arithmetic). Specific OS/hardware routines for user input and printing are left unimplemented.
<syntaxhighlight lang="6502asm">Arithmetic: PHA ;push accumulator and X register onto stack
TXA
PHA
Line 179:
The 6502 has no opcodes for multiplication, division, or modulus; the routines for multiplication, division, and modulus given above can be heavily optimized at the expense of some clarity.
=={{header|68000 Assembly}}==
<syntaxhighlight lang="68000devpac">ADD.L D0,D1 ; add two numbers
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
SUB.L D1,D0 ; subtract D1 from D0
Line 194:
Exponentiation doesn't exist but can be implemented in a similar fashion to multiplication on the 6502:
 
<syntaxhighlight lang="68000devpac">Exponent:
;raises D0 to the D1 power. No overflow protection.
MOVE.L D0,D2
Line 206:
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
<syntaxhighlight lang=AArch64"aarch64 Assemblyassembly">
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program arith64.s */
Line 333:
.include "../includeARM64.inc"
</syntaxhighlight>
{{Output : Out}}
<PRE>
pi@debian-buster-64:~/asm64/rosetta/asm3 $ arith64 101 25
Line 344:
 
=={{header|ABAP}}==
<syntaxhighlight lang=ABAP"abap">report zz_arithmetic no standard page heading.
 
" Read in the two numbers from the user.
Line 371:
 
=={{header|ACL2}}==
<syntaxhighlight lang=Lisp"lisp">
:set-state-ok t
 
Line 394:
 
=={{header|Action!}}==
<syntaxhighlight lang=Action"action!">DEFINE NO_KEY="255"
DEFINE KEY_Y="43"
DEFINE KEY_N="35"
Line 446:
 
=={{header|Ada}}==
<syntaxhighlight lang="ada">with Ada.Text_Io;
with Ada.Integer_Text_IO;
 
Line 468:
 
=={{header|Aikido}}==
<syntaxhighlight lang="aikido">var a = 0
var b = 0
stdin -> a // read int from stdin
Line 484:
{{works with|ALGOL 68G|Any - tested with release [http://sourceforge.net/projects/algol68/files/algol68g/algol68g-1.18.0/algol68g-1.18.0-9h.tiny.el5.centos.fc11.i386.rpm/download 1.18.0-9h.tiny]}}
{{wont work with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release [http://sourceforge.net/projects/algol68/files/algol68toc/algol68toc-1.8.8d/algol68toc-1.8-8d.fc9.i386.rpm/download 1.8-8d] - due to extensive use of FORMATted transput}}
<syntaxhighlight lang="algol68">main:(
LONG INT a=355, b=113;
printf(($"a PLUS b = a+b = "gl$, a + b));
Line 515:
The Algol W integer division operator (called div) truncates towards zero.<br>
The result of the modulo operator (called rem) has the sign of the first operand when the operands have different signs.
<syntaxhighlight lang="algolw">begin
integer a, b;
write( "Enter 2 integers> " );
Line 531:
 
=={{header|AmigaE}}==
<syntaxhighlight lang="amigae">PROC main()
DEF a, b, t
WriteF('A = ')
Line 547:
 
=={{header|APL}}==
<syntaxhighlight lang="apl">∇res ← integer_arithmetic; l; r
l ← ⎕
r ← ⎕
Line 557:
=={{header|AppleScript}}==
 
<syntaxhighlight lang="applescript">set i1 to (text returned of (display dialog "Enter an integer value" default answer "")) as integer
set i2 to (text returned of (display dialog "Enter another integer value" default answer "")) as integer
 
Line 571:
{{output}}
 
<syntaxhighlight lang="applescript">{|integers|:{-57, 2}, difference:-59, product:-114, quotient:-28, remainder:-1, exponientiation:3249.0}</syntaxhighlight>
 
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang=ARM"arm Assemblyassembly">
 
/* ARM assembly Raspberry PI */
Line 870:
=={{header|Arturo}}==
 
<syntaxhighlight lang="rebol">a: to :integer input "give me the first number : "
b: to :integer input "give me the second number : "
 
Line 893:
 
=={{header|Asymptote}}==
<syntaxhighlight lang=Asymptote"asymptote">int a = -12;
int b = 7;
 
Line 913:
=={{header|AutoHotkey}}==
The quotient rounds towards 0 if both inputs are integers or towards negative infinity if either input is floating point. The sign of the remainder is always the same as the sign of the first parameter (dividend).
<syntaxhighlight lang="autohotkey">Gui, Add, Edit, va, 5
Gui, Add, Edit, vb, -3
Gui, Add, Button, Default, Compute
Line 934:
 
=={{header|Avail}}==
<syntaxhighlight lang=Avail"avail">Method "arithmetic demo_,_" is
[
a : integer,
Line 949:
 
=={{header|AWK}}==
<syntaxhighlight lang="awk">/^[ \t]*-?[0-9]+[ \t]+-?[0-9]+[ \t]*$/ {
print "add:", $1 + $2
print "sub:", $1 - $2
Line 966:
Same code as [[#Commodore_BASIC|Commodore BASIC]]
==={{header|BaCon}}===
<syntaxhighlight lang="freebasic">' Arthimetic/Integer
DECLARE a%, b%
INPUT "Enter integer A: ", a%
Line 978:
PRINT "MOD(", a%, ", ", b%, ") is ", MOD(a%, b%), ", same sign as first operand"
PRINT "POW(", a%, ", ", b%, ") is ", INT(POW(a%, b%))</syntaxhighlight>
 
==={{header|Chipmunk Basic}}===
{{works with|Chipmunk Basic|3.6.4}}
<syntaxhighlight lang="qbasic">10 input "Enter two integers separated by a comma: ";a,b
20 print " Sum: ";a+b
30 print "Difference: ";a-b
40 print " Product: ";a*b
50 print " Quontent: ";int(a/b)
60 print " Remainder: ";a mod b
70 print " Power: ";a^b</syntaxhighlight>
 
==={{header|Commodore BASIC}}===
<syntaxhighlight lang="basic">10 INPUT "ENTER A NUMBER"; A%
20 INPUT "ENTER ANOTHER NUMBER"; B%
30 PRINT "ADDITION:";A%;"+";B%;"=";A%+B%
Line 988 ⟶ 998:
70 PRINT "REMAINDER OR MODULO:";A%;"%";B%;"=";A%-INT(A%/B%)*B%
80 PRINT "POWER:";A%;"^";B%;"=";A%^B%</syntaxhighlight>
 
==={{header|GW-BASIC}}===
{{works with|PC-BASIC|any}}
{{works with|BASICA}}
<syntaxhighlight lang="qbasic">10 INPUT "Enter two integers separated by a comma: ";A, B
20 PRINT " Sum:"; A + B
30 PRINT "Difference:"; A - B
40 PRINT " Product:"; A * B
50 PRINT " Quontent:"; A \ B
60 PRINT " Remainder:"; A MOD B
70 PRINT " Power:"; A ^ B</syntaxhighlight>
 
==={{header|Minimal BASIC}}===
<syntaxhighlight lang="qbasic">10 PRINT "ENTER A INTEGER"
20 INPUT A
30 PRINT "ENTER ANOTHER INTEGER"
40 INPUT B
50 PRINT " SUM: "; A + B
60 PRINT "DIFFERENCE: "; A - B
70 PRINT " PRODUCT: "; A * B
80 PRINT " QUONTENT: "; INT(A / B)
90 PRINT " REMAINDER: "; A - INT(A / B ) * B
100 PRINT " POWER:"; A ^ B
110 END</syntaxhighlight>
 
==={{header|MSX Basic}}===
{{works with|MSX BASIC|any}}
<syntaxhighlight lang="qbasic">10 INPUT "Enter two integers separated by a comma: ";A, B
20 PRINT " Sum:"; A + B
30 PRINT "Difference:"; A - B
40 PRINT " Product:"; A * B
50 PRINT " Quontent:"; A \ B
60 PRINT " Remainder:"; A MOD B
70 PRINT " Power:"; A ^ B</syntaxhighlight>
 
==={{header|Quite BASIC}}===
<syntaxhighlight lang="qbasic">10 INPUT "enter a integer"; A
20 INPUT "enter another integer"; B
30 PRINT " Sum: "; A + B
40 PRINT "Difference: "; A - B
50 PRINT " Product: "; A * B
60 PRINT " Quontent: "; INT(A / B)
70 PRINT " Remainder: "; A - INT(A / B ) * B</syntaxhighlight>
 
==={{Header|Tiny BASIC}}===
<syntaxhighlight lang="Tiny BASIC"> LET A = 5
LET B = 3
PRINT "A = ", A, ", B = ", B
PRINT ""
PRINT A," + ",B," = ", A+B
PRINT A," - ",B," = ", A-B
PRINT A," * ",B," = ", A*B
PRINT A," / ",B," = ", A/B
PRINT A," % ",B," = ", A-(A/B)*B
REM Exponent calculation
LET X = 1
LET E = 0
10 IF X >= B THEN GOTO 30
LET T = E
IF E < A THEN LET E = A*A
IF T < A THEN GOTO 20
IF E >= A THEN LET E = E*A
20 LET X = X+1
GOTO 10
30 PRINT A," ^ ",B," = ", E
END</syntaxhighlight>
 
==={{header|True BASIC}}===
<syntaxhighlight lang="basic">
! RosettaCode: Integer Arithmetic
! True BASIC v6.007
Line 1,005 ⟶ 1,081:
PRINT "POW(";a;", ";b;") is ";INT(a^b)
GET KEY done
END</syntaxhighlight>
END
 
</syntaxhighlight>
==={{header|QBasic}}===
{{works with|QuickBasic|4.5}}
<syntaxhighlight lang="qbasic">function math(a!, b!)
print a + b
print a - b
Line 1,019 ⟶ 1,095:
 
Remainder sign matches: first operand
 
==={{header|XBasic}}===
{{works with|Windows XBasic}}
<syntaxhighlight lang="qbasic">PROGRAM "IntegerArithmetic"
VERSION "0.0000"
 
DECLARE FUNCTION Entry ()
 
FUNCTION Entry ()
a$ = INLINE$("Enter integer A: ")
a = SLONG(a$)
b$ = INLINE$("Enter integer B: ")
b = SLONG(b$)
PRINT
PRINT " Sum:"; a + b
PRINT "Difference:"; a - b
PRINT " Product:"; a * b
PRINT " Quontent:"; a / b
PRINT " Remainder:"; a MOD b
PRINT " Power:"; a ** b
END FUNCTION
END PROGRAM</syntaxhighlight>
 
=={{header|BASIC256}}==
<syntaxhighlight lang=BASIC256"basic256">
input "enter a number ?", a
input "enter another number ?", b
Line 1,035 ⟶ 1,133:
=={{header|Batch File}}==
{{works with|Windows 7| or later, haven't checked earlier versions}}
<syntaxhighlight lang="dos">
set /p equation=
set /a result=%equation%
Line 1,043 ⟶ 1,141:
 
=={{header|BBC BASIC}}==
<syntaxhighlight lang="bbcbasic"> INPUT "Enter the first integer: " first%
INPUT "Enter the second integer: " second%
Line 1,054 ⟶ 1,152:
 
=={{header|bc}}==
<syntaxhighlight lang="bc">define f(a, b) {
"add: "; a + b
"sub: "; a - b
Line 1,064 ⟶ 1,162:
 
=={{header|Befunge}}==
<syntaxhighlight lang="befunge">&&00p"=A",,:."=B ",,,00g.55+,v
v,+55.+g00:,,,,"A+B="<
>"=B-A",,,,:00g-.55+,v
Line 1,097 ⟶ 1,195:
=={{header|Bracmat}}==
The remainder returned by mod is non-negative. Furthermore, <code>div$(!a.!d)*!d+mod$(!a.!d):!a</code> for all integer <code>!a</code> and <code>!d</code>, <code>!d:~0</code>.
<syntaxhighlight lang=Bracmat"bracmat"> ( enter
= put$"Enter two integer numbers, separated by space:"
& get':(~/#?k_~/#?m|quit:?k)
Line 1,118 ⟶ 1,216:
=={{header|Brat}}==
Inspired by the second VBScript version.
<syntaxhighlight lang="brat">x = ask("First number: ").to_i
y = ask("Second number: ").to_i
 
Line 1,127 ⟶ 1,225:
 
=={{header|C}}==
<syntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
 
Line 1,146 ⟶ 1,244:
 
=={{header|C sharp|C#}}==
<syntaxhighlight lang="csharp">using System;
 
class Program
Line 1,172 ⟶ 1,270:
 
=={{header|C++}}==
<syntaxhighlight lang="cpp">#include <iostream>
 
int main()
Line 1,187 ⟶ 1,285:
=={{header|Chef}}==
 
<syntaxhighlight lang=Chef"chef">Number Soup.
 
Only reads single values.
Line 1,225 ⟶ 1,323:
 
=={{header|Clipper}}==
<syntaxhighlight lang="visualfoxpro">procedure Test( a, b )
? "a+b", a + b
? "a-b", a - b
Line 1,238 ⟶ 1,336:
 
=={{header|Clojure}}==
<syntaxhighlight lang="clojure">(defn myfunc []
(println "Enter x and y")
(let [x (read), y (read)]
Line 1,258 ⟶ 1,356:
 
=={{header|COBOL}}==
<syntaxhighlight lang="cobol"> IDENTIFICATION DIVISION.
PROGRAM-ID. Int-Arithmetic.
 
Line 1,305 ⟶ 1,403:
=={{header|Common Lisp}}==
 
<syntaxhighlight lang="lisp">(defun arithmetic (&optional (a (read *query-io*)) (b (read *query-io*)))
(mapc
(lambda (op)
Line 1,336 ⟶ 1,434:
=={{header|Component Pascal}}==
Works with Gardens Point Component Pascal
<syntaxhighlight lang="oberon2">
MODULE Arithmetic;
IMPORT CPmain,Console,RTS;
Line 1,376 ⟶ 1,474:
</pre>
Works with BlackBox Component Builder
<syntaxhighlight lang="oberon2">
MODULE Arithmetic;
IMPORT StdLog,DevCommanders,TextMappers;
Line 1,422 ⟶ 1,520:
 
=={{header|Crystal}}==
<syntaxhighlight lang="crystal">a = gets.not_nil!.to_i64
b = gets.not_nil!.to_i64
 
Line 1,435 ⟶ 1,533:
 
=={{header|D}}==
<syntaxhighlight lang="d">import std.stdio, std.string, std.conv;
 
void main() {
Line 1,463 ⟶ 1,561:
===Shorter Version===
Same output.
<syntaxhighlight lang="d">import std.stdio, std.string, std.conv, std.meta;
 
void main() {
Line 1,477 ⟶ 1,575:
}</syntaxhighlight>
Division and modulus are defined as in C99.
 
=={{header|Dart}}==
<syntaxhighlight lang="dart">import 'dart:io';
import 'dart:math' show pow;
 
void main() {
print('enter a integer: ');
int a = int.parse(stdin.readLineSync());
print('enter another integer: ');
int b = int.parse(stdin.readLineSync());
 
print('a + b = ${a + b}');
print('a - b = ${a - b}');
print('a * b = ${a * b}');
print('a / b = ${a ~/ b}');
print('a % b = ${a % b}');
print('a ^ b = ${pow(a, b)}');
 
//Integer division uses the '~/' operator
}</syntaxhighlight>
 
=={{header|dc}}==
<syntaxhighlight lang="dc">[Enter 2 integers on 1 line.
Use whitespace to separate. Example: 2 3
Use underscore for negative integers. Example: _10
Line 1,491 ⟶ 1,609:
 
=={{header|DCL}}==
<syntaxhighlight lang=DCL"dcl">$ inquire a "Enter first number"
$ a = f$integer( a )
$ inquire b "Enter second number"
Line 1,516 ⟶ 1,634:
 
=={{header|Delphi}}==
<syntaxhighlight lang=Delphi"delphi">program IntegerArithmetic;
 
{$APPTYPE CONSOLE}
Line 1,537 ⟶ 1,655:
 
=={{header|DWScript}}==
<syntaxhighlight lang="delphi">var a := StrToInt(ParamStr(0));
var b := StrToInt(ParamStr(1));
 
Line 1,553 ⟶ 1,671:
Dyalect has no operator for exponential.
 
<syntaxhighlight lang=Dyalect"dyalect">let a = 6
let b = 4
Line 1,564 ⟶ 1,682:
=={{header|E}}==
 
<syntaxhighlight lang="e">def arithmetic(a :int, b :int) {
return `$\
Sum: ${a + b}
Line 1,575 ⟶ 1,693:
=={{header|EasyLang}}==
 
<syntaxhighlight lang="text">a = number input
b = number input
print a + b
Line 1,585 ⟶ 1,703:
 
=={{header|ECL}}==
<syntaxhighlight lang=ECL"ecl">
ArithmeticDemo(INTEGER A,INTEGER B) := FUNCTION
ADDit := A + B;
Line 1,621 ⟶ 1,739:
=={{header|Efene}}==
 
<syntaxhighlight lang="efene">@public
run = fn () {
 
Line 1,640 ⟶ 1,758:
{{works with|SmartEiffel|2.4}}
In a file called main.e:
<syntaxhighlight lang="eiffel">class MAIN
creation make
feature make is
Line 1,672 ⟶ 1,790:
 
=={{header|Elena}}==
ELENA 46.x :
<syntaxhighlight lang="elena">import system'math;
import extensions;
 
Line 1,685 ⟶ 1,803:
console.printLine(a," * ",b," = ",a * b);
console.printLine(a," / ",b," = ",a / b); // truncates towards 0
console.printLine(a," % ",b," = ",a.mod:(b)); // matches sign of first operand
console.printLine(a," ^ ",b," = ",a ^ b);
}</syntaxhighlight>
Line 1,691 ⟶ 1,809:
=={{header|Elixir}}==
{{works with|Elixir|1.4}}
<syntaxhighlight lang=Elixir"elixir">defmodule Arithmetic_Integer do
# Function to remove line breaks and convert string to int
defp get_int(msg) do
Line 1,778 ⟶ 1,896:
Modulo: -1
Exponent: -0.0029154518950437317
</pre>
 
=={{header|EMal}}==
<syntaxhighlight lang="emal">
^|EMal has no divmod operator or built-in function,
|its interface can be easily emulated as shown below.
|The performace is worse than using / and % operators.
|^
fun divmod = Pair by int dividend, int divisor
Pair result = int%int().named("quotient", "remainder")
result.quotient = dividend / divisor
result.remainder = dividend % divisor
return result
end
fun main = int by List args
int a, b
if args.length == 2
a = int!args[0]
b = int!args[1]
else
a = ask(int, "first number: ")
b = ask(int, "second number: ")
end
writeLine("sum: " + (a + b))
writeLine("difference: " + (a - b))
writeLine("product: " + (a * b))
writeLine("integer quotient: " + (a / b)) # truncates towards 0
writeLine("remainder: " + (a % b)) # matches sign of first operand
writeLine("exponentiation: " + (a ** b))
writeLine("logarithm: " + (a // b))
writeLine("divmod: " + divmod(a, b))
return 0
end
exit main(Runtime.args)
</syntaxhighlight>
{{out}}
<pre>
emal.exe Org\RosettaCode\AritmeticInteger.emal
first number: 19
second number: 7
sum: 26
difference: 12
product: 133
integer quotient: 2
remainder: 5
exponentiation: 893871739
logarithm: 2
divmod: [2,5]
</pre>
 
=={{header|Emojicode}}==
<syntaxhighlight lang=Emojicode"emojicode">🏁🍇
🍺🔢🆕🔡▶️👂🏼❗ 10❗️ ➡️ x 💭 Get first number
🍺🔢🆕🔡▶️👂🏼❗ 10❗️ ➡️ y 💭 Get second number
Line 1,792 ⟶ 1,958:
 
=={{header|Erlang}}==
<syntaxhighlight lang="erlang">% Implemented by Arjun Sunel
-module(arith).
-export([start/0]).
Line 1,809 ⟶ 1,975:
 
=={{header|ERRE}}==
<syntaxhighlight lang="text">
PROGRAM INTEGER_ARITHMETIC
 
Line 1,847 ⟶ 2,013:
 
=={{header|Euphoria}}==
<syntaxhighlight lang="euphoria">include get.e
 
integer a,b
Line 1,876 ⟶ 2,042:
 
For sum, type in C1
<syntaxhighlight lang="excel">
=$A1+$B1
</syntaxhighlight>
 
For difference, type in D1
<syntaxhighlight lang="excel">
=$A1-$B1
</syntaxhighlight>
 
For product, type in E1
<syntaxhighlight lang="excel">
=$A1*$B1
</syntaxhighlight>
 
For quotient, type in F1
<syntaxhighlight lang="excel">
=QUOTIENT($A1,$B1)
</syntaxhighlight>
 
For remainder, type in G1
<syntaxhighlight lang="excel">
=MOD($A1,$B1)
</syntaxhighlight>
 
For exponentiation, type in H1
<syntaxhighlight lang="excel">
=$A1^$B1
</syntaxhighlight>
Line 1,907 ⟶ 2,073:
=={{header|F_Sharp|F#}}==
As F# is a functional language, we can easily create a list of pairs of the string name of a function and the function itself to iterate over printing the operation and applying the function to obtain the result:
<syntaxhighlight lang="fsharp">
do
let a, b = int Sys.argv.[1], int Sys.argv.[2]
Line 1,914 ⟶ 2,080:
</syntaxhighlight>
For example, the output with the arguments 4 and 3 is:
<syntaxhighlight lang="fsharp">
4 + 3 = 7
4 - 3 = 1
Line 1,923 ⟶ 2,089:
 
=={{header|Factor}}==
<syntaxhighlight lang="factor">USING: combinators io kernel math math.functions math.order
math.parser prettyprint ;
 
Line 1,960 ⟶ 2,126:
 
=={{header|FALSE}}==
<syntaxhighlight lang="false">12 7
\$@$@$@$@$@$@$@$@$@$@\ { 6 copies }
"sum = "+."
Line 1,971 ⟶ 2,137:
=={{header|Fermat}}==
Integer division rounds towards zero; remainders are always positive regardless of the signs of the numbers.
<syntaxhighlight lang="fermat">
?a;
?b;
Line 1,994 ⟶ 2,160:
=={{header|Forth}}==
To keep the example simple, the word takes the two numbers from the stack. '''/mod''' returns two results; the stack effect is ( a b -- a%b a/b ).
<syntaxhighlight lang="forth">: arithmetic ( a b -- )
cr ." a=" over . ." b=" dup .
cr ." a+b=" 2dup + .
Line 2,004 ⟶ 2,170:
Different host systems have different native signed division behavior. ANS Forth defines two primitive double-precision signed division operations, from which the implementation may choose the most natural to implement the basic divide operations ( / , /mod , mod , */ ). This is partly due to differing specifications in the two previous standards, Forth-79 and Forth-83.
 
<syntaxhighlight lang="forth">FM/MOD ( d n -- mod div ) \ floored
SM/REM ( d n -- rem div ) \ symmetric
M* ( n n -- d )</syntaxhighlight>
Line 2,010 ⟶ 2,176:
In addition, there are unsigned variants.
 
<syntaxhighlight lang="forth">UM/MOD ( ud u -- umod udiv )
UM* ( u u -- ud )</syntaxhighlight>
 
=={{header|Fortran}}==
In ANSI FORTRAN 77 or later:
<syntaxhighlight lang="fortran"> INTEGER A, B
PRINT *, 'Type in two integer numbers separated by white space',
+ ' and press ENTER'
Line 2,031 ⟶ 2,197:
 
=={{header|FreeBASIC}}==
<syntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
Dim As Integer i, j
Line 2,061 ⟶ 2,227:
 
=={{header|friendly interactive shell}}==
<syntaxhighlight lang="fishshell">
read a
read b
Line 2,074 ⟶ 2,240:
=={{header|Frink}}==
This demonstrates normal division (which produces rational numbers when possible), <CODE>div</CODE>, and <CODE>mod</CODE>. <CODE>div</CODE> rounds toward negative infinity (defined as <CODE>floor[x/y]</CODE>). <CODE>mod</CODE> uses the sign of the second number (defined as <CODE>x - y * floor[x/y]</CODE>). All operators automatically produce big integers or exact rational numbers when necessary.
<syntaxhighlight lang="frink">
[a,b] = input["Enter numbers",["a","b"]]
ops=["+", "-", "*", "/", "div" ,"mod" ,"^"]
Line 2,085 ⟶ 2,251:
 
{{out}}
<syntaxhighlight lang="frink">
10 + 20 = 30
10 - 20 = -10
Line 2,097 ⟶ 2,263:
=={{header|FutureBasic}}==
Basic program
<syntaxhighlight lang="futurebasic">
window 1, @"Integer Arithmetic", ( 0, 0, 400, 300 )
 
Line 2,126 ⟶ 2,292:
 
Standalone Intel, M1, M2 Macintosh application with user input
<syntaxhighlight lang="futurebasic">
 
_window = 1
Line 2,256 ⟶ 2,422:
 
=={{header|Gambas}}==
<syntaxhighlight lang="gambas">Public Sub Main()
Dim a, b As String
Dim c, d As Integer
Line 2,288 ⟶ 2,454:
 
=={{header|GAP}}==
<syntaxhighlight lang="gap">run := function()
local a, b, f;
f := InputTextUser();
Line 2,303 ⟶ 2,469:
CloseStream(f);
end;</syntaxhighlight>
 
=={{header|GDScript}}==
Requires Godot 4.
 
<syntaxhighlight lang="gdscript">
@tool
extends Node
 
@export var a: int:
set(value):
a = value
refresh()
 
@export var b: int:
set(value):
b = value
refresh()
 
# Output properties
@export var sum: int
@export var difference: int
@export var product: int
@export var integer_quotient: int
@export var remainder: int
@export var exponentiation: int
@export var divmod: int
 
func refresh():
sum = a + b
difference = a - b
product = a * b
integer_quotient = a / b # Rounds towards 0
remainder = a % b # Matches the sign of a
exponentiation = pow(a, b)
</syntaxhighlight>
 
=={{header|Genie}}==
Note: Using ''init:int'' and the ''return'' from the init block was introduced in release 0.43.92, February 2019.
 
<syntaxhighlight lang="genie">[indent=4]
/*
Arithmethic/Integer, in Genie
Line 2,341 ⟶ 2,542:
 
=={{header|GEORGE}}==
<syntaxhighlight lang=GEORGE"george">R (m) ;
R (n) ;
m n + P;
Line 2,351 ⟶ 2,552:
=={{header|Go}}==
===int===
<syntaxhighlight lang="go">package main
 
import "fmt"
Line 2,376 ⟶ 2,577:
</pre>
===big.Int===
<syntaxhighlight lang="go">package main
 
import (
Line 2,416 ⟶ 2,617:
-5 mod 3 = 1
</pre>
 
=={{header|Golfscript}}==
Quotients round towards negative infinity. Remainders match the sign of the second operand.
<syntaxhighlight lang="golfscript">n/~~:b;~:a;a b+n a b-n a b*n a b/n a b%n a b?</syntaxhighlight>
 
=={{header|Groovy}}==
'''Solution:'''
<syntaxhighlight lang="groovy">def arithmetic = { a, b ->
println """
a + b = ${a} + ${b} = ${a + b}
Line 2,435 ⟶ 2,640:
 
'''Test:'''
<syntaxhighlight lang="groovy">arithmetic(5,3)</syntaxhighlight>
 
{{out}}
Line 2,450 ⟶ 2,655:
 
=={{header|Harbour}}==
<syntaxhighlight lang="visualfoxpro">procedure Test( a, b )
? "a+b", a + b
? "a-b", a - b
Line 2,464 ⟶ 2,669:
=={{header|Haskell}}==
 
<syntaxhighlight lang="haskell">main = do
a <- readLn :: IO Integer
b <- readLn :: IO Integer
Line 2,481 ⟶ 2,686:
 
=={{header|Haxe}}==
<syntaxhighlight lang="haxe">class BasicIntegerArithmetic {
public static function main() {
var args =Sys.args();
Line 2,497 ⟶ 2,702:
=={{header|HicEst}}==
All numeric is 8-byte-float. Conversions are by INT, NINT, FLOOR, CEILING, or Formatted IO
<syntaxhighlight lang="hicest">DLG(Edit=A, Edit=B, TItle='Enter numeric A and B')
WRITE(Name) A, B
WRITE() ' A + B = ', A + B
Line 2,510 ⟶ 2,715:
WRITE() 'A to the power of B = ', A ^ B
WRITE() 'A to the power of B = ', A ** B</syntaxhighlight>
<syntaxhighlight lang="hicest">A=5; B=-4;
A + B = 1
A - B = 9
Line 2,524 ⟶ 2,729:
 
=={{header|HolyC}}==
<syntaxhighlight lang="holyc">I64 *a, *b;
a = Str2I64(GetStr("Enter your first number: "));
b = Str2I64(GetStr("Enter your second number: "));
Line 2,540 ⟶ 2,745:
 
=={{header|i}}==
<syntaxhighlight lang="i">main
a $= integer(in(' ')); ignore
b $= integer(in('\n')); ignore
Line 2,553 ⟶ 2,758:
 
=={{header|Icon}} and {{header|Unicon}}==
<syntaxhighlight lang=Icon"icon">procedure main()
writes("Input 1st integer a := ")
a := integer(read())
Line 2,569 ⟶ 2,774:
=={{header|Inform 7}}==
 
<syntaxhighlight lang="inform7">Enter Two Numbers is a room.
 
Numerically entering is an action applying to one number. Understand "[number]" as numerically entering.
Line 2,597 ⟶ 2,802:
 
=={{header|J}}==
<syntaxhighlight lang="j">calc =: + , - , * , <.@% , |~ , ^</syntaxhighlight>
The function <code>calc</code> constructs a list of numeric results for this task. The implementation of integer division we use here (<code><.@%.</code>) rounds down (towards negative infinity), and this is compatible with the remainder implementation we use here.
<syntaxhighlight lang="j"> 17 calc 3
20 14 51 5 2 4913</syntaxhighlight>
 
The function <code>bia</code> assembles these results, textually:
 
<syntaxhighlight lang="j">labels =: ];.2 'Sum: Difference: Product: Quotient: Remainder: Exponentiation: '
combine =: ,. ":@,.
bia =: labels combine calc
Line 2,617 ⟶ 2,822:
 
=={{header|Java}}==
<syntaxhighlight lang="java">import java.util.Scanner;
 
public class IntegerArithmetic {
Line 2,645 ⟶ 2,850:
{{works with|SpiderMonkey}}
Note that the operators work the same in all versions of JavaScript; the requirement for specific implementations is in order to get user input.
<syntaxhighlight lang="javascript">var a = parseInt(get_input("Enter an integer"), 10);
var b = parseInt(get_input("Enter an integer"), 10);
 
Line 2,684 ⟶ 2,889:
remainder: a % b = -21</pre>
===Node.JS===
<syntaxhighlight lang="javascript">// Invoked as node script_name.js <a> <b>. Positions 0 and 1 in the argv array contain 'node' and 'script_name.js' respectively
var a = parseInt(process.argv[2], 10);
var b = parseInt(process.argv[3], 10);
Line 2,708 ⟶ 2,913:
 
=={{header|jq}}==
<syntaxhighlight lang="jq"># Lines which do not have two integers are skipped:
 
def arithmetic:
Line 2,757 ⟶ 2,962:
 
=={{header|Jsish}}==
<syntaxhighlight lang="javascript">"use strict";
/* Arthimetic/Integer, in Jsish */
var line = console.input();
Line 2,796 ⟶ 3,001:
 
=={{header|Julia}}==
<syntaxhighlight lang=Julia"julia">function arithmetic (a = parse(Int, readline()), b = parse(Int, readline()))
for op in [+,-,*,div,rem]
println("a $op b = $(op(a,b))")
Line 2,812 ⟶ 3,017:
 
=={{header|Kotlin}}==
<syntaxhighlight lang=scala"kotlin">// version 1.1
import kotlin.math.pow // not an operator but in the standard library
 
fun main(args: Array<String>) {
val r = Regex("""-?\d+[ 0-9]+\s+-?\d[0-9]+""")
print("Enter two integers separated by space(s): ")
while(true) {
val input: String = readLine()!!.trim()
print("Enter two integers separated by space(s) or q to quit: ")
val input: Stringindex = readLine()!!input.trimlastIndexOf(' ')
val a = input.substring(0, index).trimEnd().toLong()
if (input == "q" || input == "Q") break
val b = input.substring(index if+ (!input1).matchestoLong(r)) {
println("$a + $b = ${a + b}")
println("Invalid input, try again")
println("$a - $b = ${a - continueb}")
println("$a * $b = ${a * b}")
println("$a / $b = ${a / b}") // rounds towards zero
val index = input.lastIndexOf(' ')
println("$a % $b = ${a % b}") // if non-zero, matches sign of first operand
val a = input.substring(0, index).trimEnd().toLong()
println("$a ^ val $b = input${a.substringtoDouble(index + 1).toLongpow(b.toDouble())}")
}
println("$a + $b = ${a + b}")
println("$a - $b = ${a - b}")
println("$a * $b = ${a * b}")
if (b != 0L) {
println("$a / $b = ${a / b}") // rounds towards zero
println("$a % $b = ${a % b}") // if non-zero, matches sign of first operand
}
else {
println("$a / $b = undefined")
println("$a % $b = undefined")
}
val d = Math.pow(a.toDouble(), b.toDouble())
print("$a ^ $b = ")
if (d % 1.0 == 0.0) {
if (d >= Long.MIN_VALUE.toDouble() && d <= Long.MAX_VALUE.toDouble())
println("${d.toLong()}")
else
println("out of range")
}
else if (!d.isFinite())
println("not finite")
else
println("not integral")
println()
}
}</syntaxhighlight>
 
{{out}}
<pre>
Enter two integers separated by space(s) or q to quit: 2 63
2 + 63 = 65
2 - 63 = -61
Line 2,862 ⟶ 3,044:
2 / 63 = 0
2 % 63 = 2
2 ^ 63 = 92233720368547758079.223372036854776E18
 
Enter two integers separated by space(s) or q to quit: -3 50
-3 + 50 = 47
-3 - 50 = -53
-3 * 50 = -150
-3 / 50 = 0
-3 % 50 = -3
-3 ^ 50 = out of range
 
Enter two integers separated by space(s) or q to quit: q
</pre>
 
Line 2,881 ⟶ 3,053:
=={{header|Lambdatalk}}==
Translation of Racket
<syntaxhighlight lang=Scheme"scheme">
{def arithmetic
{lambda {:x :y}
Line 2,905 ⟶ 3,077:
 
=={{header|Lasso}}==
<syntaxhighlight lang=Lasso"lasso">local(a = 6, b = 4)
#a + #b // 10
#a - #b // 2
Line 2,913 ⟶ 3,085:
math_pow(#a,#b) // 1296
math_pow(#b,#a) // 4096</syntaxhighlight>
 
=={{header|LDPL}}==
<syntaxhighlight lang="ldpl">data:
x is number
y is number
result is number
 
procedure:
display "Enter x: "
accept x
display "Enter y: "
accept y
add x and y in result
display "x + y = " result lf
subtract y from x in result
display "x - y = " result lf
multiply x by y in result
display "x * y = " result lf
divide x by y in result # There is no integer division but
floor result # floor rounds toward negative infinity
display "x / y = " result lf
modulo x by y in result
display "x % y = " result lf # Returns the sign of the 2nd argument
raise x to y in result
display "x ^ y = " result lf</syntaxhighlight>
{{out}}
<pre>
Enter x: 13
Enter y: 4
x + y = 17
x - y = 9
x * y = 52
x / y = 3
x % y = 1
x ^ y = 28561
</pre>
 
=={{header|LFE}}==
 
<syntaxhighlight lang="lisp">
(defmodule arith
(export all))
Line 2,934 ⟶ 3,142:
 
Usage from the LFE REPL:
<syntaxhighlight lang="lisp">
> (slurp '"arith.lfe")
#(ok arith)
Line 2,950 ⟶ 3,158:
=={{header|Liberty BASIC}}==
Note that raising to a power can display very large integers without going to approximate power-of-ten notation.
<syntaxhighlight lang="lb">
input "Enter the first integer: "; first
input "Enter the second integer: "; second
Line 2,963 ⟶ 3,171:
 
=={{header|LIL}}==
<syntaxhighlight lang="tcl"># Arithmetic/Integer, in LIL
write "Enter two numbers separated by space: "
if {[canread]} {set line [readline]}
Line 3,000 ⟶ 3,208:
 
=={{header|Lingo}}==
<syntaxhighlight lang=Lingo"lingo">-- X, Y: 2 editable field members, shown as sprites in the current GUI
x = integer(member("X").text)
y = integer(member("Y").text)
Line 3,012 ⟶ 3,220:
 
=={{header|Little}}==
<syntaxhighlight lang=C"c"># Maybe you need to import the mathematical funcions
# from Tcl with:
# eval("namespace path ::tcl::mathfunc");
Line 3,029 ⟶ 3,237:
 
=={{header|LiveCode}}==
<syntaxhighlight lang=LiveCode"livecode">ask "enter 2 numbers (comma separated)"
if it is not empty then
put item 1 of it into n1
Line 3,041 ⟶ 3,249:
put ai
end if</syntaxhighlight>
Examples<syntaxhighlight lang="text">-2,4 - power:16,product:-8,quotient:0,remainder:-2,sum:2
2,-4 - power:0.0625,product:-8,quotient:0,remainder:2,sum:-2
-2,-4 - power:0.0625,product:8,quotient:0,remainder:-2,sum:-6
Line 3,048 ⟶ 3,256:
 
=={{header|Logo}}==
<syntaxhighlight lang="logo">to operate :a :b
(print [a =] :a)
(print [b =] :b)
Line 3,061 ⟶ 3,269:
 
=={{header|LSE64}}==
<syntaxhighlight lang="lse64">over : 2 pick
2dup : over over
 
Line 3,073 ⟶ 3,281:
 
=={{header|Lua}}==
<syntaxhighlight lang="lua">local x = io.read()
local y = io.read()
 
Line 3,089 ⟶ 3,297:
 
 
<syntaxhighlight lang=M2000"m2000 Interpreterinterpreter">
MODULE LikeCommodoreBasic {
\\ ADDITION: EUCLIDEAN DIV# & MOD# AND ** FOR POWER INCLUDING ^
Line 3,142 ⟶ 3,350:
 
Because of the particular nature of M4, the only user-input is the code itself. Anyway the following code can be used:
<syntaxhighlight lang="m4">eval(A+B)
eval(A-B)
eval(A*B)
Line 3,154 ⟶ 3,362:
or using a sort of ''driver'':
 
<syntaxhighlight lang="m4">define(`A', 4)dnl
define(`B', 6)dnl
include(`operations.m4')</syntaxhighlight>
Line 3,160 ⟶ 3,368:
=={{header|Maple}}==
These operations are all built-in. As all operations are exact, there are no rounding issues involved.
<syntaxhighlight lang=Maple"maple">
DoIt := proc()
local a := readstat( "Input an integer: " ):
Line 3,173 ⟶ 3,381:
</syntaxhighlight>
Here is an example of calling DoIt.
<syntaxhighlight lang=Maple"maple">
> DoIt();
Input an integer: 15;
Line 3,187 ⟶ 3,395:
=={{header|Mathematica}}/{{header|Wolfram Language}}==
Mathematica has all the function built-in to handle this task. Example:
<syntaxhighlight lang=Mathematica"mathematica">a = Input["Give me an integer please!"];
b = Input["Give me another integer please!"];
Print["You gave me ", a, " and ", b];
Line 3,259 ⟶ 3,467:
 
=={{header|MATLAB}} / {{header|Octave}}==
<syntaxhighlight lang="octave">disp("integer a: "); a = scanf("%d", 1);
disp("integer b: "); b = scanf("%d", 1);
a+b
Line 3,269 ⟶ 3,477:
 
=={{header|Maxima}}==
<syntaxhighlight lang="maxima">block(
[a: read("a"), b: read("b")],
print(a + b),
Line 3,281 ⟶ 3,489:
 
=={{header|MAXScript}}==
<syntaxhighlight lang="maxscript">x = getKBValue prompt:"First number"
y = getKBValue prompt:"Second number:"
 
Line 3,291 ⟶ 3,499:
 
=={{header|Mercury}}==
<syntaxhighlight lang="text">
:- module arith_int.
:- interface.
Line 3,338 ⟶ 3,546:
=={{header|Metafont}}==
 
<syntaxhighlight lang="metafont">string s[];
message "input number a: ";
s1 := readstring;
Line 3,358 ⟶ 3,566:
 
=={{header|min}}==
{{works with|min|0.1937.30}}
<syntaxhighlight lang="min">(concat dup'+ '-> '* prepend'div "$1 -> $2" swap % puts!'mod) :show
(("Enter an integer" ask integer) 2 times) quote-map =>
 
("Enter$1 an-> integer$2" askrollup int)concat 2dup times-> 'quote prepend %) prepend
('+ '- '* 'div 'mod) quote-map ('show"\n" concat) mapjoin cleaveputs!</syntaxhighlight>
{{out}}
<pre>
Line 3,375 ⟶ 3,583:
 
=={{header|МК-61/52}}==
<syntaxhighlight lang="text">П1 <-> П0
+ С/П
ИП0 ИП1 - С/П
Line 3,387 ⟶ 3,595:
and then output the results to 'standard output' or similar.
 
<syntaxhighlight lang=ML"ml/Ii">MCSKIP "WITH" NL
"" Arithmetic/Integer
"" assumes macros on input stream 1, terminal on stream 2
Line 3,404 ⟶ 3,612:
 
=={{header|Modula-2}}==
<syntaxhighlight lang="modula2">MODULE ints;
 
IMPORT InOut;
Line 3,437 ⟶ 3,645:
 
=={{header|Modula-3}}==
<syntaxhighlight lang="modula3">MODULE Arith EXPORTS Main;
 
IMPORT IO, Fmt;
Line 3,462 ⟶ 3,670:
find out the beauty of cyclic algebra as formulated by Niels Henrik Abel (August 5, 1802 – April 6, 1829).</p>
 
<syntaxhighlight lang=MUMPS"mumps">Arith(first,second) ; Mathematical operators
Write "Plus",?12,first,"+",second,?25," = ",first+second,!
Write "Minus",?12,first,"-",second,?25," = ",first-second,!
Line 3,509 ⟶ 3,717:
=={{header|Nanoquery}}==
{{trans|Python}}
<syntaxhighlight lang=Nanoquery"nanoquery">print "Number 1: "
x = int(input())
print "Number 2: "
Line 3,534 ⟶ 3,742:
=={{header|Nemerle}}==
Adapted nearly verbatim from C# solution above. Note that I've used the exponentiation operator (**), but Math.Pow() as used in the C# solution would also work.
<syntaxhighlight lang=Nemerle"nemerle">using System;
class Program
Line 3,554 ⟶ 3,762:
=={{header|NetRexx}}==
{{trans|REXX}}
<syntaxhighlight lang=NetRexx"netrexx">/* NetRexx */
 
options replace format comments java crossref symbols binary
Line 3,581 ⟶ 3,789:
=={{header|NewLISP}}==
 
<syntaxhighlight lang=NewLISP"newlisp">; integer.lsp
; oofoe 2012-01-17
 
Line 3,627 ⟶ 3,835:
 
Define new operator using an atlas of operators:
<syntaxhighlight lang="nial"> arithmetic is OP A B{[first,last,+,-,*,quotient,mod,power] A B}</syntaxhighlight>
 
Test new operator:
<syntaxhighlight lang="nial"> -23 arithmetic 7
-23 7 -16 -30 -161 -4 5 -3404825447</syntaxhighlight>
 
Line 3,643 ⟶ 3,851:
Nial definition of <code>quotient</code>:
 
<syntaxhighlight lang="nial">A quotient B =f= floor (A / B)</syntaxhighlight>
 
<code>floor</code> rounds towards negative infinity (next lower integer).
 
=={{header|Nim}}==
<syntaxhighlight lang="nim">import parseopt, strutils
var
Line 3,687 ⟶ 3,895:
=={{header|NSIS}}==
All Arithmetic in NSIS is handled by the [http://nsis.sourceforge.net/Docs/Chapter4.html#4.9.10.2 IntOp] instruction. It is beyond the scope of this task to implement user input (a fairly involved task), so I will be providing hard-coded values simulating the user input, with the intention of later adding the user-input piece.
<syntaxhighlight lang="nsis">Function Arithmetic
Push $0
Push $1
Line 3,711 ⟶ 3,919:
Pop $0
FunctionEnd</syntaxhighlight>
 
=={{header|Nu}}==
Division rounds towards -infinity. Modulus will match the sign of the first number.
 
<syntaxhighlight lang="nu">
input | parse "{a} {b}" | first | values | into int | do {|a b|
{
Sum: ($a + $b)
Difference: ($a - $b)
Product: ($a * $b)
Quotient: ($a // $b)
Remainder: ($a mod $b)
Exponent: ($a ** $b)
}
} $in.0 $in.1
</syntaxhighlight>
{{out}}
<pre>
-1 2
╭────────────┬────╮
│ Sum │ 1 │
│ Difference │ -3 │
│ Product │ -2 │
│ Quotient │ -1 │
│ Remainder │ -1 │
│ Exponent │ 1 │
╰────────────┴────╯
</pre>
 
=={{header|Nutt}}==
<syntaxhighlight lang="Nutt">
module main
imports native.io{input.hear,output.say}
 
vals a=hear(Numerable),b=hear(Numerable)
say("a+b="+(a+b))
say("a-b="+(a-b))
say("a*b="+(a*b))
say("a//b="+(a//b))
say("a%b="+(a%b))
say("a^b="+(a^b))
 
end
</syntaxhighlight>
 
=={{header|Oberon-2}}==
Oxford Oberon-2
<syntaxhighlight lang="oberon2">
MODULE Arithmetic;
IMPORT In, Out;
Line 3,739 ⟶ 3,991:
 
=={{header|Objeck}}==
<syntaxhighlight lang="objeck">bundle Default {
class Arithmetic {
function : Main(args : System.String[]) ~ Nil {
Line 3,758 ⟶ 4,010:
 
=={{header|OCaml}}==
<syntaxhighlight lang="ocaml">let _ =
let a = read_int ()
and b = read_int () in
Line 3,770 ⟶ 4,022:
=={{header|Oforth}}==
 
<syntaxhighlight lang=Oforth"oforth">: integers (a b -- )
"a + b =" . a b + .cr
"a - b =" . a b - .cr
Line 3,793 ⟶ 4,045:
=={{header|Ol}}==
 
<syntaxhighlight lang="scheme">
(define a 8)
(define b 12)
Line 3,836 ⟶ 4,088:
=={{header|Onyx}}==
 
<syntaxhighlight lang="onyx"># 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.
Line 3,899 ⟶ 4,151:
=={{header|Openscad}}==
 
<syntaxhighlight lang="openscad">echo (a+b); /* Sum */
echo (a-b); /* Difference */
echo (a*b); /* Product */
Line 3,906 ⟶ 4,158:
 
=={{header|Oz}}==
<syntaxhighlight lang="oz">declare
StdIn = {New class $ from Open.file Open.text end init(name:stdin)}
 
Line 3,928 ⟶ 4,180:
=={{header|Panda}}==
Use reflection to get all functions defined on numbers taking number and returning number.
<syntaxhighlight lang="panda">a=3 b=7 func:_bbf__number_number_number =>f.name.<b> '(' a b ')' ' => ' f(a b) nl</syntaxhighlight>
 
{{out}}
Line 3,946 ⟶ 4,198:
=={{header|PARI/GP}}==
Integer division with <code>\</code> rounds to <math>-\infty</math>. There also exists the <code>\/</code> round-to-nearest (ties to <math>+\infty</math>) operator. Ordinary division <code>/</code> does not round but returns rationals if given integers with a non-integral quotient.
<syntaxhighlight lang="parigp">arith(a,b)={
print(a+b);
print(a-b);
Line 3,956 ⟶ 4,208:
 
=={{header|Pascal}}==
<syntaxhighlight lang="pascal">program arithmetic(input, output)
 
var
Line 3,973 ⟶ 4,225:
=={{header|Perl}}==
{{works with|Perl|5.x}}
<syntaxhighlight lang="perl">my $a = <>;
my $b = <>;
 
Line 3,989 ⟶ 4,241:
{{libheader|Phix/online}}
You can run this online [http://phix.x10.mx/p2js/ArithInt.htm here] (layout/space is not perfected yet).
<!--<syntaxhighlight lang=Phix"phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">include</span> <span style="color: #000000;">pGUI</span><span style="color: #0000FF;">.</span><span style="color: #000000;">e</span>
Line 4,049 ⟶ 4,301:
 
=={{header|Phixmonti}}==
<syntaxhighlight lang=Phixmonti"phixmonti">def printOp
swap print print nl
enddef
Line 4,066 ⟶ 4,318:
=={{header|PHL}}==
 
<syntaxhighlight lang="phl">module arith;
 
extern printf;
Line 4,087 ⟶ 4,339:
 
=={{header|PHP}}==
<syntaxhighlight lang="php"><?php
$a = fgets(STDIN);
$b = fgets(STDIN);
Line 4,102 ⟶ 4,354:
 
=={{header|Picat}}==
<syntaxhighlight lang=Picat"picat">main =>
X = read_int(),
Y = read_int(),
Line 4,122 ⟶ 4,374:
 
=={{header|PicoLisp}}==
<syntaxhighlight lang=PicoLisp"picolisp">(de math (A B)
(prinl "Add " (+ A B))
(prinl "Subtract " (- A B))
Line 4,172 ⟶ 4,424:
 
=={{header|PL/I}}==
<syntaxhighlight lang=PL"pl/Ii">
get list (a, b);
put skip list (a+b);
Line 4,182 ⟶ 4,434:
 
=={{header|Plain English}}==
<syntaxhighlight lang="plainenglish">To run:
Start up.
Demonstrate integer arithmetic.
Line 4,222 ⟶ 4,474:
=={{header|Pop11}}==
 
<syntaxhighlight lang="pop11">;;; Setup token reader
vars itemrep;
incharitem(charin) -> itemrep;
Line 4,235 ⟶ 4,487:
 
=={{header|PostScript}}==
<syntaxhighlight lang="ps">/arithInteger {
/x exch def
/y exch def
Line 4,247 ⟶ 4,499:
 
=={{header|PowerShell}}==
<syntaxhighlight lang="powershell">$a = [int] (Read-Host First Number)
$b = [int] (Read-Host Second Number)
 
Line 4,261 ⟶ 4,513:
 
No exponentiation operator exists, but can be worked around with the .NET BCL:
<syntaxhighlight lang="powershell">[Math]::Pow($a, $b)</syntaxhighlight>
 
=={{header|Processing}}==
<syntaxhighlight lang=Processing"processing">int a = 7, b = 5;
 
println(a + " + " + b + " = " + (a + b));
Line 4,279 ⟶ 4,531:
 
=={{header|ProDOS}}==
<syntaxhighlight lang=ProDOS"prodos">IGNORELINE Note: This example includes the math module.
include arithmeticmodule
:a
Line 4,299 ⟶ 4,551:
:end</syntaxhighlight>
 
<syntaxhighlight lang=ProDOS"prodos">IGNORELINE Note: This example does not use the math module.
:a
editvar /newvar /value=a /title=Enter first integer:
Line 4,321 ⟶ 4,573:
Remainder (`rem`) matches the sign of its first operand.
 
<syntaxhighlight lang="prolog">
 
print_expression_and_result(M, N, Operator) :-
Line 4,337 ⟶ 4,589:
Use thus:
 
<syntaxhighlight lang="prolog">
?- arithmetic_integer.
|: 5.
Line 4,351 ⟶ 4,603:
 
=={{header|PureBasic}}==
<syntaxhighlight lang="purebasic">OpenConsole()
Define a, b
Line 4,371 ⟶ 4,623:
=={{header|Python}}==
 
<syntaxhighlight lang="python">x = int(raw_input("Number 1: "))
y = int(raw_input("Number 2: "))
 
Line 4,388 ⟶ 4,640:
Notes: In Python3 ''raw_input()'' will be renamed to ''input()'' (the old ''input()'' built-in will go away, though one could use ''eval(input())'' to emulate the old ... and ill-advised ... behavior). Also a better program would wrap the attempted ''int()'' conversions in a ''try: ... except ValueError:...'' construct such as:
 
<syntaxhighlight lang="python">def getnum(prompt):
while True: # retrying ...
try:
Line 4,409 ⟶ 4,661:
 
=== Python 3.0 compatible code ===
<syntaxhighlight lang="python">def arithmetic(x, y):
for op in "+ - * // % **".split():
expr = "%(x)s %(op)s %(y)s" % vars()
Line 4,434 ⟶ 4,686:
 
== Python 3.x Long Form ==
<syntaxhighlight lang="python">input1 = 18
# input1 = input()
input2 = 7
Line 4,468 ⟶ 4,720:
=={{header|QB64}}==
''CBTJD'': 2020/03/12
<syntaxhighlight lang="vb">START:
INPUT "Enter two integers (a,b):"; a!, b!
IF a = 0 THEN END
Line 4,491 ⟶ 4,743:
=={{header|Quackery}}==
 
<syntaxhighlight lang=Quackery"quackery "> $ "Please enter two integers separated by a space. "
input quackery
2dup say "Their sum is: " + echo cr
Line 4,515 ⟶ 4,767:
 
=={{header|R}}==
<syntaxhighlight lang=R"r">cat("insert number ")
a <- scan(nmax=1, quiet=TRUE)
cat("insert number ")
Line 4,528 ⟶ 4,780:
 
=={{header|Racket}}==
<syntaxhighlight lang="racket">
#lang racket/base
 
Line 4,556 ⟶ 4,808:
 
Note that <code>div</code> <b>requires</b> integer arguments. If you want integer division with other types, say <code>floor($a/$b)</code>.
<syntaxhighlight lang=perl6"raku" line>my Int $a = get.floor;
my Int $b = get.floor;
 
Line 4,568 ⟶ 4,820:
=={{header|Raven}}==
 
<syntaxhighlight lang="raven">' Number 1: ' print expect 0 prefer as x
' Number 2: ' print expect 0 prefer as y
 
Line 4,578 ⟶ 4,830:
 
=={{header|REBOL}}==
<syntaxhighlight lang="rebol">REBOL [
Title: "Integer"
URL: http://rosettacode.org/wiki/Arithmetic/Integer
Line 4,650 ⟶ 4,902:
=={{header|Relation}}==
There is no input, variables have to be set in code. Format is there only for output.
<syntaxhighlight lang=Relation"relation">
set a = -17
set b = 4
Line 4,663 ⟶ 4,915:
=={{header|ReScript}}==
 
<syntaxhighlight lang=ReScript"rescript">let a = int_of_string(Sys.argv[2])
let b = int_of_string(Sys.argv[3])
 
Line 4,692 ⟶ 4,944:
Retro's arithmetic functions are based on those in [[Forth]]. The example is an adaption of the one from Forth.
<syntaxhighlight lang=Retro"retro">:arithmetic (ab-)
over '\na_______=_%n s:put
dup '\nb_______=_%n s:put
Line 4,707 ⟶ 4,959:
For division that produces a floating point number, the result is rounded to the nearest number that can be expressed
<br>within the current number of decimal digits &nbsp; (in the example program below, it is &nbsp; '''20''' &nbsp; decimal digits).
<syntaxhighlight lang="rexx">/*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. */
Line 4,751 ⟶ 5,003:
 
=={{header|Ring}}==
<syntaxhighlight lang="ring">
func Test a,b
see "a+b" + ( a + b ) + nl
Line 4,764 ⟶ 5,016:
 
=={{header|Robotic}}==
<syntaxhighlight lang="robotic">
input string "Enter number 1:"
set "a" to "input"
Line 4,777 ⟶ 5,029:
[ "Exponentiation: ('a'^'b')"
</syntaxhighlight>
 
=={{header|RPL}}==
≪ → a b
≪ "a + b = " a b + →STR +
"a - b = " a b - →STR +
"a * b = " a b * →STR +
"a / b = " a b / →STR +
"a % b = " a b / LAST ROT * - →STR +
"a ^ b = " a B→R b B→R ^ R→B →STR +
≫ ≫ '<span style="color:blue">SHOWA</span>' STO
 
#14 #3 <span style="color:blue">SHOWA</span>
<pre>
6: "a + b = # 17d"
5: "a - b = # 11d"
4: "a * b = # 42d"
3: "a / b = # 4d"
2: "a % b = # 2d"
1: "a ^ b = # 2744d"
</pre>
 
=={{header|Ruby}}==
 
<syntaxhighlight lang="ruby">puts 'Enter x and y'
x = gets.to_i # to check errors, use x=Integer(gets)
y = gets.to_i
Line 4,790 ⟶ 5,062:
"Quotient: #{x.fdiv(y)}", # float
"Remainder: #{x%y}", # same sign as second operand
"Exponentiation: #{x**y}"</syntaxhighlight>,
"Quotient: %d with Remainder: %d" % x.divmod(y)</syntaxhighlight>
 
=={{header|Run BASIC}}==
<syntaxhighlight lang="runbasic">input "1st integer: "; i1
input "2nd integer: "; i2
Line 4,806 ⟶ 5,079:
 
Note that this code cannot be run within the [http://play.rust-lang.org Rust playpen] as it does not support console input.
<syntaxhighlight lang="rust">use std::env;
 
fn main() {
Line 4,822 ⟶ 5,095:
=={{header|Sass/SCSS}}==
 
<syntaxhighlight lang="coffeescript">
@function arithmetic($a,$b) {
@return $a + $b, $a - $b, $a * $b, ($a - ($a % $b))/$b, $a % $b;
Line 4,828 ⟶ 5,101:
</syntaxhighlight>
Which you use with:
<syntaxhighlight lang="coffeescript">
nth(arithmetic(10,3),1);
</syntaxhighlight>
Or each of the functions separately:
<syntaxhighlight lang="coffeescript">
@function sum($a,$b) {
@return $a + $b;
Line 4,859 ⟶ 5,132:
 
=={{header|Scala}}==
<syntaxhighlight lang="scala">val a = Console.readInt
val b = Console.readInt
Line 4,871 ⟶ 5,144:
=={{header|Scheme}}==
 
<syntaxhighlight lang="scheme">(define (arithmetic x y)
(for-each (lambda (op)
(write (list op x y))
Line 4,899 ⟶ 5,172:
 
=={{header|Seed7}}==
<syntaxhighlight lang="seed7">$ include "seed7_05.s7i";
 
const proc: main is func
Line 4,921 ⟶ 5,194:
 
=={{header|SenseTalk}}==
<syntaxhighlight lang="sensetalk">ask "Enter the first number:"
put it into number1
 
Line 4,935 ⟶ 5,208:
 
=={{header|Sidef}}==
<syntaxhighlight lang="ruby">var a = Sys.scanln("First number: ").to_i;
var b = Sys.scanln("Second number: ").to_i;
 
Line 4,960 ⟶ 5,233:
 
=={{header|Slate}}==
<syntaxhighlight lang="slate">[| :a :b |
inform: (a + b) printString.
inform: (a - b) printString.
Line 4,969 ⟶ 5,242:
 
] applyTo: {Integer readFrom: (query: 'Enter a: '). Integer readFrom: (query: 'Enter b: ')}.</syntaxhighlight>
 
=={{header|SmallBASIC}}==
<syntaxhighlight lang="SmallBASIC">
input "Enter first number : "; A
input "Enter second number: "; B
 
print "Sum : "; A + B
print "Difference: "; A - B
print "Product : "; A * B
print "Quotient : "; A \ B ' Integer quotient rounds towards smaller number
print "Remainder : "; A % B ' sign of remainder is given by sign of first operand
print "Power : "; A ^ B
</syntaxhighlight>
 
=={{header|Smalltalk}}==
{{works with|GNU Smalltalk}}
<syntaxhighlight lang="smalltalk">| a b |
'Input number a: ' display.
a := (stdin nextLine) asInteger.
Line 4,984 ⟶ 5,270:
 
{{works with|Smalltalk/X}} (and all other Smalltalks)
<syntaxhighlight lang="smalltalk">|a b|
a := (Dialog request:'Enter first number:') asNumber.
b := (Dialog request:'Enter second number:') asNumber.
Line 5,042 ⟶ 5,328:
 
=={{header|smart BASIC}}==
<syntaxhighlight lang="qbasic">INPUT "Enter first number.":first
INPUT "Enter second number.":second
PRINT "The sum of";first;"and";second;"is ";first+second&"."
Line 5,062 ⟶ 5,348:
 
=={{header|SNOBOL4}}==
<syntaxhighlight lang="snobol4">
output = "Enter first integer:"
first = input
Line 5,079 ⟶ 5,365:
 
''See also: [[Ethiopian Multiplication]]''
<syntaxhighlight lang=SNUSP"snusp">$\
,
@
Line 5,140 ⟶ 5,426:
=={{header|SQL}}==
{{works with|Oracle}}
<syntaxhighlight lang="sql">
-- test.sql
-- Tested in SQL*plus
Line 5,210 ⟶ 5,496:
=={{header|SSEM}}==
The only operation that the SSEM supports natively is substraction. This program uses the <tt>001 Sub.</tt> instruction to find the difference between <i>a</i> and <i>b</i>, assuming they are loaded into storage addresses 20 and 21 respectively.
<syntaxhighlight lang="ssem">00101000000000100000000000000000 0. -20 to c
10100000000001100000000000000000 1. c to 5
10100000000000100000000000000000 2. -5 to c
Line 5,217 ⟶ 5,503:
00000000000000000000000000000000 5. 0</syntaxhighlight>
The routine is slightly more complicated than it would otherwise be, because the SSEM cannot load a value into the accumulator (<tt>c</tt> register) from storage without negating it in the process—so we have to shuffle the negation of <i>a</i> back out into storage and then negate it again before we can subtract <i>b</i> from it. This does, however, make it easy to implement addition using negation and subtraction. In this program, we first negate <i>a</i>; then subtract <i>b</i>, and store the result; and finally negate that result, thereby obtaining the sum of the two integers.
<syntaxhighlight lang="ssem">00101000000000100000000000000000 0. -20 to c
10101000000000010000000000000000 1. Sub. 21
10100000000001100000000000000000 2. c to 5
Line 5,226 ⟶ 5,512:
 
=={{header|Standard ML}}==
<syntaxhighlight lang="sml">val () = let
val a = valOf (Int.fromString (valOf (TextIO.inputLine TextIO.stdIn)))
val b = valOf (Int.fromString (valOf (TextIO.inputLine TextIO.stdIn)))
Line 5,241 ⟶ 5,527:
 
=={{header|Swift}}==
<syntaxhighlight lang="swift">
let a = 6
let b = 4
Line 5,254 ⟶ 5,540:
 
=={{header|Tcl}}==
<syntaxhighlight lang="tcl">puts "Please enter two numbers:"
 
set x [expr {int([gets stdin])}]; # Force integer interpretation
Line 5,270 ⟶ 5,556:
Often, these operations would be performed in a different way from what is shown here. For example, to increase the variable "x" by the value of the variable "y", one would write
 
<syntaxhighlight lang="tcl">incr x $y</syntaxhighlight>
 
Also, it's important to surround the arguments to the <code>expr</code> in braces, especially when any of the parts of the expression are not literal constants. Discussion of this is on [http://wiki.tcl.tk/10225 The Tcler's Wiki].
Line 5,276 ⟶ 5,562:
=={{header|Terraform}}==
HCL doesn't have an exponentiation operator and even integer division is contrived as shown in the code, but at least it prints the output variables alphabetically without any effort.......
<syntaxhighlight lang="terraform">
#Aamrun, 15th August 2022
 
Line 5,335 ⟶ 5,621:
=={{header|TI-83 BASIC}}==
Pauses added due to TI-83's lack of screen size.
<syntaxhighlight lang="ti83b">
Prompt A,B
Disp "SUM"
Line 5,351 ⟶ 5,637:
=={{header|TI-89 BASIC}}==
 
<syntaxhighlight lang="ti89b">Local a, b
Prompt a, b
Disp "Sum: " & string(a + b)
Line 5,361 ⟶ 5,647:
=={{header|Toka}}==
 
<syntaxhighlight lang="toka">[ ( a b -- )
2dup ." a+b = " + . cr
2dup ." a-b = " - . cr
Line 5,369 ⟶ 5,655:
 
=={{header|TUSCRIPT}}==
<syntaxhighlight lang="tuscript">
$$ MODE TUSCRIPT
a=5
Line 5,401 ⟶ 5,687:
{{works with|Bourne Shell}}
{{works with|Almquist SHell}}
<syntaxhighlight lang="bash">#!/bin/sh
read a; read b;
echo "a+b = " `expr $a + $b`
Line 5,416 ⟶ 5,702:
{{works with|pdksh|5.2.14}}
{{works with|Z SHell}}
<syntaxhighlight lang="bash">#!/bin/sh
read a; read b;
echo "a+b = $((a+b))"
Line 5,427 ⟶ 5,713:
 
=={{header|Ursa}}==
<syntaxhighlight lang="ursa">#
# integer arithmetic
#
Line 5,456 ⟶ 5,742:
 
=={{header|VBA}}==
<syntaxhighlight lang="vb">
'Arithmetic - Integer
Sub RosettaArithmeticInt()
Line 5,480 ⟶ 5,766:
 
===Implementation===
<syntaxhighlight lang="vb">option explicit
dim a, b
wscript.stdout.write "A? "
Line 5,500 ⟶ 5,786:
===Another Implementation===
Gives the same output for the same input. Inspired by Python version.
<syntaxhighlight lang="vb">option explicit
dim a, b
wscript.stdout.write "A? "
Line 5,530 ⟶ 5,816:
 
=={{header|Vedit macro language}}==
<syntaxhighlight lang="vedit">#1 = Get_Num("Give number a: ")
#2 = Get_Num("Give number b: ")
Message("a + b = ") Num_Type(#1 + #2)
Line 5,540 ⟶ 5,826:
 
=={{header|Verilog}}==
<syntaxhighlight lang=Verilog"verilog">module main;
integer a, b;
integer suma, resta, producto;
Line 5,568 ⟶ 5,854:
 
=={{header|Vim Script}}==
<syntaxhighlight lang="vim">let a = float2nr(input("Number 1: ") + 0)
let b = float2nr(input("Number 2: ") + 0)
echo "\nSum: " . (a + b)
Line 5,580 ⟶ 5,866:
 
=={{header|Visual Basic .NET}}==
<syntaxhighlight lang="vbnet">Imports System.Console
Module Module1
Sub Main
Line 5,595 ⟶ 5,881:
End Module</syntaxhighlight>
 
=={{header|V (Vlang)}}==
<syntaxhighlight lang="go">// Arithmetic-integer in V (Vlang)
// Tectonics: v run arithmetic-integer.v
module main
Line 5,639 ⟶ 5,925:
 
=={{header|Wart}}==
<syntaxhighlight lang="python">a <- (read)
b <- (read)
prn "sum: " a+b
Line 5,653 ⟶ 5,939:
 
The sign of the remainder operator '%' matches the sign of the first operand.
<syntaxhighlight lang=ecmascript"wren">import "io" for Stdin, Stdout
System.write("first number: ")
Stdout.flush()
Line 5,682 ⟶ 5,968:
=={{header|x86 Assembly}}==
Input and output would be OS-specific and are not implemented. This routine works on the 16-bit 8086, as well as on its 32-bit and 64-bit successors: it could be trivially modified to perform 32-bit or 64-bit arithmetic on machines where those are supported. The quotient is truncated towards zero; the remainder takes its sign from the first operand.
<syntaxhighlight lang="asm">arithm: mov cx, a
mov bx, b
xor dx, dx
Line 5,706 ⟶ 5,992:
 
=={{header|XLISP}}==
<syntaxhighlight lang="xlisp">(DEFUN INTEGER-ARITHMETIC ()
(DISPLAY "Enter two integers separated by a space.")
(NEWLINE)
Line 5,725 ⟶ 6,011:
 
=={{header|XPL0}}==
<syntaxhighlight lang=XPL0"xpl0">include c:\cxpl\codes;
int A, B;
[A:= IntIn(0);
Line 5,737 ⟶ 6,023:
 
=={{header|XSLT}}==
<syntaxhighlight lang="xml"><xsl:template name="arithmetic">
<xsl:param name="a">5</xsl:param>
<xsl:param name="b">2</xsl:param>
Line 5,749 ⟶ 6,035:
 
=={{header|Yabasic}}==
<syntaxhighlight lang=Yabasic"yabasic">input "ingrese un numero? " a
input "ingrese otro numero? " b
 
Line 5,762 ⟶ 6,048:
 
=={{header|Yorick}}==
<syntaxhighlight lang="yorick">x = y = 0;
read, x, y;
write, "x + y =", x + y;
Line 5,772 ⟶ 6,058:
 
=={{header|zkl}}==
<syntaxhighlight lang="zkl">x,y:=ask("Two ints: ").split(" ").apply("toInt");
println("x+y = ",x + y);
println("x-y = ",x - y);
Line 5,781 ⟶ 6,067:
 
=={{header|zonnon}}==
<syntaxhighlight lang="zonnon">
module Main;
var
Line 5,807 ⟶ 6,093:
 
=={{header|ZX Spectrum Basic}}==
<syntaxhighlight lang="zxbasic">5 LET a=5: LET b=3
10 PRINT a;" + ";b;" = ";a+b
20 PRINT a;" - ";b;" = ";a-b
Anonymous user