A+B: Difference between revisions

From Rosetta Code
Content added Content deleted
(Added Modula-3)
(47 intermediate revisions by 32 users not shown)
Line 32: Line 32:


=={{header|0815}}==
=={{header|0815}}==
<lang 0815>|x|+%</lang>
<syntaxhighlight lang="0815">|x|+%</syntaxhighlight>


=={{header|11l}}==
=={{header|11l}}==
{{trans|Python}}
{{trans|Python}}
<lang 11l>print(sum(input().split(‘ ’, group_delimiters' 1B).map(i -> Int(i))))</lang>
<syntaxhighlight lang="11l">print(sum(input().split(‘ ’, group_delimiters' 1B).map(i -> Int(i))))</syntaxhighlight>


=={{header|360 Assembly}}==
=={{header|360 Assembly}}==
<lang 360asm>* A+B 29/08/2015
<syntaxhighlight lang="360asm">* A+B 29/08/2015
APLUSB CSECT
APLUSB CSECT
USING APLUSB,R12
USING APLUSB,R12
Line 60: Line 60:
YREGS
YREGS
END APLUSB
END APLUSB
</syntaxhighlight>
</lang>
{{in}}
{{in}}
<pre>
<pre>
Line 75: Line 75:


=={{header|8th}}==
=={{header|8th}}==
<lang forth>gets dup . space eval n:+ . cr</lang>
<syntaxhighlight lang="forth">gets dup . space eval n:+ . cr</syntaxhighlight>


=={{header|8080 Assembly}}==
=={{header|8080 Assembly}}==
Line 86: Line 86:
which can take four forms:
which can take four forms:


<lang 8080asm> dad b ; HL += BC (i.e., add BC reg pair to HL reg pair)
<syntaxhighlight lang="8080asm"> dad b ; HL += BC (i.e., add BC reg pair to HL reg pair)
dad d ; HL += DE
dad d ; HL += DE
dad h ; HL += HL (also known as "mul HL by two")
dad h ; HL += HL (also known as "mul HL by two")
dad sp ; HL += SP (actually the only way to get at SP at all)</lang>
dad sp ; HL += SP (actually the only way to get at SP at all)</syntaxhighlight>


Merely doing A+B, with 16-bit numbers so that <math>(-1000 \le A,B \le +1000)</math> will fit,
Merely doing A+B, with 16-bit numbers so that <math>(-1000 \le A,B \le +1000)</math> will fit,
would look like this:
would look like this:
<lang 8080asm> lxi h,123
<syntaxhighlight lang="8080asm"> lxi h,123
lxi d,456
lxi d,456
dad d
dad d
; HL is now 579</lang>
; HL is now 579</syntaxhighlight>


Then, the following is what is required to wrap it all in a CP/M command line utility.
Then, the following is what is required to wrap it all in a CP/M command line utility.
Line 104: Line 104:
fits exactly in one CP/M block.
fits exactly in one CP/M block.


<lang 8080asm>fcb1n: equ 5Ch+1 ; "Filename" in first FCB
<syntaxhighlight lang="8080asm">fcb1n: equ 5Ch+1 ; "Filename" in first FCB
fcb2n: equ 6Ch+1 ; "Filename" in second FCB
fcb2n: equ 6Ch+1 ; "Filename" in second FCB
puts: equ 9 ; CP/M call to write string to console
puts: equ 9 ; CP/M call to write string to console
Line 193: Line 193:
negf: db 0 ; Space for negative flag
negf: db 0 ; Space for negative flag
db '-00000'
db '-00000'
num: db '$' ; Space for number</lang>
num: db '$' ; Space for number</syntaxhighlight>


{{out}}
{{out}}
Line 209: Line 209:
=={{header|AArch64 Assembly}}==
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
<syntaxhighlight lang="aarch64 assembly">
<lang AArch64 Assembly>
/* ARM assembly AARCH64 Raspberry PI 3B */
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program addAetB.s */
/* program addAetB.s */
Line 406: Line 406:
.align 4 // instruction to realign the following routines
.align 4 // instruction to realign the following routines


</syntaxhighlight>
</lang>


=={{header|ABAP}}==
=={{header|ABAP}}==
<lang ABAP>report z_sum_a_b.
<syntaxhighlight lang="abap">report z_sum_a_b.
data: lv_output type i.
data: lv_output type i.
selection-screen begin of block input.
selection-screen begin of block input.
Line 423: Line 423:
start-of-selection.
start-of-selection.
lv_output = p_first + p_second.
lv_output = p_first + p_second.
write : / lv_output.</lang>
write : / lv_output.</syntaxhighlight>

=={{header|Acornsoft Lisp}}==
{{trans|Common Lisp}}

<pre>
Evaluate: (print (plus (read) (read)))
3 2
5
</pre>


=={{header|Action!}}==
=={{header|Action!}}==
<lang Action!>BYTE FUNC Find(CHAR ARRAY s CHAR c BYTE POINTER err)
<syntaxhighlight lang="action!">BYTE FUNC Find(CHAR ARRAY s CHAR c BYTE POINTER err)
BYTE i
BYTE i
FOR i=1 TO s(0)
FOR i=1 TO s(0)
Line 487: Line 496:
PutE();
PutE();
OD
OD
RETURN</lang>
RETURN</syntaxhighlight>
{{out}}
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/A+B.png Screenshot from Atari 8-bit computer]
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/A+B.png Screenshot from Atari 8-bit computer]
Line 503: Line 512:


=={{header|Ada}}==
=={{header|Ada}}==
<lang Ada>-- Standard I/O Streams
<syntaxhighlight lang="ada">-- Standard I/O Streams


with Ada.Integer_Text_Io;
with Ada.Integer_Text_Io;
Line 512: Line 521:
Ada.Integer_Text_Io.Get (Item => B);
Ada.Integer_Text_Io.Get (Item => B);
Ada.Integer_Text_Io.Put (A+B);
Ada.Integer_Text_Io.Put (A+B);
end APlusB;</lang>
end APlusB;</syntaxhighlight>
Using appropriate user defined types:
Using appropriate user defined types:
<lang Ada>with Ada.Text_IO;
<syntaxhighlight lang="ada">with Ada.Text_IO;


procedure A_Plus_B is
procedure A_Plus_B is
Line 525: Line 534:
IO.Get (B);
IO.Get (B);
IO.Put (A + B, Width => 4, Base => 10);
IO.Put (A + B, Width => 4, Base => 10);
end A_Plus_B;</lang>
end A_Plus_B;</syntaxhighlight>


=={{header|Agena}}==
=={{header|Agena}}==
Tested with Agena 2.9.5 Win32
Tested with Agena 2.9.5 Win32
<lang agena>scope
<syntaxhighlight lang="agena">scope
local f := trim( io.read() ) split " "; # read a line and split into fields
local f := trim( io.read() ) split " "; # read a line and split into fields
local a := tonumber( f[ 1 ] );
local a := tonumber( f[ 1 ] );
local b := tonumber( f[ 2 ] );
local b := tonumber( f[ 2 ] );
print( a + b )
print( a + b )
epocs</lang>
epocs</syntaxhighlight>


=={{header|Aime}}==
=={{header|Aime}}==
<lang aime>file f;
<syntaxhighlight lang="aime">file f;
list l;
list l;


Line 543: Line 552:
f_list(f, l, 0);
f_list(f, l, 0);
o_integer(atoi(l[0]) + atoi(l[1]));
o_integer(atoi(l[0]) + atoi(l[1]));
o_newline();</lang>
o_newline();</syntaxhighlight>


=={{header|ALGOL 60}}==
=={{header|ALGOL 60}}==
{{works with|A60}}
{{works with|A60}}
<lang algol60>begin
<syntaxhighlight lang="algol60">begin
comment A+B;
comment A+B;
integer a,b;
integer a,b;
ininteger(0,a); ininteger(0,b);
ininteger(0,a); ininteger(0,b);
outinteger(1,a+b)
outinteger(1,a+b)
end </lang>
end </syntaxhighlight>
{{in}}
{{in}}
<pre>
<pre>
Line 569: Line 578:
{{wont work with|ELLA ALGOL 68|Any (with appropriate job cards) - missing transput function "read int"}}
{{wont work with|ELLA ALGOL 68|Any (with appropriate job cards) - missing transput function "read int"}}
===Console===
===Console===
<lang algol68>print((read int + read int))</lang>
<syntaxhighlight lang="algol68">print((read int + read int))</syntaxhighlight>
Input:
Input:
<pre>
<pre>
Line 580: Line 589:


===File===
===File===
<lang algol68>open(stand in, "input.txt", stand in channel);
<syntaxhighlight lang="algol68">open(stand in, "input.txt", stand in channel);
open(stand out, "output.txt", stand out channel);
open(stand out, "output.txt", stand out channel);
print((read int + read int))</lang>
print((read int + read int))</syntaxhighlight>
Input "input.txt":
Input "input.txt":
<pre>
<pre>
Line 593: Line 602:


=={{header|ALGOL W}}==
=={{header|ALGOL W}}==
<lang algolw>begin
<syntaxhighlight lang="algolw">begin
integer a, b;
integer a, b;
read( a, b );
read( a, b );
write( a + b )
write( a + b )
end.</lang>
end.</syntaxhighlight>


=={{header|Amazing Hopper}}==
=={{header|Amazing Hopper}}==
<syntaxhighlight lang="amazing hopper">
<lang Amazing Hopper>
#include <hbasic.h>
#include <hbasic.h>


Line 615: Line 624:
Print("Suma : ", Token(1),Val(Token$(msg)) Plus (Token(2),Val(Token$(msg))), Newl)
Print("Suma : ", Token(1),Val(Token$(msg)) Plus (Token(2),Val(Token$(msg))), Newl)
End
End
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 625: Line 634:
Version dos: hopper-BASIC acepta "programación fluída"
Version dos: hopper-BASIC acepta "programación fluída"


<syntaxhighlight lang="amazing hopper">
<lang Amazing Hopper>
#include <hbasic.h>
#include <hbasic.h>


Line 646: Line 655:
Take(A, B), and Add It; then Print It with a Newl
Take(A, B), and Add It; then Print It with a Newl
End
End
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 660: Line 669:


=={{header|Apex}}==
=={{header|Apex}}==
<syntaxhighlight lang="apex">
<lang Apex>


static Integer sumOfTwoNums(Integer A, Integer B) {
static Integer sumOfTwoNums(Integer A, Integer B) {
Line 677: Line 686:
A = 50 and B = -25: 25
A = 50 and B = -25: 25


</syntaxhighlight>
</lang>


=={{header|APL}}==
=={{header|APL}}==
<lang APL> ⎕+⎕ </lang>
<syntaxhighlight lang="apl"> ⎕+⎕ </syntaxhighlight>


=={{header|AppleScript}}==
=={{header|AppleScript}}==
Open the '''AppleScript Editor''' and save this as '''A+B.scpt''' on your Desktop
Open the '''AppleScript Editor''' and save this as '''A+B.scpt''' on your Desktop
<lang AppleScript>on run argv
<syntaxhighlight lang="applescript">on run argv
try
try
return ((first item of argv) as integer) + (second item of argv) as integer
return ((first item of argv) as integer) + (second item of argv) as integer
Line 690: Line 699:
return "Usage with -1000 <= a,b <= 1000: " & tab & " A+B.scpt a b"
return "Usage with -1000 <= a,b <= 1000: " & tab & " A+B.scpt a b"
end try
end try
end run</lang>
end run</syntaxhighlight>


To make this run in Terminal open the '''Terminal.app''' and type
To make this run in Terminal open the '''Terminal.app''' and type
Line 700: Line 709:


=={{header|Arc}}==
=={{header|Arc}}==
<syntaxhighlight lang="arc">
<lang Arc>
(prn (+ (read)
(prn (+ (read)
(read)))
(read)))
</syntaxhighlight>
</lang>


=={{header|Argile}}==
=={{header|Argile}}==
{{trans|C}}
{{trans|C}}
{{works with|Argile|1.0.0}}
{{works with|Argile|1.0.0}}
<lang Argile>(: Standard input-output streams :)
<syntaxhighlight lang="argile">(: Standard input-output streams :)
use std, array
use std, array
Cfunc scanf "%d%d" (&val int a) (&val int b)
Cfunc scanf "%d%d" (&val int a) (&val int b)
printf "%d\n" (a + b)</lang>
printf "%d\n" (a + b)</syntaxhighlight>
<lang Argile>(: Input file : input.txt :)
<syntaxhighlight lang="argile">(: Input file : input.txt :)
(: Output file: output.txt :)
(: Output file: output.txt :)
use std, array
use std, array
Line 721: Line 730:
fprintf out "%d\n" (x+y)
fprintf out "%d\n" (x+y)
fclose in
fclose in
fclose out</lang>
fclose out</syntaxhighlight>


=={{header|ARM Assembly}}==
=={{header|ARM Assembly}}==
Line 727: Line 736:
Exploiting C standard library functions (scanf and printf).
Exploiting C standard library functions (scanf and printf).
Requires arm-linux-gnueabi-gcc and qemu-arm. Compile with:
Requires arm-linux-gnueabi-gcc and qemu-arm. Compile with:
<lang ARM_Assembly>arm-linux-gnueabi-as src.s -o src.o && arm-linux-gnueabi-gcc -static src.o -o run && qemu-arm run</lang>
<syntaxhighlight lang="arm_assembly">arm-linux-gnueabi-as src.s -o src.o && arm-linux-gnueabi-gcc -static src.o -o run && qemu-arm run</syntaxhighlight>


<syntaxhighlight lang="arm_assembly">.text
<lang ARM_Assembly>.text
.global main
.global main
.extern printf
.extern printf
Line 755: Line 764:
.bss
.bss
num_a: .skip 4
num_a: .skip 4
num_b: .skip 4</lang>
num_b: .skip 4</syntaxhighlight>


{{works with|gcc|Linux}}
{{works with|gcc|Linux}}
Line 775: Line 784:
Save in ab.S
Save in ab.S
Build with:
Build with:
<lang ARM_Assembly>as -o ab.o ab.S
<syntaxhighlight lang="arm_assembly">as -o ab.o ab.S
ld -o a.out ab.o</lang>
ld -o a.out ab.o</syntaxhighlight>


<syntaxhighlight lang="arm_assembly">.data
<lang ARM_Assembly>.data
.align 2
.align 2
.code 32
.code 32
Line 1,291: Line 1,300:
movlt r0, #0
movlt r0, #0
ldmfd sp!, {r7, pc}
ldmfd sp!, {r7, pc}
</syntaxhighlight>
</lang>


=={{header|Arturo}}==
=={{header|Arturo}}==


<lang rebol>while ø [
<syntaxhighlight lang="rebol">while ø [
x: map split.words input "give me 2 numbers:" 'x -> to :integer x
x: map split.words input "give me 2 numbers:" 'x -> to :integer x
print add x\0 x\1
print add x\0 x\1
]
]
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 1,309: Line 1,318:


=={{header|AsciiDots}}==
=={{header|AsciiDots}}==
<<syntaxhighlight lang="asciidots">
<Lang AsciiDots>
&-#$-\
&-#$-\
.-#?-[+]
.-#?-[+]
.-#?--/
.-#?--/
</syntaxhighlight>
</Lang>


=={{header|ATS}}==
=={{header|ATS}}==
<syntaxhighlight lang="ats">
<lang ATS>
(* ****** ****** *)
(* ****** ****** *)
//
//
Line 1,343: Line 1,352:


(* ****** ****** *)
(* ****** ****** *)
</syntaxhighlight>
</lang>


=={{header|AutoHotkey}}==
=={{header|AutoHotkey}}==
This handles more than two inputs
This handles more than two inputs
<lang AutoHotkey>Gui, Add, Edit, vEdit ;Enter your A+B, i.e. 5+3 or 5+3+1+4+6+2
<syntaxhighlight lang="autohotkey">Gui, Add, Edit, vEdit ;Enter your A+B, i.e. 5+3 or 5+3+1+4+6+2
Gui, Add, Button, gAdd, Add
Gui, Add, Button, gAdd, Add
Gui, Add, Edit, ReadOnly x+10 w80
Gui, Add, Edit, ReadOnly x+10 w80
Line 1,359: Line 1,368:
GuiControl, Text, Edit2, %var% ;here it displays var in the second edit control
GuiControl, Text, Edit2, %var% ;here it displays var in the second edit control
var := 0 ;here it makes sure var is 0 so it won't contain the value from the previous addition
var := 0 ;here it makes sure var is 0 so it won't contain the value from the previous addition
return</lang>
return</syntaxhighlight>


=={{header|AutoIt}}==
=={{header|AutoIt}}==
<lang AutoIt>;AutoIt Version: 3.2.10.0
<syntaxhighlight lang="autoit">;AutoIt Version: 3.2.10.0
$num = "45 54"
$num = "45 54"
consolewrite ("Sum of " & $num & " is: " & sum($num))
consolewrite ("Sum of " & $num & " is: " & sum($num))
Line 1,368: Line 1,377:
$numm = StringSplit($numbers," ")
$numm = StringSplit($numbers," ")
Return $numm[1]+$numm[$numm[0]]
Return $numm[1]+$numm[$numm[0]]
EndFunc</lang>
EndFunc</syntaxhighlight>


===Example2===
===Example2===
This version can handle any amount of numbers in the input:
This version can handle any amount of numbers in the input:
<lang AutoIt>ConsoleWrite("# A+B:" & @CRLF)
<syntaxhighlight lang="autoit">ConsoleWrite("# A+B:" & @CRLF)


Func Sum($inp)
Func Sum($inp)
Line 1,393: Line 1,402:
; so the program works correctly even with this input:
; so the program works correctly even with this input:
Local $inp = "999x y 42 -999", $res = Sum($inp)
Local $inp = "999x y 42 -999", $res = Sum($inp)
ConsoleWrite($inp & " --> " & $res & @CRLF)</lang>
ConsoleWrite($inp & " --> " & $res & @CRLF)</syntaxhighlight>
{{Out}}
{{Out}}
<pre>
<pre>
Line 1,402: Line 1,411:


=={{header|AWK}}==
=={{header|AWK}}==
<lang awk>{print $1 + $2}</lang>
<syntaxhighlight lang="awk">{print $1 + $2}</syntaxhighlight>

=={{header|BabyCobol}}==
<syntaxhighlight lang="cobol">
* NB: COBOL's ACCEPT does not work with multiple identifiers
IDENTIFICATION DIVISION.
PROGRAM-ID. PLUS.
DATA DIVISION.
01 A PICTURE IS S9999.
01 B LIKE A.
PROCEDURE DIVISION.
DISPLAY "Enter two numbers: " WITH NO ADVANCING.
ACCEPT A B.
ADD A TO B.
DISPLAY "A+B =" B.
</syntaxhighlight>


=={{header|BASIC}}==
=={{header|BASIC}}==
<lang qbasic>DEFINT A-Z
<syntaxhighlight lang="qbasic">DEFINT A-Z


tryagain:
tryagain:
Line 1,420: Line 1,444:
ELSE
ELSE
GOTO tryagain
GOTO tryagain
END IF</lang>
END IF</syntaxhighlight>


==={{header|Applesoft BASIC}}===
==={{header|Applesoft BASIC}}===
<lang ApplesoftBasic>10 BH = PEEK(37)
<syntaxhighlight lang="applesoftbasic">10 BH = PEEK(37)
20 INPUT ""; A$ : I$ = A$ : VTAB BH : A = PEEK(40) + PEEK(41) * 256 : FOR S = 0 TO 39 : IF PEEK(A + S) = 160 THEN NEXT S : S = 0
20 INPUT ""; A$ : I$ = A$ : VTAB BH : A = PEEK(40) + PEEK(41) * 256 : FOR S = 0 TO 39 : IF PEEK(A + S) = 160 THEN NEXT S : S = 0
40 IF LEN(I$) THEN IF MID$(I$, LEN(I$), 1) = " " THEN I$ = MID$(I$, 1, LEN(I$) - 1) : GOTO 40RTRIM
40 IF LEN(I$) THEN IF MID$(I$, LEN(I$), 1) = " " THEN I$ = MID$(I$, 1, LEN(I$) - 1) : GOTO 40RTRIM
Line 1,433: Line 1,457:
100 VTAB BH
100 VTAB BH
110 HTAB LEN(A$) + 2 + S
110 HTAB LEN(A$) + 2 + S
120 PRINT C%</lang>
120 PRINT C%</syntaxhighlight>


==={{header|BaCon}}===
==={{header|BaCon}}===
<lang qbasic>' A+B
<syntaxhighlight lang="qbasic">' A+B
INPUT d$
INPUT d$
PRINT VAL(TOKEN$(d$, 1)) + VAL(TOKEN$(d$, 2))</lang>
PRINT VAL(TOKEN$(d$, 1)) + VAL(TOKEN$(d$, 2))</syntaxhighlight>


==={{header|BASIC256}}===
==={{header|BASIC256}}===
<lang basic256>dim a(2)
<syntaxhighlight lang="basic256">dim a(2)
input "Enter two numbers separated by a space?", t$
input "Enter two numbers separated by a space?", t$
a = explode(t$," ")
a = explode(t$," ")
print t$ & " " & int(a[0]) + int(a[1])</lang>
print t$ & " " & int(a[0]) + int(a[1])</syntaxhighlight>


==={{header|BBC BASIC}}===
==={{header|BBC BASIC}}===
<lang bbc> REPEAT
<syntaxhighlight lang="bbc"> REPEAT
hereY% = VPOS
hereY% = VPOS
INPUT LINE "" q$
INPUT LINE "" q$
Line 1,460: Line 1,484:
PRINT TAB(hereX%, hereY%) ; a + b
PRINT TAB(hereX%, hereY%) ; a + b
ENDIF
ENDIF
UNTIL FALSE</lang>
UNTIL FALSE</syntaxhighlight>
That seems overly complicated. What's wrong with:
That seems overly complicated. What's wrong with:
<lang bbc> REPEAT
<syntaxhighlight lang="bbc"> REPEAT
INPUT LINE "" q$
INPUT LINE "" q$
space% = INSTR(q$," ")
space% = INSTR(q$," ")
PRINT VAL LEFT$(q$,space%-1) + VAL MID$(q$,space%+1)
PRINT VAL LEFT$(q$,space%-1) + VAL MID$(q$,space%+1)
UNTIL FALSE</lang>
UNTIL FALSE</syntaxhighlight>

==={{header|Chipmunk Basic}}===
{{works with|Chipmunk Basic|3.6.4}}
{{works with|Applesoft BASIC}}
{{works with|GW-BASIC}}
{{works with|MSX_BASIC}}
{{works with|PC-BASIC|any}}
{{works with|QBasic}}
<syntaxhighlight lang="qbasic">10 CLS : rem 10 HOME for Applesoft BASIC
20 PRINT "ENTER TWO NUMBERS, SEPARATED BY A SPACE: ";
30 INPUT X$
40 I = 1 : N = LEN(X$)
50 IF MID$(X$, I, 1) <> " " AND I < N THEN I = I + 1 : GOTO 50
60 A = VAL(LEFT$(X$, I))
70 B = VAL(RIGHT$(X$, N - 1))
80 PRINT A + B
90 END</syntaxhighlight>


==={{header|Commodore BASIC}}===
==={{header|Commodore BASIC}}===
<lang qbasic>10 PRINT "ENTER TWO NUMBERS, SEPARATED BY A SPACE: ";
<syntaxhighlight lang="qbasic">10 PRINT "ENTER TWO NUMBERS, SEPARATED BY A SPACE: ";
20 INPUT X$
20 INPUT X$
30 I = 1 : N = LEN(X$)
30 I = 1 : N = LEN(X$)
Line 1,475: Line 1,516:
50 A = VAL(LEFT$(X$,I))
50 A = VAL(LEFT$(X$,I))
60 B = VAL(RIGHT$(X$,N-1))
60 B = VAL(RIGHT$(X$,N-1))
70 PRINT A+B</lang>
70 PRINT A+B</syntaxhighlight>


==={{header|FreeBASIC}}===
==={{header|FreeBASIC}}===
<lang freebasic>' fb 1.05.0 Win64
<syntaxhighlight lang="freebasic">' fb 1.05.0 Win64


Dim As Integer a, b
Dim As Integer a, b
Line 1,494: Line 1,535:
Print
Print
Print "Press any key to quit the program"
Print "Press any key to quit the program"
Sleep</lang>
Sleep</syntaxhighlight>

==={{header|GW-BASIC}}===
The [[#Chipmunk_Basic|Chipmunk Basic]] solution works without any changes.


==={{header|FUZE BASIC}}===
==={{header|FUZE BASIC}}===
<lang qbasic>INPUT n$
<syntaxhighlight lang="qbasic">INPUT n$
PRINT VAL(LEFT$(n$,(LEN(STR$(VAL(n$))))))+VAL(RIGHT$(n$,(LEN(n$)-LEN(STR$(VAL(n$)))-1)))
PRINT VAL(LEFT$(n$,(LEN(STR$(VAL(n$))))))+VAL(RIGHT$(n$,(LEN(n$)-LEN(STR$(VAL(n$)))-1)))
END</lang>
END</syntaxhighlight>


==={{header|IS-BASIC}}===
==={{header|IS-BASIC}}===
<lang IS-BASIC>100 DO
<syntaxhighlight lang="is-basic">100 DO
110 INPUT PROMPT "Ener two integers separated by a comma: ":A,B
110 INPUT PROMPT "Ener two integers separated by a comma: ":A,B
120 IF ABS(A)>1000 OR ABS(B)>1000 OR IP(A)<>A OR IP(B)<>B THEN
120 IF ABS(A)>1000 OR ABS(B)>1000 OR IP(A)<>A OR IP(B)<>B THEN
Line 1,510: Line 1,554:
160 EXIT DO
160 EXIT DO
170 END IF
170 END IF
180 LOOP</lang>
180 LOOP</syntaxhighlight>


==={{header|Liberty BASIC}}===
==={{header|Liberty BASIC}}===
<lang lb>input, n$
<syntaxhighlight lang="lb">input, n$
print eval(word$(n$,1);" + ";word$(n$,2))</lang>
print eval(word$(n$,1);" + ";word$(n$,2))</syntaxhighlight>

==={{header|Minimal BASIC}}===
{{works with|QBasic}}
{{works with|QuickBasic}}
{{works with|Applesoft BASIC}}
{{works with|BASICA}}
{{works with|Chipmunk Basic}}
{{works with|GW-BASIC}}
{{works with|IS-BASIC}}
{{works with|MSX Basic}}
{{works with|Just BASIC}}
{{works with|Liberty BASIC}}
{{works with|Run BASIC}}
{{works with|Yabasic}}
<syntaxhighlight lang="qbasic">10 PRINT "ENTER NUMBER A";
20 INPUT A
30 PRINT "ENTER NUMBER B";
40 INPUT B
50 PRINT A+B
60 END</syntaxhighlight>

==={{header|MSX Basic}}===
The [[#Chipmunk_Basic|Chipmunk Basic]] solution works without any changes.


==={{header|OxygenBasic}}===
==={{header|OxygenBasic}}===
<lang>
<syntaxhighlight lang="text">
uses console
uses console
int i
int i
Line 1,530: Line 1,597:
print val(s)+val(mid(s,i))+cr
print val(s)+val(mid(s,i))+cr
loop
loop
</syntaxhighlight>
</lang>


==={{header|Sinclair ZX81 BASIC}}===
==={{header|Sinclair ZX81 BASIC}}===
<lang basic>10 INPUT A$
<syntaxhighlight lang="basic">10 INPUT A$
20 LET I=1
20 LET I=1
30 IF A$(I)=" " THEN GOTO 60
30 IF A$(I)=" " THEN GOTO 60
40 LET I=I+1
40 LET I=I+1
50 GOTO 30
50 GOTO 30
60 PRINT VAL A$( TO I-1)+VAL A$(I+1 TO )</lang>
60 PRINT VAL A$( TO I-1)+VAL A$(I+1 TO )</syntaxhighlight>

==={{header|SmallBASIC}}===
<syntaxhighlight lang="SmallBASIC">
input "Enter number A: "; a
input "Enter number B: "; b
print "A + B = "; a + b
</syntaxhighlight>


==={{Header|Tiny BASIC}}===
==={{Header|Tiny BASIC}}===
<lang Tiny BASIC>REM Rosetta Code problem: https://rosettacode.org/wiki/A+B
<syntaxhighlight lang="tiny basic">REM Rosetta Code problem: https://rosettacode.org/wiki/A+B
REM by Jjuanhdez, 06/2022
REM by Jjuanhdez, 06/2022


Line 1,558: Line 1,632:
60 PRINT "Both integers must be in the range [-1000..1000] - try again."
60 PRINT "Both integers must be in the range [-1000..1000] - try again."
GOTO 10
GOTO 10
70 END</lang>
70 END</syntaxhighlight>


==={{header|True BASIC}}===
==={{header|True BASIC}}===
<lang qbasic>DO
<syntaxhighlight lang="qbasic">DO
INPUT PROMPT "Enter two integers separated by a comma: ": A, B
INPUT PROMPT "Enter two integers separated by a comma: ": A, B
IF ABS(A)>1000 OR ABS(B)>1000 OR IP(A)<>A OR IP(B)<>B THEN
IF ABS(A)>1000 OR ABS(B)>1000 OR IP(A)<>A OR IP(B)<>B THEN
Line 1,571: Line 1,645:
END IF
END IF
LOOP
LOOP
END</lang>
END</syntaxhighlight>
==={{header|uBasic/4tH}}===
==={{header|uBasic/4tH}}===
<lang>s = FUNC(_GetInt(1000)) + FUNC(_GetInt(1000))
<syntaxhighlight lang="text">s = FUNC(_GetInt(1000)) + FUNC(_GetInt(1000))
Print "The sum is: ";s
Print "The sum is: ";s
End
End
Line 1,586: Line 1,660:
Print "Wrong, must be between "; -a@; " and "; a@; ". Try again.."
Print "Wrong, must be between "; -a@; " and "; a@; ". Try again.."
Loop
Loop
Return (b@)</lang>
Return (b@)</syntaxhighlight>

==={{header|XBasic}}===
{{works with|Windows XBasic}}
<syntaxhighlight lang="qbasic">PROGRAM "A+B"
VERSION "0.0000"

DECLARE FUNCTION Entry ()

FUNCTION Entry ()
a$ = INLINE$("Enter integer A: ")
a = SLONG(a$)
b$ = INLINE$("Enter integer B: ")
b = SLONG(b$)
DO WHILE 1
IF ABS(a) > 1000 OR ABS(b) > 1000 THEN
PRINT "Both integers must be in the interval [-1000..1000] - try again."
PRINT
ELSE
PRINT "Their sum is"; a + b
EXIT DO
END IF
LOOP
END FUNCTION
END PROGRAM</syntaxhighlight>


=={{header|Batch File}}==
=={{header|Batch File}}==
Prompts version
Prompts version
<lang dos>::aplusb.cmd
<syntaxhighlight lang="dos">::aplusb.cmd
@echo off
@echo off
setlocal
setlocal
Line 1,597: Line 1,695:
set /a c=a+b
set /a c=a+b
echo %c%
echo %c%
endlocal</lang>
endlocal</syntaxhighlight>
All on the commandline version
All on the commandline version
<lang dos>::aplusb.cmd
<syntaxhighlight lang="dos">::aplusb.cmd
@echo off
@echo off
setlocal
setlocal
Line 1,606: Line 1,704:
set /a c=a+b
set /a c=a+b
echo %c%
echo %c%
endlocal</lang>
endlocal</syntaxhighlight>
Formula on the command line version
Formula on the command line version
<lang dos>::aplusb.cmd
<syntaxhighlight lang="dos">::aplusb.cmd
@echo off
@echo off
setlocal
setlocal
set /a c=%~1
set /a c=%~1
echo %c%
echo %c%
endlocal</lang>
endlocal</syntaxhighlight>
Example of 'Formula on the command line version'
Example of 'Formula on the command line version'
<pre>
<pre>
Line 1,622: Line 1,720:
</pre>
</pre>
Parse the input stream version (thanks to Tom Lavedas on alt.msdos.batch.nt)
Parse the input stream version (thanks to Tom Lavedas on alt.msdos.batch.nt)
<lang dos>::aplusb.cmd
<syntaxhighlight lang="dos">::aplusb.cmd
@echo off
@echo off
setlocal
setlocal
Line 1,634: Line 1,732:
set /a res=res+%1
set /a res=res+%1
shift
shift
if "%1" neq "" goto :add</lang>
if "%1" neq "" goto :add</syntaxhighlight>
Example of 'parse the input stream version'
Example of 'parse the input stream version'
<pre>>aplusb
<pre>>aplusb
Line 1,645: Line 1,743:
=={{header|bc}}==
=={{header|bc}}==
{{Works with|GNU bc}}
{{Works with|GNU bc}}
<lang bc>read() + read()</lang>
<syntaxhighlight lang="bc">read() + read()</syntaxhighlight>


=={{header|Befunge}}==
=={{header|Befunge}}==
<lang befunge>&&+.@</lang>
<syntaxhighlight lang="befunge">&&+.@</syntaxhighlight>


=={{header|Bird}}==
=={{header|Bird}}==
<lang Bird>use Console Math
<syntaxhighlight lang="bird">use Console Math


define Main
define Main
Line 1,657: Line 1,755:
$b Console.Read
$b Console.Read
Console.Println Math.Add $a $b
Console.Println Math.Add $a $b
end</lang>
end</syntaxhighlight>


=={{header|BlooP}}==
=={{header|BlooP}}==
BlooP and FlooP can't actually read from stdin, but here's the procedure it would use, if it could.
BlooP and FlooP can't actually read from stdin, but here's the procedure it would use, if it could.
<syntaxhighlight lang="bloop">
<Lang BlooP>
DEFINE PROCEDURE ''ADD'' [A, B]:
DEFINE PROCEDURE ''ADD'' [A, B]:
BLOCK 0: BEGIN
BLOCK 0: BEGIN
OUTPUT <= A + B;
OUTPUT <= A + B;
BLOCK 0: END.
BLOCK 0: END.
</syntaxhighlight>
</Lang>


=={{header|bootBASIC}}==
=={{header|bootBASIC}}==
Both numbers are entered separately.
Both numbers are entered separately.
<lang bootBASIC>10 print "Number 1";
<syntaxhighlight lang="bootbasic">10 print "Number 1";
20 input a
20 input a
30 print "Number 2";
30 print "Number 2";
40 input b
40 input b
50 print a+b</lang>
50 print a+b</syntaxhighlight>


=={{header|BQN}}==
=={{header|BQN}}==
Line 1,680: Line 1,778:
{{works with|https://github.com/dzaima/CBQN CBQN}}
{{works with|https://github.com/dzaima/CBQN CBQN}}


<lang bqn>#!/usr/bin/env bqn
<syntaxhighlight lang="bqn">#!/usr/bin/env bqn


# Cut 𝕩 at occurrences of 𝕨, removing separators and empty segments
# Cut 𝕩 at occurrences of 𝕨, removing separators and empty segments
Line 1,693: Line 1,791:


# •GetLine and •_while_ are nonstandard CBQN extensions.
# •GetLine and •_while_ are nonstandard CBQN extensions.
{•Show +´ ParseNums 𝕩 ⋄ •GetLine@} •_while_ (@⊸≢) •GetLine@</lang>
{•Show +´ ParseNums 𝕩 ⋄ •GetLine@} •_while_ (@⊸≢) •GetLine@</syntaxhighlight>


=={{header|Bracmat}}==
=={{header|Bracmat}}==
<code>filter</code> is a pattern that checks that input is a non-fractional number not less than -1000 and not greater than 1000. The filter is applied to each input.
<code>filter</code> is a pattern that checks that input is a non-fractional number not less than -1000 and not greater than 1000. The filter is applied to each input.
<lang bracmat>( out
<syntaxhighlight lang="bracmat">( out
$ ( put$"Enter two integer numbers between -1000 and 1000:"
$ ( put$"Enter two integer numbers between -1000 and 1000:"
& (filter=~/#%:~<-1000:~>1000)
& (filter=~/#%:~<-1000:~>1000)
Line 1,704: Line 1,802:
| "Invalid input. Try again"
| "Invalid input. Try again"
)
)
);</lang>
);</syntaxhighlight>


=={{header|Brainf***}}==
=={{header|Brainf***}}==
<lang brainf***>INPUT AND SUMMATION
<syntaxhighlight lang="brainf***">INPUT AND SUMMATION
TODO if first symbol is a minus sign print Qgo awayQ
TODO if first symbol is a minus sign print Qgo awayQ
+> initialize sum to one
+> initialize sum to one
Line 1,730: Line 1,828:
>++++++++++++++++++++++++++++++++++++++++++++++++> convert remainder to ascii digit
>++++++++++++++++++++++++++++++++++++++++++++++++> convert remainder to ascii digit
]
]
<[.<<] print ascii digits</lang>
<[.<<] print ascii digits</syntaxhighlight>


=={{header|Brat}}==
=={{header|Brat}}==
<lang brat>numbers = g.split[0,1].map(:to_i)
<syntaxhighlight lang="brat">numbers = g.split[0,1].map(:to_i)
p numbers[0] + numbers[1] #Prints the sum of the input</lang>
p numbers[0] + numbers[1] #Prints the sum of the input</syntaxhighlight>

=={{header|Bruijn}}==
<syntaxhighlight lang="bruijn">
:import std/Combinator .
:import std/String .
:import std/Number .
:import std/Char C

main (split-by (C.eq? ' ')) → &(add ⋔ string→number)
</syntaxhighlight>


=={{header|Burlesque}}==
=={{header|Burlesque}}==
<lang burlesque>ps++</lang>
<syntaxhighlight lang="burlesque">ps++</syntaxhighlight>


=={{header|C}}==
=={{header|C}}==
<lang c>// Standard input-output streams
<syntaxhighlight lang="c">// Standard input-output streams
#include <stdio.h>
#include <stdio.h>
int main()
int main()
Line 1,748: Line 1,856:
printf("%d\n", a + b);
printf("%d\n", a + b);
return 0;
return 0;
}</lang>
}</syntaxhighlight>
<lang c>// Input file: input.txt
<syntaxhighlight lang="c">// Input file: input.txt
// Output file: output.txt
// Output file: output.txt
#include <stdio.h>
#include <stdio.h>
Line 1,760: Line 1,868:
printf("%d\n", a + b);
printf("%d\n", a + b);
return 0;
return 0;
}</lang>
}</syntaxhighlight>
<syntaxhighlight lang="c">
<lang c>
#include <stdio.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdlib.h>
Line 1,769: Line 1,877:
return 0;
return 0;
}
}
</syntaxhighlight>
</lang>


=={{header|C sharp|C#}}==
=={{header|C sharp|C#}}==
<lang csharp>using System;
<syntaxhighlight lang="csharp">using System;
using System.Linq;
using System.Linq;


Line 1,781: Line 1,889:
Console.WriteLine(Console.ReadLine().Split().Select(int.Parse).Sum());
Console.WriteLine(Console.ReadLine().Split().Select(int.Parse).Sum());
}
}
}</lang>
}</syntaxhighlight>
Another way (not recommended since it does not work with more than two numbers):
Another way (not recommended since it does not work with more than two numbers):
<lang csharp>using System;
<syntaxhighlight lang="csharp">using System;


class Program
class Program
Line 1,796: Line 1,904:
Console.WriteLine(sum.ToString());
Console.WriteLine(sum.ToString());
}
}
}</lang>
}</syntaxhighlight>


=={{header|C++}}==
=={{header|C++}}==
<lang cpp>// Standard input-output streams
<syntaxhighlight lang="cpp">// Standard input-output streams
#include <iostream>
#include <iostream>
using namespace std;
using namespace std;
Line 1,807: Line 1,915:
cin >> a >> b;
cin >> a >> b;
cout << a + b << endl;
cout << a + b << endl;
}</lang>
}</syntaxhighlight>
<lang cpp>// Input file: input.txt
<syntaxhighlight lang="cpp">// Input file: input.txt
// Output file: output.txt
// Output file: output.txt
#include <fstream>
#include <fstream>
Line 1,820: Line 1,928:
out << a + b << endl;
out << a + b << endl;
return 0;
return 0;
}</lang>
}</syntaxhighlight>


=={{header|Ceylon}}==
=={{header|Ceylon}}==
<lang ceylon>shared void run() {
<syntaxhighlight lang="ceylon">shared void run() {


print("please enter two numbers for me to add");
print("please enter two numbers for me to add");
Line 1,847: Line 1,955:
}
}
}
}
}</lang>
}</syntaxhighlight>

=={{header|CFEngine}}==
There is no concept of CFEngine policy reading from stdin so I will read from a file.

<syntaxhighlight lang="cfengine">
$ cat sum.cf
bundle agent main
{
vars:
"line_count" int => readintarray(
"input",
"${this.promise_dirname}${const.dirsep}input.txt",
"#[^\n]*",
" ",
"inf",
"inf"
);
"indices" slist => getindices( "input" );
reports:
"${with}" with => format( "%d", eval( "${input[${indices}][0]} + ${input[${indices}][1]}" ));
DEBUG::
"line_count is ${line_count}";
"input is ${with}" with => storejson( "input" );
"input[${indices}] is ${with}" with => storejson( "input[${indices}]" );
}

$ cat input.txt
2 3
2 2

$ cf-agent -KIf ./sum.cf
R: 5
R: 4
</syntaxhighlight>

The "R:" prefix is for a report promise and the only way to output to stdout with policy.
You could also output to a file I suppose.


=={{header|Clojure}}==
=={{header|Clojure}}==
<lang clojure>(println (+ (Integer/parseInt (read-line)) (Integer/parseInt (read-line))))
<syntaxhighlight lang="clojure">(println (+ (Integer/parseInt (read-line)) (Integer/parseInt (read-line))))
3
3
4
4
=>7</lang>
=>7</syntaxhighlight>
<lang clojure>(eval (read-string (str "(+ " (read-line) " )") ))
<syntaxhighlight lang="clojure">(eval (read-string (str "(+ " (read-line) " )") ))
3 3
3 3
6</lang>
6</syntaxhighlight>


Translation of Common Lisp version:
Translation of Common Lisp version:
<lang clojure>(println (+ (read) (read)))
<syntaxhighlight lang="clojure">(println (+ (read) (read)))
3 4
3 4
7</lang>
7</syntaxhighlight>




Safely and without reader tricks:
Safely and without reader tricks:
<lang clojure>(let [ints (map #(Integer/parseInt %) (clojure.string/split (read-line) #"\s") )]
<syntaxhighlight lang="clojure">(let [ints (map #(Integer/parseInt %) (clojure.string/split (read-line) #"\s") )]
(println (reduce + ints)))
(println (reduce + ints)))
3 4
3 4
=>7</lang>
=>7</syntaxhighlight>


or same as above, but without "let":
or same as above, but without "let":
<lang clojure>(println (reduce + (map #(Integer/parseInt %) (clojure.string/split (read-line) #"\s") )))
<syntaxhighlight lang="clojure">(println (reduce + (map #(Integer/parseInt %) (clojure.string/split (read-line) #"\s") )))


3 4
3 4
=>7</lang>
=>7</syntaxhighlight>


=={{header|COBOL}}==
=={{header|COBOL}}==
<lang cobol> IDENTIFICATION DIVISION.
<syntaxhighlight lang="cobol"> IDENTIFICATION DIVISION.
PROGRAM-ID. A-Plus-B.
PROGRAM-ID. A-Plus-B.


Line 1,896: Line 2,041:


GOBACK
GOBACK
.</lang>
.</syntaxhighlight>


A second version.
A second version.


<syntaxhighlight lang="cobol">
<lang COBOL>


IDENTIFICATION DIVISION.
IDENTIFICATION DIVISION.
Line 1,941: Line 2,086:
STOP RUN.
STOP RUN.


</syntaxhighlight>
</lang>


=={{header|CoffeeScript}}==
=={{header|CoffeeScript}}==
{{trans|JavaScript}}
{{trans|JavaScript}}
<lang html4strict><html>
<syntaxhighlight lang="html4strict"><html>
<script type="text/javascript" src="http://jashkenas.github.com/coffee-script/extras/coffee-script.js"></script>
<script type="text/javascript" src="http://jashkenas.github.com/coffee-script/extras/coffee-script.js"></script>
<script type="text/coffeescript">
<script type="text/coffeescript">
Line 1,958: Line 2,103:
<div id='output'></div>
<div id='output'></div>
</body>
</body>
</html></lang>
</html></syntaxhighlight>


{{works with|Node.js}}
{{works with|Node.js}}
<lang coffeescript>
<syntaxhighlight lang="coffeescript">
{ stdin } = process
{ stdin } = process
sum = ( a, b ) -> a + b
sum = ( a, b ) -> a + b
Line 1,992: Line 2,137:
# Start the main loop.
# Start the main loop.
do prompt
do prompt
</syntaxhighlight>
</lang>


=={{header|Common Lisp}}==
=={{header|Common Lisp}}==
<lang lisp>(write (+ (read) (read)))</lang>
<syntaxhighlight lang="lisp">(write (+ (read) (read)))</syntaxhighlight>


=={{header|Component Pascal}}==
=={{header|Component Pascal}}==
BlackBox Component Builder
BlackBox Component Builder
<lang oberon2>
<syntaxhighlight lang="oberon2">
MODULE AB;
MODULE AB;
IMPORT StdLog, DevCommanders,TextMappers;
IMPORT StdLog, DevCommanders,TextMappers;
Line 2,029: Line 2,174:
END Go;
END Go;
END AB.
END AB.
</syntaxhighlight>
</lang>
Execute: <i>AB.Go 12 23 ~ </i><br/>
Execute: <i>AB.Go 12 23 ~ </i><br/>
{{out}}
{{out}}
Line 2,037: Line 2,182:


=={{header|Computer/zero Assembly}}==
=={{header|Computer/zero Assembly}}==
<lang czasm> STP ; wait for input
<syntaxhighlight lang="czasm"> STP ; wait for input
a: 0
a: 0
b: 0
b: 0
LDA a
LDA a
ADD b
ADD b
STP</lang>
STP</syntaxhighlight>


=={{header|Crystal}}==
=={{header|Crystal}}==
<lang ruby>puts gets.not_nil!.split.map(&.to_i).sum</lang>
<syntaxhighlight lang="ruby">puts gets.not_nil!.split.map(&.to_i).sum</syntaxhighlight>


The <code>not_nil!</code> call on <code>gets</code> is needed because <code>gets</code> might return <code>nil</code> and the compiler forces us to deal with it.
The <code>not_nil!</code> call on <code>gets</code> is needed because <code>gets</code> might return <code>nil</code> and the compiler forces us to deal with it.
Line 2,052: Line 2,197:
To handle the <code>nil</code> case we could do:
To handle the <code>nil</code> case we could do:


<lang ruby>if line = gets
<syntaxhighlight lang="ruby">if line = gets
puts line.split.map(&.to_i).sum
puts line.split.map(&.to_i).sum
else
else
puts "No input"
puts "No input"
end</lang>
end</syntaxhighlight>


=={{header|D}}==
=={{header|D}}==
===From Console===
===From Console===
<lang d>import std.stdio, std.conv, std.string;
<syntaxhighlight lang="d">import std.stdio, std.conv, std.string;


void main() {
void main() {
Line 2,070: Line 2,215:


writeln(to!int(r[0]) + to!int(r[1]));
writeln(to!int(r[0]) + to!int(r[1]));
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>30</pre>
<pre>30</pre>
===From File===
===From File===
<lang d>void main() {
<syntaxhighlight lang="d">void main() {
import std.stdio, std.file;
import std.stdio, std.file;


immutable ab = "sum_input.txt".slurp!(int, int)("%d %d")[0];
immutable ab = "sum_input.txt".slurp!(int, int)("%d %d")[0];
"sum_output.txt".File("w").writeln(ab[0] + ab[1]);
"sum_output.txt".File("w").writeln(ab[0] + ab[1]);
}</lang>
}</syntaxhighlight>


=={{header|Dart}}==
=={{header|Dart}}==
<lang Dart>import 'dart:io';
<syntaxhighlight lang="dart">import 'dart:io';


// a little helper function that checks if the string only contains
// a little helper function that checks if the string only contains
Line 2,109: Line 2,254:
}
}
}
}
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 2,118: Line 2,263:


=={{header|dc}}==
=={{header|dc}}==
<lang dc>? + psz</lang>
<syntaxhighlight lang="dc">? + psz</syntaxhighlight>


The question mark ''?'' reads and executes a line of input. The user must enter a dc program that pushes two numbers to the stack, such as ''2 3'' or ''5 _1''. (The user must use underscore ''_'' for negative numbers.)
The question mark ''?'' reads and executes a line of input. The user must enter a dc program that pushes two numbers to the stack, such as ''2 3'' or ''5 _1''. (The user must use underscore ''_'' for negative numbers.)


=={{header|DCL}}==
=={{header|DCL}}==
<lang DCL>$ read sys$command line
<syntaxhighlight lang="dcl">$ read sys$command line
$ a = f$element( 0, " ", line )
$ a = f$element( 0, " ", line )
$ b = f$element( 1, " ", line )
$ b = f$element( 1, " ", line )
$ write sys$output a, "+", b, "=", a + b</lang>
$ write sys$output a, "+", b, "=", a + b</syntaxhighlight>


=={{header|Delphi}}==
=={{header|Delphi}}==
Console version.
Console version.
<lang delphi>program SUM;
<syntaxhighlight lang="delphi">program SUM;


{$APPTYPE CONSOLE}
{$APPTYPE CONSOLE}
Line 2,144: Line 2,289:
Readln(s2);
Readln(s2);
Writeln(StrToIntDef(s1, 0) + StrToIntDef(s2,0));
Writeln(StrToIntDef(s1, 0) + StrToIntDef(s2,0));
end.</lang>
end.</syntaxhighlight>


=={{header|Diego}}==
=={{header|Diego}}==
<lang diego>set_namespace(rosettacode)_me();
<syntaxhighlight lang="diego">set_namespace(rosettacode)_me();
begin_instuct(A + B);
begin_instuct(A + B);
Line 2,161: Line 2,306:
exec_instruct(A + B)_me();
exec_instruct(A + B)_me();


reset_namespace[];</lang>
reset_namespace[];</syntaxhighlight>


=={{header|DMS}}==
=={{header|DMS}}==
<lang DMS>number a = GetNumber( "Please input 'a'", a, a ) // prompts for 'a'
<syntaxhighlight lang="dms">number a = GetNumber( "Please input 'a'", a, a ) // prompts for 'a'
number b = GetNumber( "Please input 'b'", b, b ) // prompts for 'b'
number b = GetNumber( "Please input 'b'", b, b ) // prompts for 'b'
Result( a + b + "\n" )</lang>
Result( a + b + "\n" )</syntaxhighlight>


=={{header|Dragon}}==
=={{header|Dragon}}==
<lang dragon>
<syntaxhighlight lang="dragon">
select "graphic"
select "graphic"
select "types"
select "types"
Line 2,177: Line 2,322:


showln a + b
showln a + b
</syntaxhighlight>
</lang>


=={{header|DWScript}}==
=={{header|DWScript}}==
Ghetto GUI version
Ghetto GUI version
<lang delphi>var a := StrToInt(InputBox('A+B', 'Enter 1st number', '0'));
<syntaxhighlight lang="delphi">var a := StrToInt(InputBox('A+B', 'Enter 1st number', '0'));
var b := StrToInt(InputBox('A+B', 'Enter 2nd number', '0'));
var b := StrToInt(InputBox('A+B', 'Enter 2nd number', '0'));
ShowMessage('Sum is '+IntToStr(a+b));</lang>
ShowMessage('Sum is '+IntToStr(a+b));</syntaxhighlight>


=={{header|Déjà Vu}}==
=={{header|Déjà Vu}}==
{{trans|Python}}
{{trans|Python}}
===Console===
===Console===
<lang dejavu>0
<syntaxhighlight lang="dejavu">0
for k in split !prompt "" " ":
for k in split !prompt "" " ":
+ to-num k
+ to-num k
!print</lang>
!print</syntaxhighlight>


=={{header|EasyLang}}==
=={{header|EasyLang}}==
<syntaxhighlight>
<lang>a$ = input
a$ = input
while i < len a$ and substr a$ i 1 <> " "
repeat
i += 1
i += 1
until i > len a$ or substr a$ i 1 = " "
.
.
a = number substr a$ 0 i
a = number substr a$ 1 i
b = number substr a$ i -1
b = number substr a$ i 99
print a + b
print a + b
</syntaxhighlight>
</lang>


=={{header|EchoLisp}}==
=={{header|EchoLisp}}==
<lang scheme>
<syntaxhighlight lang="scheme">
(+ (read-number 1 "value for A") (read-number 2 "value for B"))
(+ (read-number 1 "value for A") (read-number 2 "value for B"))
</syntaxhighlight>
</lang>


=={{header|EDSAC order code}}==
=={{header|EDSAC order code}}==
The EDSAC does not support input of data while a program is running, so A and B are pre-set to 37 and 28. Other values can of course be substituted: note the slightly idiosyncratic format in which integer data is written (the least significant bit set using an alphabetic character). The result of the computation is displayed in binary in the first address of storage tank 3.
The EDSAC does not support input of data while a program is running, so A and B are pre-set to 37 and 28. Other values can of course be substituted: note the slightly idiosyncratic format in which integer data is written (the least significant bit set using an alphabetic character). The result of the computation is displayed in binary in the first address of storage tank 3.
<lang edsac>[ A plus B
<syntaxhighlight lang="edsac">[ A plus B
========
========
Line 2,242: Line 2,389:
[ When loading is finished: ]
[ When loading is finished: ]


EZPF [ Branch to load point ]</lang>
EZPF [ Branch to load point ]</syntaxhighlight>
{{out}}
{{out}}
<pre>00000000001000001</pre>
<pre>00000000001000001</pre>
Line 2,260: Line 2,407:


3. Dismiss the message, make the file with the two integers the active file, and click Reset. The simulator will continue, read the integers, and print them together with their sum.
3. Dismiss the message, make the file with the two integers the active file, and click Reset. The simulator will continue, read the integers, and print them together with their sum.
<lang edsac>
<syntaxhighlight lang="edsac">
[A + B for Rosetta Code.
[A + B for Rosetta Code.
Read two integers and find their sum.
Read two integers and find their sum.
Line 2,369: Line 2,516:
P F
P F
-987.123.
-987.123.
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 2,379: Line 2,526:
=={{header|EGL}}==
=={{header|EGL}}==


<syntaxhighlight lang="egl">
<lang EGL>
package programs;
package programs;


Line 2,398: Line 2,545:
end
end
end
end
</syntaxhighlight>
</lang>


=={{header|Eiffel}}==
=={{header|Eiffel}}==
argument(0) contains the path of the executable - thus we start at argument(1)
argument(0) contains the path of the executable - thus we start at argument(1)
<lang eiffel>
<syntaxhighlight lang="eiffel">
class
class
APPLICATION
APPLICATION
Line 2,416: Line 2,563:
end
end
end
end
</syntaxhighlight>
</lang>


Alternatively ...
Alternatively ...
<lang eiffel>
<syntaxhighlight lang="eiffel">
make
make
-- Run application.
-- Run application.
Line 2,440: Line 2,587:
end
end
end
end
</syntaxhighlight>
</lang>


=={{header|Ela}}==
=={{header|Ela}}==
<lang ela>open monad io string list
<syntaxhighlight lang="ela">open monad io string list


a'b() = do
a'b() = do
Line 2,449: Line 2,596:
putStrLn <| show <| sum <| map gread <| string.split " " <| str
putStrLn <| show <| sum <| map gread <| string.split " " <| str


a'b() ::: IO</lang>
a'b() ::: IO</syntaxhighlight>


{{Out}}
{{Out}}
Line 2,456: Line 2,603:


=={{header|Elena}}==
=={{header|Elena}}==
ELENA 5.0 :
ELENA 6.0 :
<lang elena>import extensions;
<syntaxhighlight lang="elena">import extensions;
public program()
public program()
Line 2,465: Line 2,612:
console.loadLine(A,B).printLine(A + B)
console.loadLine(A,B).printLine(A + B)
}</lang>
}</syntaxhighlight>


Or more generic solution:
Or more generic solution:
<lang elena>import system'routines;
<syntaxhighlight lang="elena">import system'routines;
import extensions;
import extensions;


Line 2,475: Line 2,622:
console.printLine(console.readLine()
console.printLine(console.readLine()
.split()
.split()
.selectBy(mssgconst toInt<convertorOp>[1])
.selectBy(mssgconst toInt<intConvertOp>[1])
.summarize())
.summarize())
}</lang>
}</syntaxhighlight>


=={{header|Elixir}}==
=={{header|Elixir}}==
<lang Elixir>IO.gets("Enter two numbers seperated by a space: ")
<syntaxhighlight lang="elixir">IO.gets("Enter two numbers seperated by a space: ")
|> String.split
|> String.split
|> Enum.map(&String.to_integer(&1))
|> Enum.map(&String.to_integer(&1))
|> Enum.sum
|> Enum.sum
|> IO.puts</lang>
|> IO.puts</syntaxhighlight>


=={{header|Elm}}==
=={{header|Elm}}==
<syntaxhighlight lang="elm">
<lang Elm>
--To write this function directly run cmd
--To write this function directly run cmd
--Type elm-repl to start
--Type elm-repl to start
Line 2,499: Line 2,646:
--END
--END


</syntaxhighlight>
</lang>


=={{header|Emacs Lisp}}==
=={{header|Emacs Lisp}}==
<lang lisp>(let* ((input (read-from-minibuffer ""))
<syntaxhighlight lang="lisp">(let* ((input (read-from-minibuffer ""))
(numbers (mapcar #'string-to-number (split-string input)))
(numbers (mapcar #'string-to-number (split-string input)))
(a (car numbers))
(a (car numbers))
(b (cadr numbers)))
(b (cadr numbers)))
(message "%d" (+ a b)))</lang>
(message "%d" (+ a b)))</syntaxhighlight>

=={{header|EMal}}==
<syntaxhighlight lang="emal">
fun main = int by List args
text input = when(args.length == 1, args[0], ask(text, "Enter n integers separated by a space: "))
int sum, count
for each text word in input.split(" ")
word = word.trim()
if word.isEmpty() do continue end # ignore empty words
int nr = int!word # this can raise an exception
if abs(nr) > 1000
Event.error(0, "Integers must be in the interval [-1000, 1000]").raise()
end
sum += nr
++count
end
if count < 2 do Event.error(1, "At least two integers must be provided").raise() end
writeLine("The sum of " + count + " integers is: " + sum)
return 0
end
exit main(Runtime.args)
</syntaxhighlight>
{{out}}
<pre>
emal.exe Org\RosettaCode\Aplusb.emal " 9 8 "
The sum of 2 integers is: 17
</pre>


=={{header|Emojicode}}==
=={{header|Emojicode}}==
<lang Emojicode>🏁🍇
<syntaxhighlight lang="emojicode">🏁🍇
🆕🔡▶️👂🏼❗️ ➡️ input 💭 Get numbers as input string
🆕🔡▶️👂🏼❗️ ➡️ input 💭 Get numbers as input string
🔫 input 🔤 🔤❗ ➡️ nums 💭 Split numbers by space
🔫 input 🔤 🔤❗ ➡️ nums 💭 Split numbers by space
Line 2,515: Line 2,689:
🍺🔢 🐽 nums 1❗ 10❗ ➡️ B 💭 Retrieve second number
🍺🔢 🐽 nums 1❗ 10❗ ➡️ B 💭 Retrieve second number
😀 🔤🧲A➕B🧲🔤 ❗ 💭 Output sum
😀 🔤🧲A➕B🧲🔤 ❗ 💭 Output sum
🍉️</lang>
🍉️</syntaxhighlight>


=={{header|Erlang}}==
=={{header|Erlang}}==
<lang erlang>-module(aplusb).
<syntaxhighlight lang="erlang">-module(aplusb).
-export([start/0]).
-export([start/0]).


Line 2,527: Line 2,701:
io:format("~w~n",[A+B]),
io:format("~w~n",[A+B]),
start()
start()
end.</lang>
end.</syntaxhighlight>


=={{header|ERRE}}==
=={{header|ERRE}}==
<syntaxhighlight lang="erre">
<lang ERRE>
PROGRAM SUM2
PROGRAM SUM2


Line 2,543: Line 2,717:


END PROGRAM
END PROGRAM
</syntaxhighlight>
</lang>

=={{header|Euler}}==
'''begin'''
'''out''' '''in''' + '''in'''
'''end''' $


=={{header|Euler Math Toolbox}}==
=={{header|Euler Math Toolbox}}==


<syntaxhighlight lang="euler math toolbox">
<lang Euler Math Toolbox>
>s=lineinput("Two numbers seperated by a blank");
>s=lineinput("Two numbers seperated by a blank");
Two numbers seperated by a blank? >4 5
Two numbers seperated by a blank? >4 5
Line 2,555: Line 2,734:
>vs[1]()+vs[2]()
>vs[1]()+vs[2]()
9
9
</syntaxhighlight>
</lang>


=={{header|Euphoria}}==
=={{header|Euphoria}}==
<lang euphoria>include get.e
<syntaxhighlight lang="euphoria">include get.e


function snd(sequence s)
function snd(sequence s)
Line 2,569: Line 2,748:
b = snd(get(0))
b = snd(get(0))


printf(1," %d\n",a+b)</lang>
printf(1," %d\n",a+b)</syntaxhighlight>


=={{header|Excel}}==
=={{header|Excel}}==
Take any 3 columns of any row or rows. Let's say A1,B1 and C1 are taken. In C1 type in :
Take any 3 columns of any row or rows. Let's say A1,B1 and C1 are taken. In C1 type in :


<lang excel>
<syntaxhighlight lang="excel">
=A1+B1
=A1+B1
</syntaxhighlight>
</lang>


The value of C1 will change as the values of A1 and B1 are changed
The value of C1 will change as the values of A1 and B1 are changed


<lang>1 2 3
<syntaxhighlight lang="text">1 2 3
</syntaxhighlight>
</lang>


=={{header|F Sharp|F#}}==
=={{header|F Sharp|F#}}==
<lang fsharp>open System
<syntaxhighlight lang="fsharp">open System


let SumOf(str : string) =
let SumOf(str : string) =
Line 2,592: Line 2,771:
let main argv =
let main argv =
Console.WriteLine(SumOf(Console.ReadLine()))
Console.WriteLine(SumOf(Console.ReadLine()))
0</lang>
0</syntaxhighlight>


=={{header|Factor}}==
=={{header|Factor}}==
<lang factor>USING: math.parser splitting ;
<syntaxhighlight lang="factor">USING: math.parser splitting ;
: a+b ( -- )
: a+b ( -- )
readln " " split1
readln " " split1
[ string>number ] bi@ +
[ string>number ] bi@ +
number>string print ;</lang>
number>string print ;</syntaxhighlight>
<pre>
<pre>
( scratchpad ) a+b
( scratchpad ) a+b
Line 2,607: Line 2,786:


=={{header|FALSE}}==
=={{header|FALSE}}==
<lang false>[0[^$$'9>'0@>|~]['0-\10*+]#%]n: {read an integer}
<syntaxhighlight lang="false">[0[^$$'9>'0@>|~]['0-\10*+]#%]n: {read an integer}
n;!n;!+.</lang>
n;!n;!+.</syntaxhighlight>


=={{header|Fantom}}==
=={{header|Fantom}}==
<lang fantom>class APlusB
<syntaxhighlight lang="fantom">class APlusB
{
{
public static Void main ()
public static Void main ()
Line 2,621: Line 2,800:
echo (sum)
echo (sum)
}
}
}</lang>
}</syntaxhighlight>


=={{header|FBSL}}==
=={{header|FBSL}}==
Using stdin and stdout
Using stdin and stdout
<lang qbasic>#APPTYPE CONSOLE
<syntaxhighlight lang="qbasic">#APPTYPE CONSOLE


DIM %a, %b
DIM %a, %b
Line 2,631: Line 2,810:
PRINT a, "+", b, "=", a + b
PRINT a, "+", b, "=", a + b


PAUSE</lang>
PAUSE</syntaxhighlight>

=={{header|Fennel}}==
{{trans|Lua}}
<syntaxhighlight lang="fennel">
(let [(a b) (io.read :*number :*number)]
(print (+ a b)))
</syntaxhighlight>


=={{header|Fhidwfe}}==
=={{header|Fhidwfe}}==
<syntaxhighlight lang="fhidwfe">
<lang Fhidwfe>
function listint scanint (num:ptr) {// as of writing, fhidwfe has no builtin int scanning
function listint scanint (num:ptr) {// as of writing, fhidwfe has no builtin int scanning
reset negative
reset negative
Line 2,676: Line 2,862:
puti$ + access_word$ inp 0u access_word$ inp 1u
puti$ + access_word$ inp 0u access_word$ inp 1u
free$ inp
free$ inp
</syntaxhighlight>
</lang>


=={{header|Fish}}==
=={{header|Fish}}==
<lang Fish>i:o:"-"=?v1$68*-v
<syntaxhighlight lang="fish">i:o:"-"=?v1$68*-v
v >~01-0 >
v >~01-0 >
>i:o:" "=?v68*-$a*+
>i:o:" "=?v68*-$a*+
Line 2,685: Line 2,871:
v >~01-0 >
v >~01-0 >
>i:o:d=?v68*-$a*+
>i:o:d=?v68*-$a*+
>~*+aonao;</lang>
>~*+aonao;</syntaxhighlight>


=={{header|Forth}}==
=={{header|Forth}}==
<lang Forth>pad dup 80 accept evaluate + .</lang>
<syntaxhighlight lang="forth">pad dup 80 accept evaluate + .</syntaxhighlight>


=={{header|Fortran}}==
=={{header|Fortran}}==
<lang fortran>program a_plus_b
<syntaxhighlight lang="fortran">program a_plus_b
implicit none
implicit none
integer :: a,b
integer :: a,b
read (*, *) a, b
read (*, *) a, b
write (*, '(i0)') a + b
write (*, '(i0)') a + b
end program a_plus_b</lang>
end program a_plus_b</syntaxhighlight>
And in Fortran 77
And in Fortran 77
<lang fortran> READ (1,100) I,J
<syntaxhighlight lang="fortran"> READ (1,100) I,J
100 FORMAT(2I5)
100 FORMAT(2I5)
WRITE (2,200) I+J
WRITE (2,200) I+J
200 FORMAT(1X,I5)
200 FORMAT(1X,I5)
END</lang>
END</syntaxhighlight>


=={{header|Free Pascal}}==
=={{header|Free Pascal}}==
<lang pascal>program SUMA;
<syntaxhighlight lang="pascal">program SUMA;
uses
uses
SysUtils;
SysUtils;
Line 2,715: Line 2,901:
WriteLn(IntToStr(s1 + s2));
WriteLn(IntToStr(s1 + s2));
end.
end.
</syntaxhighlight>
</lang>




=={{header|Frink}}==
=={{header|Frink}}==
This program handles arbitrarily-large integers, or even floating-point or rational numbers or complex numbers (as long as they're not internally separated with spaces, of course, which are the delimiters for this task.) It can even handle units of measure (with no embedded spaces) such as "3.3meter 2feet" and does the right thing when summing those units. It can handle any number of arbitrary whitespace characters separating the numbers. It also works whether the input is user-interactive, or input comes from stdin or a pipe. (It will bring up a user dialog for input when run in a graphical environment.)
This program handles arbitrarily-large integers, or even floating-point or rational numbers or complex numbers (as long as they're not internally separated with spaces, of course, which are the delimiters for this task.) It can even handle units of measure (with no embedded spaces) such as "3.3meter 2feet" and does the right thing when summing those units. It can handle any number of arbitrary whitespace characters separating the numbers. It also works whether the input is user-interactive, or input comes from stdin or a pipe. (It will bring up a user dialog for input when run in a graphical environment.)
<lang frink>
<syntaxhighlight lang="frink">
sum[eval[split[%r/\s+/, input[""]]]]
sum[eval[split[%r/\s+/, input[""]]]]
</syntaxhighlight>
</lang>


=={{header|FunL}}==
=={{header|FunL}}==
<lang funl>println( sum(map(int, readLine().split(' +'))) )</lang>
<syntaxhighlight lang="funl">println( sum(map(int, readLine().split(' +'))) )</syntaxhighlight>


=={{header|Furor}}==
=={{header|Furor}}==
<syntaxhighlight lang="furor">
<lang Furor>
cin sto mystring
cin sto mystring
#s dec mystring @mystring sprintnl
#s dec mystring @mystring sprintnl
Line 2,746: Line 2,932:
{ „mylist” }
{ „mylist” }
{ „nums” }
{ „nums” }
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 2,768: Line 2,954:
</pre>
</pre>







=={{header|FutureBasic}}==
The input statement was removed from FB several years ago. However, it's trivial to write our own input field which compiles as a stand-alone Macintosh application.
<syntaxhighlight lang="futurebasic">
_window = 1
begin enum 1
_label
_input
_result
end enum

void local fn BuildWindow
window _window, @"A + B", ( 0, 0, 260, 200 )
textlabel _label, @"Enter two signed integers separated by a comma, space/s or plus sign. Enter return to calculate.", ( 20, 130, 220, 48 ), _window
textfield _input,,,( 20, 90, 220, 24 ), _window
TextFieldSetMaximumNumberOfLines( _input, 1 )
ControlSetFormat( _input, @"0123456789 ,+-", YES, 0, NULL )
ControlSetAlignment( _input, NSTextAlignmentCenter )
textlabel _result,, ( 20, 50, 220, 24 ), _window
ControlSetAlignment( _result, NSTextAlignmentRight )
WindowMakeFirstResponder( _window, _input )
end fn

local fn DoCalc
NSInteger value1, value2
CFStringRef calcStr = fn ControlStringValue( _input )
calcStr = fn StringByReplacingOccurrencesOfString( calcStr, @",", @"\t" )
calcStr = fn StringByReplacingOccurrencesOfString( calcStr, @"+", @"\t" )
calcStr = fn StringByReplacingOccurrencesOfString( calcStr, @" ", @"\t" )
CFArrayRef calcArr = fn StringComponentsSeparatedByString( calcStr, @"\t" )
value1 = fn StringIntegerValue( fn ArrayFirstObject( calcArr ) )
value2 = fn StringIntegerValue( fn ArrayLastObject( calcArr ) )
ControlSetStringValue( _result, fn StringWithFormat( @"%ld + %ld = %ld", value1, value2, value1 + value2 ) )
end fn

void local fn DoDialog( ev as long, tag as long, wnd as long )
select ( ev )
case _textFieldDidEndEditing : fn DoCalc
case _windowWillClose : end
end select
end fn

on dialog fn DoDialog
fn BuildWindow

HandleEvents
</syntaxhighlight>
{{output}}
<pre>
-250 1000 = 750
or
-250,1000 = 750
or
-250 + 1000 = 750
</pre>


=={{header|Gambas}}==
=={{header|Gambas}}==
<lang gambas>Public Sub Main()
<syntaxhighlight lang="gambas">Public Sub Main()
Dim sInput As String = InputBox("Input 2 numbers seperated by a space", "A + B")
Dim sInput As String = InputBox("Input 2 numbers seperated by a space", "A + B")


Print Split(sInput, " ")[0] & " + " & Split(sInput, " ")[1] & " = " & Str(Val(Split(sInput, " ")[0]) + Val(Split(sInput, " ")[1]))
Print Split(sInput, " ")[0] & " + " & Split(sInput, " ")[1] & " = " & Str(Val(Split(sInput, " ")[0]) + Val(Split(sInput, " ")[1]))


End</lang>
End</syntaxhighlight>
Output:
Output:
<pre>
<pre>
Line 2,783: Line 3,028:
=={{header|Gastona}}==
=={{header|Gastona}}==
Taking A and B from command line arguments
Taking A and B from command line arguments
<lang gastona>#listix#
<syntaxhighlight lang="gastona">#listix#


<main>
<main>
"@<p1> + @<p2> = "
"@<p1> + @<p2> = "
=, p1 + p2
=, p1 + p2
</syntaxhighlight>
</lang>
Using Graphical interface
Using Graphical interface
<lang gastona>#javaj#
<syntaxhighlight lang="gastona">#javaj#


<layout of main>
<layout of main>
Line 2,805: Line 3,050:
<suma> =, eA + eB
<suma> =, eA + eB
</syntaxhighlight>
</lang>

=={{header|GDScript}}==
Requires Godot 4. Runs as a tool script using the input and output properties. Does not check for zero lines of input.

<syntaxhighlight lang="gdscript">
@tool
extends Node

@export var input: String:
set(value):
input = value # Save the input field

var fields := value.split(" ", false) # Split by spaces
if len(fields) == 2: # Basic input validation
output = str(int(fields[0]) + int(fields[1]))
else: # Invalid input
output = ""

@export var output: String
</syntaxhighlight>


=={{header|Gema}}==
=={{header|Gema}}==
<lang gema><D> <D>=@add{$1;$2}</lang>
<syntaxhighlight lang="gema"><D> <D>=@add{$1;$2}</syntaxhighlight>


=={{header|Genie}}==
=={{header|Genie}}==
<lang genie>[indent=4]
<syntaxhighlight lang="genie">[indent=4]
/*
/*
A+B in Genie
A+B in Genie
Line 2,833: Line 3,098:
print "B" + warning
print "B" + warning


print "From %s\nA + B = %llu", line, a+b</lang>
print "From %s\nA + B = %llu", line, a+b</syntaxhighlight>


{{out}}
{{out}}
Line 2,853: Line 3,118:


=={{header|GML}}==
=={{header|GML}}==
<lang GML>var add, a, b;
<syntaxhighlight lang="gml">var add, a, b;
add = argument0; // get the string with the numbers to add
add = argument0; // get the string with the numbers to add
a = real(string_copy(add, 1, string_pos(" ", add)));
a = real(string_copy(add, 1, string_pos(" ", add)));
b = real(string_copy(add, string_pos(" ", add) + 1, string_length(add) - string_pos(" ", add)));
b = real(string_copy(add, string_pos(" ", add) + 1, string_length(add) - string_pos(" ", add)));
return(a + b);</lang>
return(a + b);</syntaxhighlight>


=={{header|Go}}==
=={{header|Go}}==
<lang go>package main
<syntaxhighlight lang="go">package main


import "fmt"
import "fmt"
Line 2,868: Line 3,133:
fmt.Scan(&a, &b)
fmt.Scan(&a, &b)
fmt.Println(a + b)
fmt.Println(a + b)
}</lang>
}</syntaxhighlight>


=={{header|Golfscript}}==
=={{header|Golfscript}}==
<lang golfscript>~+</lang>
<syntaxhighlight lang="golfscript">~+</syntaxhighlight>


=={{header|Golo}}==
=={{header|Golo}}==
<lang Golo>#!/usr/bin/env golosh
<syntaxhighlight lang="golo">#!/usr/bin/env golosh
----
----
This module asks for two numbers, adds them, and prints the result.
This module asks for two numbers, adds them, and prints the result.
Line 2,900: Line 3,165:
println("they both need to be numbers for this to work")
println("they both need to be numbers for this to work")
}
}
}</lang>
}</syntaxhighlight>


=={{header|Gosu}}==
=={{header|Gosu}}==
<syntaxhighlight lang="gosu">
<lang Gosu>
uses java.io.InputStreamReader
uses java.io.InputStreamReader
uses java.util.Scanner
uses java.util.Scanner
Line 2,913: Line 3,178:


print( a + b )
print( a + b )
</syntaxhighlight>
</lang>


=={{header|Groovy}}==
=={{header|Groovy}}==
<lang groovy>def abAdder = {
<syntaxhighlight lang="groovy">def abAdder = {
def reader = new Scanner(System.in)
def reader = new Scanner(System.in)
def a = reader.nextInt();
def a = reader.nextInt();
Line 2,923: Line 3,188:
a + b
a + b
}
}
abAdder()</lang>
abAdder()</syntaxhighlight>


=={{header|GUISS}}==
=={{header|GUISS}}==
We cannot use variables, but we can find the sum of two numbers.Here we add 3 + 2:
We cannot use variables, but we can find the sum of two numbers.Here we add 3 + 2:
<lang guiss>Start,Programs,Accessories,Calculator,Button:3,Button:[plus],
<syntaxhighlight lang="guiss">Start,Programs,Accessories,Calculator,Button:3,Button:[plus],
Button:2,Button:[equals]</lang>
Button:2,Button:[equals]</syntaxhighlight>


=={{header|Harbour}}==
=={{header|Harbour}}==
<lang visualfoxpro>PROCEDURE Main()
<syntaxhighlight lang="visualfoxpro">PROCEDURE Main()
LOCAL GetList := {}
LOCAL GetList := {}
LOCAL bValid := { |n| iif(n>-1001, iif(n<1001, .T.,.F.),.F.) }
LOCAL bValid := { |n| iif(n>-1001, iif(n<1001, .T.,.F.),.F.) }
Line 2,944: Line 3,209:


RETURN
RETURN
</lang>
</syntaxhighlight>
Screen output:<p>Enter two numbers (range -1000...+1000): ''-56 98''</p>
Screen output:<p>Enter two numbers (range -1000...+1000): ''-56 98''</p>
<p>Sum of given numbers is 42</p>
<p>Sum of given numbers is 42</p>
Line 2,950: Line 3,215:


=={{header|Haskell}}==
=={{header|Haskell}}==
<lang haskell>main = print . sum . map read . words =<< getLine</lang>
<syntaxhighlight lang="haskell">main = print . sum . map read . words =<< getLine</syntaxhighlight>


=={{header|hexiscript}}==
=={{header|hexiscript}}==
<lang hexiscript>fun split s delim
<syntaxhighlight lang="hexiscript">fun split s delim
let ret dict 32
let ret dict 32
let l len s
let l len s
Line 2,973: Line 3,238:
let a tonum nums[0]
let a tonum nums[0]
let b tonum nums[1]
let b tonum nums[1]
println a + b</lang>
println a + b</syntaxhighlight>


=={{header|HicEst}}==
=={{header|HicEst}}==
A and B are input via edit controls with spinners limiting inputs to +-1000.
A and B are input via edit controls with spinners limiting inputs to +-1000.
<lang HicEst>DLG(Edit=A, DNum, MIn=-1000, MAx=1000, E=B, DN, MI=-1000, MA=1000)
<syntaxhighlight lang="hicest">DLG(Edit=A, DNum, MIn=-1000, MAx=1000, E=B, DN, MI=-1000, MA=1000)
WRITE(Messagebox, Name) A, B, "Sum = ", A+B</lang>
WRITE(Messagebox, Name) A, B, "Sum = ", A+B</syntaxhighlight>


=={{header|Hoon}}==
=={{header|Hoon}}==
<lang>
<syntaxhighlight lang="text">
|= [a=@ud b=@ud] (add a b)
|= [a=@ud b=@ud] (add a b)
</syntaxhighlight>
</lang>


=={{header|Hope}}==
=={{header|Hope}}==
Line 3,001: Line 3,266:


=={{header|Huginn}}==
=={{header|Huginn}}==
<lang huginn>import Algorithms as algo;
<syntaxhighlight lang="huginn">import Algorithms as algo;
import Text as text;
import Text as text;


Line 3,016: Line 3,281:
);
);
);
);
}</lang>
}</syntaxhighlight>


=={{header|Hy}}==
=={{header|Hy}}==
<lang hy>(print (sum (map int (.split (input)))))</lang>
<syntaxhighlight lang="hy">(print (sum (map int (.split (input)))))</syntaxhighlight>
Alternatively, with the "threading tail" macro:
Alternatively, with the "threading tail" macro:
<lang hy>(->> (input) (.split) (map int) (sum) (print))</lang>
<syntaxhighlight lang="hy">(->> (input) (.split) (map int) (sum) (print))</syntaxhighlight>


=={{header|i}}==
=={{header|i}}==
<lang i>main: print(integer(in(' '))+integer(in('\n'))); ignore</lang>
<syntaxhighlight lang="i">main: print(integer(in(' '))+integer(in('\n'))); ignore</syntaxhighlight>


=={{header|Icon}} and {{header|Unicon}}==
=={{header|Icon}} and {{header|Unicon}}==
<lang icon>procedure main()
<syntaxhighlight lang="icon">procedure main()
numChars := '-'++&digits
numChars := '-'++&digits
read() ? {
read() ? {
Line 3,034: Line 3,299:
}
}
write((\A + \B) | "Bad input")
write((\A + \B) | "Bad input")
end</lang>
end</syntaxhighlight>


=={{header|Idris}}==
=={{header|Idris}}==
<lang idris>main : IO()
<syntaxhighlight lang="idris">main : IO()
main = do
main = do
line <- getLine
line <- getLine
print $ sum $ map cast $ words line</lang>
print $ sum $ map cast $ words line</syntaxhighlight>

=={{header|Insitux}}==
<syntaxhighlight lang="insitux">(+ (to-num (prompt "Enter first number: "))
(to-num (prompt "Enter second number: ")))</syntaxhighlight>


=={{header|J}}==
=={{header|J}}==
Typically, in J, you would find the sum of two numbers (let us say 2 and 3) by entering both of them on a line with a + sign between them:
Typically, in J, you would find the sum of two numbers (let us say 2 and 3) by entering both of them on a line with a + sign between them:
<lang J> 2+3
<syntaxhighlight lang="j"> 2+3
5</lang>
5</syntaxhighlight>
Next we describe then implement a command line program to add some numbers.
In the following expression, <tt>1!:1(3)</tt> reads a line from STDIN; <tt>-.LF</tt> drops the line ending character; <tt>".</tt> converts the remaining text to a sequence of numbers which are then summed using <tt>+/</tt>.

<lang J>+/". (1!:1(3))-.LF</lang>
1) In the following expression, <tt>1!:1(3)</tt> reads a line from STDIN; <tt>-.LF</tt> drops the line ending character; <tt>".</tt> converts the remaining text to a sequence of numbers which are then summed using <tt>+/</tt>.
Here's a little script, called "a+b.ijs":
<syntaxhighlight lang="j">+/". (1!:1(3))-.LF</syntaxhighlight>
<lang J>#!/Applications/j602/bin/jconsole
2) Here's a little script, called "a+b.ijs":
<syntaxhighlight lang="j">#!/usr/bin/ijconsole
echo +/". (1!:1(3))-.LF
echo +/". (1!:1(3))-.LF
exit ''</lang>
exit ''</syntaxhighlight>
Here is the execution of the script:
3) Here is an execution of the script:
<lang bash>echo 2 3 | ./a+b.ijs
<syntaxhighlight lang="bash">echo 2 3 | ./a+b.ijs
5</lang>
5</syntaxhighlight>

Note: under OSX, you should probably install a symbolic link at /usr/bin/ijconsole which links to something like /Applications/j602/bin/jconsole.


=={{header|Java}}==
=={{header|Java}}==
The task description is somewhat vague, if the 'input stream' is in reference to the data provided at the command line, then Java will parse these values into a <code>String</code> array, accessible via the <kbd>args</kbd> parameter of the <code>main</code> method.
<lang java>import java.util.Scanner;
<syntaxhighlight lang="java">
public static void main(String[] args) {
int A = Integer.parseInt(args[0]);
int B = Integer.parseInt(args[1]);
System.out.println(A + B);
}
</syntaxhighlight>
If the 'input stream' is the standard-in, you can use the following.<br />
The <code>Scanner</code> class can be used to "scan" the standard-in stream from left to right, returning the next value requested.
<syntaxhighlight lang="java">
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int A = scanner.nextInt();
int B = scanner.nextInt();
System.out.println(A + B);
}
</syntaxhighlight>
If the 'input stream' is referring to any abstraction, then you can use the following.<br />
In this example, the data is considered to be under a specific charset, so the integer values are parsed using UTF-8.
<syntaxhighlight lang="java">
import static java.nio.charset.StandardCharsets.UTF_8;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
</syntaxhighlight>
<syntaxhighlight lang="java">
int sum(InputStream input) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
String line = reader.readLine();
reader.close();
/* split parameter here is a regex */
String[] values = line.split(" +");
int A = Integer.parseInt(values[0]);
int B = Integer.parseInt(values[1]);
return A + B;
}
</syntaxhighlight>
<br />
An alternate implemenation
<syntaxhighlight lang="java">import java.util.Scanner;


public class Sum2 {
public class Sum2 {
Line 3,064: Line 3,380:
System.out.println(in.nextInt() + in.nextInt()); // Standard output
System.out.println(in.nextInt() + in.nextInt()); // Standard output
}
}
}</lang>
}</syntaxhighlight>
Object of [[class]] Scanner works slow enough, because of that contestants prefer to avoid its use. Often, longer solution works faster and easily scales to problems.
Object of [[class]] Scanner works slow enough, because of that contestants prefer to avoid its use. Often, longer solution works faster and easily scales to problems.
<lang java>import java.io.*;
<syntaxhighlight lang="java">import java.io.*;
import java.util.*;
import java.util.*;


Line 3,092: Line 3,408:
out.println(nextInt() + nextInt());
out.println(nextInt() + nextInt());
}
}
}</lang>
}</syntaxhighlight>


The following code uses a StreamTokenizer instead of a Scanner.
The following code uses a StreamTokenizer instead of a Scanner.


<lang java>import java.io.*;
<syntaxhighlight lang="java">import java.io.*;
import java.nio.charset.Charset;
import java.nio.charset.Charset;


Line 3,112: Line 3,428:
}
}
}
}
</syntaxhighlight>
</lang>




<lang>
<syntaxhighlight lang="text">
grammar aplusb ;
grammar aplusb ;


Line 3,130: Line 3,446:
NEWLINE : WS* '\r'? '\n'
NEWLINE : WS* '\r'? '\n'
;
;
</syntaxhighlight>
</lang>
Produces:
Produces:
<pre>
<pre>
Line 3,151: Line 3,467:
Client side:
Client side:


<lang html4strict><html>
<syntaxhighlight lang="html4strict"><html>
<body>
<body>
<div id='input'></div>
<div id='input'></div>
Line 3,164: Line 3,480:
</script>
</script>
</body>
</body>
</html></lang>
</html></syntaxhighlight>


Server side (with [http://nodejs.org node.js]):
Server side (with [http://nodejs.org node.js]):


<lang javascript>process.openStdin().on (
<syntaxhighlight lang="javascript">process.openStdin().on (
'data',
'data',
function (line) {
function (line) {
Line 3,177: Line 3,493:
process.exit()
process.exit()
}
}
)</lang>
)</syntaxhighlight>


$ node io.js
$ node io.js
Line 3,188: Line 3,504:
=== ES6 ===
=== ES6 ===
Node.js in a terminal:
Node.js in a terminal:
<lang javascript>process.stdin.on("data", buffer => {
<syntaxhighlight lang="javascript">process.stdin.on("data", buffer => {
console.log(
console.log(
(buffer + "").trim().split(" ").map(Number).reduce((a, v) => a + v, 0)
(buffer + "").trim().split(" ").map(Number).reduce((a, v) => a + v, 0)
);
);
});
});
</syntaxhighlight>
</lang>


<pre> $ node io.js
<pre> $ node io.js
Line 3,201: Line 3,517:


=== JScript Windows Script Host Version 5.8 ===
=== JScript Windows Script Host Version 5.8 ===
<lang javascript>var a = WScript.StdIn.ReadLine();
<syntaxhighlight lang="javascript">var a = WScript.StdIn.ReadLine();
var b = WScript.StdIn.ReadLine();
var b = WScript.StdIn.ReadLine();
WSH.echo(a, " + " , b , " = " , Number(a)+Number(b));
WSH.echo(a, " + " , b , " = " , Number(a)+Number(b));
</syntaxhighlight>
</lang>


=={{header|Joy}}==
=={{header|Joy}}==
===Console===
===Console===
<lang Joy>get get +.</lang>
<syntaxhighlight lang="joy">get get +.</syntaxhighlight>
===File===
===File===
<lang Joy>"input.txt" include
<syntaxhighlight lang="joy">"input.txt" include
"output.txt" "w" fopen
"output.txt" "w" fopen
get get + fput pop quit.</lang>
get get + fput pop quit.</syntaxhighlight>


=={{header|jq}}==
=={{header|jq}}==
Since the given task is simply to add two numbers, the simplest approach in jq is illustrated by the following transcript:
Since the given task is simply to add two numbers, the simplest approach in jq is illustrated by the following transcript:
<lang jq>$ jq -s add
<syntaxhighlight lang="jq">$ jq -s add
3 2
3 2
5 </lang>
5 </syntaxhighlight>
This will work provided the numbers are neither too small nor too large. However, the above program will add **all** the numbers presented on the stream (assuming only numbers are presented). If the task were to add consecutive pairs of numbers, then the approach illustrated in the following transcript can be used, in conjunction with the jq "-s" option:<lang jq>
This will work provided the numbers are neither too small nor too large. However, the above program will add **all** the numbers presented on the stream (assuming only numbers are presented). If the task were to add consecutive pairs of numbers, then the approach illustrated in the following transcript can be used, in conjunction with the jq "-s" option:<syntaxhighlight lang="jq">
def addpairs:
def addpairs:
if length < 2 then empty
if length < 2 then empty
Line 3,225: Line 3,541:
end;
end;


addpairs</lang>
addpairs</syntaxhighlight>
For example, here is a transcript that assumes the program is in a file named AB.jq:<lang jq>
For example, here is a transcript that assumes the program is in a file named AB.jq:<syntaxhighlight lang="jq">
$ jq -s -f AB.jq
$ jq -s -f AB.jq
1 2 3 4 5 6
1 2 3 4 5 6
3
3
7
7
11</lang>
11</syntaxhighlight>


=={{header|Jsish}}==
=={{header|Jsish}}==
<lang javascript>/* A+B in Jsish */
<syntaxhighlight lang="javascript">/* A+B in Jsish */
var line = console.input();
var line = console.input();
var nums = line.match(/^\s*([+-]?[0-9]+)\s+([+-]?[0-9]+)\s*/);
var nums = line.match(/^\s*([+-]?[0-9]+)\s+([+-]?[0-9]+)\s*/);
Line 3,247: Line 3,563:
} else {
} else {
puts("error: A+B requires two numbers separated by space");
puts("error: A+B requires two numbers separated by space");
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 3,265: Line 3,581:
=={{header|Julia}}==
=={{header|Julia}}==
Run from the command line:
Run from the command line:
<lang julia>input = parse.(Int, split(readline(stdin)))
<syntaxhighlight lang="julia">input = parse.(Int, split(readline(stdin)))
println(stdout, sum(input))</lang>
println(stdout, sum(input))</syntaxhighlight>


{{out}}
{{out}}
Line 3,274: Line 3,590:


In the next solution, an error is returned if the entry is not constituted from exactly two integers. Any number of spaces can follow an integer.
In the next solution, an error is returned if the entry is not constituted from exactly two integers. Any number of spaces can follow an integer.
<lang Julia>julia> println(parse(Int, readuntil(stdin, ' ')) + parse(Int, readuntil(stdin, '\n')))
<syntaxhighlight lang="julia">julia> println(parse(Int, readuntil(stdin, ' ')) + parse(Int, readuntil(stdin, '\n')))
1 2
1 2
3</lang>
3</syntaxhighlight>


=={{header|K}}==
=={{header|K}}==
<syntaxhighlight lang="k">
<lang K>
split:{(a@&~&/' y=/: a:(0,&x=y)_ x) _dv\: y}
split:{(a@&~&/' y=/: a:(0,&x=y)_ x) _dv\: y}
ab:{+/0$split[0:`;" "]}
ab:{+/0$split[0:`;" "]}
Line 3,285: Line 3,601:
2 3
2 3
5
5
</syntaxhighlight>
</lang>


=={{header|Keg}}==
=={{header|Keg}}==
<lang Keg>+.</lang>
<syntaxhighlight lang="keg">+.</syntaxhighlight>
[https://tio.run/##y05N//9fW@//f1MDLjMDAA Try it online!]
[https://tio.run/##y05N//9fW@//f1MDLjMDAA Try it online!]


Or, using flags (<code>-hr</code>):
Or, using flags (<code>-hr</code>):
<lang Keg>+</lang>
<syntaxhighlight lang="keg">+</syntaxhighlight>
[https://tio.run/##y05N//9f@/9/UwMuM4P/uhlFAA Try it online!]
[https://tio.run/##y05N//9f@/9/UwMuM4P/uhlFAA Try it online!]


=={{header|Kite}}==
=={{header|Kite}}==
<lang Kite>#!/usr/bin/kite
<syntaxhighlight lang="kite">#!/usr/bin/kite


import "System.file";
import "System.file";
Line 3,308: Line 3,624:


line = in|readline;
line = in|readline;
];</lang>
];</syntaxhighlight>
{{Out}}
{{Out}}
<pre>
<pre>
Line 3,318: Line 3,634:


=={{header|Klong}}==
=={{header|Klong}}==
<syntaxhighlight lang="k">
<lang K>
{(1:$(*x?0c )#x)+1:$(1+*|x?0c )_x}@.rl()
{(1:$(*x?0c )#x)+1:$(1+*|x?0c )_x}@.rl()
2 3
2 3
5
5
</syntaxhighlight>
</lang>


=={{header|Kotlin}}==
=={{header|Kotlin}}==
<lang scala>// version 1.0.5-2
<syntaxhighlight lang="scala">// version 1.0.5-2


fun main(args: Array<String>) {
fun main(args: Array<String>) {
Line 3,347: Line 3,663:
}
}
}
}
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 3,361: Line 3,677:


=={{header|KQL}}==
=={{header|KQL}}==
<lang KQL>datatable(Input:string)[
<syntaxhighlight lang="kql">datatable(Input:string)[
'2 2',
'2 2',
'3 2'
'3 2'
]
]
| parse Input with A:int ' ' B:int
| parse Input with A:int ' ' B:int
| project Input, Output = A + B</lang>
| project Input, Output = A + B</syntaxhighlight>


=={{header|L++}}==
=={{header|L++}}==
<lang lisp>(main
<syntaxhighlight lang="lisp">(main
(decl int a)
(decl int a)
(decl int b)
(decl int b)
(>> std::cin a b)
(>> std::cin a b)
(prn (+ a b)))</lang>
(prn (+ a b)))</syntaxhighlight>


=={{header|Lambdatalk}}==
=={{header|Lambdatalk}}==
<lang scheme>
<syntaxhighlight lang="scheme">
Lambdatalk works in a wiki, lambdatank.
Lambdatalk works in a wiki, lambdatank.


Line 3,408: Line 3,724:
Several boxes can be created in the wiki page
Several boxes can be created in the wiki page
with any valid lambdatalk expressions.
with any valid lambdatalk expressions.
</syntaxhighlight>
</lang>

=={{header|Lang}}==
<syntaxhighlight lang="lang">
fn.print(First number:\s)
$a = fn.int(fn.input())

fn.print(Second number:\s)
$b = fn.int(fn.input())

fn.println(Result: parser.op($a + $b))
</syntaxhighlight>


=={{header|Lang5}}==
=={{header|Lang5}}==
<lang lang5>read read + .
<syntaxhighlight lang="lang5">read read + .


read " " split expand drop + .</lang>
read " " split expand drop + .</syntaxhighlight>


=={{header|Lasso}}==
=={{header|Lasso}}==
<lang lb>[a + b]</lang>
<syntaxhighlight lang="lb">[a + b]</syntaxhighlight>


=={{header|LIL}}==
=={{header|LIL}}==
<lang tcl># A+B, in LIL
<syntaxhighlight lang="tcl"># A+B, in LIL
# Requires lil shell readline routine
# Requires lil shell readline routine
set in [readline]
set in [readline]
Line 3,426: Line 3,753:
if [expr $A < -1000 || $A > 1000] { print "A out of range: $A"; exit 1 }
if [expr $A < -1000 || $A > 1000] { print "A out of range: $A"; exit 1 }
if [expr $B < -1000 || $B > 1000] { print "B out of range: $B"; exit 1 }
if [expr $B < -1000 || $B > 1000] { print "B out of range: $B"; exit 1 }
print [expr $A + $B]</lang>
print [expr $A + $B]</syntaxhighlight>


{{out}}
{{out}}
Line 3,433: Line 3,760:


=={{header|Lisaac}}==
=={{header|Lisaac}}==
<lang lisaac>Section Header
<syntaxhighlight lang="lisaac">Section Header
+ name := A_PLUS_B
+ name := A_PLUS_B


Section Public
Section Public
- main <- ( (IO.read_integer; IO.last_integer) +
- main <- ( (IO.read_integer; IO.last_integer) +
(IO.read_integer; IO.last_integer) ).println;</lang>
(IO.read_integer; IO.last_integer) ).println;</syntaxhighlight>


=={{header|Little}}==
=={{header|Little}}==
<lang c>void main() {
<syntaxhighlight lang="c">void main() {
string a, b;
string a, b;
scan(gets(stdin), "%d %d", &a, &b);
scan(gets(stdin), "%d %d", &a, &b);
puts(((int)a + (int)b));
puts(((int)a + (int)b));
}</lang>
}</syntaxhighlight>


=={{header|Little Man Computer}}==
=={{header|Little Man Computer}}==
Line 3,453: Line 3,780:


'''Assembly'''
'''Assembly'''
<lang Little Man Computer> INP
<syntaxhighlight lang="little man computer"> INP
STA 99
STA 99
INP
INP
Line 3,459: Line 3,786:
OUT
OUT
HLT
HLT
// Output the sum of two numbers</lang>
// Output the sum of two numbers</syntaxhighlight>


'''Machine code'''
'''Machine code'''
<lang Little Man Computer>00 INP
<syntaxhighlight lang="little man computer">00 INP
01 STA 99
01 STA 99
02 INP
02 INP
03 ADD 99
03 ADD 99
04 OUT
04 OUT
05 HLT</lang>
05 HLT</syntaxhighlight>


=={{header|LiveCode}}==
=={{header|LiveCode}}==
Using Livecode Server script
Using Livecode Server script
<syntaxhighlight lang="livecode"><?lc
<lang LiveCode><?lc
if isNumber($0) and isNumber($1) then
if isNumber($0) and isNumber($1) then
put $0 + $1
put $0 + $1
Line 3,477: Line 3,804:
put $0 && $1
put $0 && $1
end if
end if
?></lang>
?></syntaxhighlight>


A graphical version using an input dialog
A graphical version using an input dialog
<lang LiveCode>on mouseUp
<syntaxhighlight lang="livecode">on mouseUp
ask "Enter two numbers"
ask "Enter two numbers"
set itemdelimiter to space
set itemdelimiter to space
Line 3,489: Line 3,816:
answer item 1 of nums && item 2 of nums
answer item 1 of nums && item 2 of nums
end if
end if
end mouseUp</lang>
end mouseUp</syntaxhighlight>


=={{header|Logo}}==
=={{header|Logo}}==
<lang logo>show apply "sum readlist</lang>
<syntaxhighlight lang="logo">show apply "sum readlist</syntaxhighlight>


=={{header|Lua}}==
=={{header|Lua}}==
<lang Lua>a,b = io.read("*number", "*number")
<syntaxhighlight lang="lua">a,b = io.read("*number", "*number")
print(a+b)</lang>
print(a+b)</syntaxhighlight>


=={{header|M2000 Interpreter}}==
=={{header|M2000 Interpreter}}==
<lang>Def Range(X%)=Abs(X%)<=1000
<syntaxhighlight lang="text">Def Range(X%)=Abs(X%)<=1000
Do {
Do {
Input A%, B%
Input A%, B%
} Until Range(A%) And Range(B%)
} Until Range(A%) And Range(B%)
Print A%+B%</lang>
Print A%+B%</syntaxhighlight>


=={{header|M4}}==
=={{header|M4}}==
<lang M4> define(`sumstr', `eval(patsubst(`$1',` ',`+'))')
<syntaxhighlight lang="m4"> define(`sumstr', `eval(patsubst(`$1',` ',`+'))')


sumstr(1 2)
sumstr(1 2)
3</lang>
3</syntaxhighlight>


=={{header|Maple}}==
=={{header|Maple}}==
<lang maple> convert( scanf( "%d %d" ), '`+`' );
<syntaxhighlight lang="maple"> convert( scanf( "%d %d" ), '`+`' );
23 34
23 34
57</lang>
57</syntaxhighlight>


=={{header|Mathematica}}/{{header|Wolfram Language}}==
=={{header|Mathematica}}/{{header|Wolfram Language}}==
Interactive in a notebook
Interactive in a notebook
<lang Mathematica>Input[] + Input[]</lang>
<syntaxhighlight lang="mathematica">Input[] + Input[]</syntaxhighlight>


=={{header|MATLAB}} / {{header|Octave}}==
=={{header|MATLAB}} / {{header|Octave}}==
<lang MATLAB>function sumOfInputs = APlusB()
<syntaxhighlight lang="matlab">function sumOfInputs = APlusB()
inputStream = input('Enter two numbers, separated by a space: ', 's');
inputStream = input('Enter two numbers, separated by a space: ', 's');
numbers = str2num(inputStream); %#ok<ST2NM>
numbers = str2num(inputStream); %#ok<ST2NM>
Line 3,528: Line 3,855:
end
end
sumOfInputs = sum(numbers);
sumOfInputs = sum(numbers);
end</lang>
end</syntaxhighlight>


=={{header|Maude}}==
=={{header|Maude}}==
===Built-in===
===Built-in===
<syntaxhighlight lang="maude">
<lang Maude>
red 3 + 4 .
red 3 + 4 .
</syntaxhighlight>
</lang>
===With restrictions===
===With restrictions===
<syntaxhighlight lang="maude">
<lang Maude>
fmod ADD is
fmod ADD is


Line 3,549: Line 3,876:
endfm
endfm
</syntaxhighlight>
</lang>


=={{header|Maxima}}==
=={{header|Maxima}}==
<lang>in_stream: openr("/dev/stdin");
<syntaxhighlight lang="text">in_stream: openr("/dev/stdin");
unless (line: readline(in_stream), line=false) do (
unless (line: readline(in_stream), line=false) do (
q: map('parse_string, split(line, " ")),
q: map('parse_string, split(line, " ")),
Line 3,558: Line 3,885:
);
);
close(in_stream);
close(in_stream);
</syntaxhighlight>
</lang>


=={{header|Mercury}}==
=={{header|Mercury}}==
<lang>:- module a_plus_b.
<syntaxhighlight lang="text">:- module a_plus_b.
:- interface.
:- interface.


Line 3,580: Line 3,907:
else
else
true
true
).</lang>
).</syntaxhighlight>


=={{header|min}}==
=={{header|min}}==
{{works with|min|0.19.3}}
{{works with|min|0.19.3}}
<lang min>gets " " split 'bool filter 'int map sum puts!</lang>
<syntaxhighlight lang="min">gets " " split 'bool filter 'int map sum puts!</syntaxhighlight>


=={{header|MiniScript}}==
=={{header|MiniScript}}==
The <code>input</code> intrinsic in MiniScript isn't available in all implementations, so we've just hard-coded the input here:
The <code>input</code> intrinsic in MiniScript isn't available in all implementations, so we've just hard-coded the input here:
<lang MiniScript>s = " 2 3 "
<syntaxhighlight lang="miniscript">s = " 2 3 "
fields = s.split
fields = s.split
for i in range(fields.len-1, 0)
for i in range(fields.len-1, 0)
Line 3,597: Line 3,924:
else
else
print val(fields[0]) + val(fields[1])
print val(fields[0]) + val(fields[1])
end if</lang>
end if</syntaxhighlight>


{{out}}
{{out}}
Line 3,603: Line 3,930:


=={{header|mIRC Scripting Language}}==
=={{header|mIRC Scripting Language}}==
<lang mirc>alias a+b {
<syntaxhighlight lang="mirc">alias a+b {
echo -ag $calc($1 + $2)
echo -ag $calc($1 + $2)
}</lang>
}</syntaxhighlight>


=={{header|МК-61/52}}==
=={{header|МК-61/52}}==
Line 3,614: Line 3,941:
=={{header|ML/I}}==
=={{header|ML/I}}==
The two numbers are read from 'standard input' or its equivalent.
The two numbers are read from 'standard input' or its equivalent.
<lang ML/I>MCSKIP "WITH" NL
<syntaxhighlight lang="ml/i">MCSKIP "WITH" NL
"" A+B
"" A+B
"" assumes macros on input stream 1, terminal on stream 2
"" assumes macros on input stream 1, terminal on stream 2
Line 3,626: Line 3,953:
MCSKIP SL WITH *
MCSKIP SL WITH *
MCSET S1=1
MCSET S1=1
*MCSET S10=2</lang>
*MCSET S10=2</syntaxhighlight>


=={{header|Modula-2}}==
=={{header|Modula-2}}==
<lang modula2>MODULE ab;
<syntaxhighlight lang="modula2">MODULE ab;


IMPORT InOut;
IMPORT InOut;
Line 3,640: Line 3,967:
InOut.WriteInt (A + B, 8);
InOut.WriteInt (A + B, 8);
InOut.WriteLn
InOut.WriteLn
END ab.</lang>
END ab.</syntaxhighlight>


=={{header|Modula-3}}==
=={{header|Modula-3}}==
<lang modula3>MODULE Ab EXPORTS Main;
<syntaxhighlight lang="modula3">MODULE Ab EXPORTS Main;


IMPORT IO;
IMPORT IO;
Line 3,658: Line 3,985:
IO.PutInt(A+B);
IO.PutInt(A+B);
IO.Put("\n");
IO.Put("\n");
END Ab.</lang>
END Ab.</syntaxhighlight>


=={{header|MoonScript}}==
=={{header|MoonScript}}==
<lang moonscript>a,b = io.read '*number','*number'
<syntaxhighlight lang="moonscript">a,b = io.read '*number','*number'
print a + b</lang>
print a + b</syntaxhighlight>

=={{header|Mosaic}}==
<syntaxhighlight lang="mosaic">
proc main =
int a, b

print "?"
readln a, b
println a + b
end
</syntaxhighlight>


=={{header|MUMPS}}==
=={{header|MUMPS}}==
<syntaxhighlight lang="mumps">ANB
<lang MUMPS>ANB
NEW A,B,T,S
NEW A,B,T,S
READ !,"Input two integers between -1000 and 1000, separated by a space: ",S
READ !,"Input two integers between -1000 and 1000, separated by a space: ",S
Line 3,672: Line 4,010:
IF T WRITE !,(A+B)
IF T WRITE !,(A+B)
IF 'T WRITE !,"Bad input"
IF 'T WRITE !,"Bad input"
QUIT</lang>
QUIT</syntaxhighlight>


=={{header|Nanoquery}}==
=={{header|Nanoquery}}==
<lang Nanoquery>// get a line of input
<syntaxhighlight lang="nanoquery">// get a line of input
line = input()
line = input()
Line 3,682: Line 4,020:
// add the two numbers and print the result
// add the two numbers and print the result
println int(strings[0]) + int(strings[1])</lang>
println int(strings[0]) + int(strings[1])</syntaxhighlight>


=={{header|Neko}}==
=={{header|Neko}}==
<syntaxhighlight lang="actionscript">/**
<lang ActionScript>/**
A+B, Rosetta Code, in Neko
A+B, Rosetta Code, in Neko
Tectonics:
Tectonics:
Line 3,749: Line 4,087:
} else $print("Need two numbers, separated by whitespace\n")
} else $print("Need two numbers, separated by whitespace\n")


} catch with $print("Exception: ", with, "\n")</lang>
} catch with $print("Exception: ", with, "\n")</syntaxhighlight>


{{out}}
{{out}}
Line 3,761: Line 4,099:
=={{header|Nemerle}}==
=={{header|Nemerle}}==
{{trans|C#}}
{{trans|C#}}
<lang Nemerle>using System;
<syntaxhighlight lang="nemerle">using System;
using System.Console;
using System.Console;
using System.Linq;
using System.Linq;
Line 3,771: Line 4,109:
WriteLine(ReadLine().Split().Select(int.Parse).Sum());
WriteLine(ReadLine().Split().Select(int.Parse).Sum());
}
}
}</lang>
}</syntaxhighlight>


=={{header|NetRexx}}==
=={{header|NetRexx}}==
<lang NetRexx>/* NetRexx */
<syntaxhighlight lang="netrexx">/* NetRexx */


options replace format comments java symbols binary
options replace format comments java symbols binary


parse ask a b .
parse ask a b .
say a '+' b '=' a + b</lang>
say a '+' b '=' a + b</syntaxhighlight>


=={{header|newLISP}}==
=={{header|newLISP}}==
<lang newLISP>(println (apply + (map int (parse (read-line)))))</lang>
<syntaxhighlight lang="newlisp">(println (apply + (map int (parse (read-line)))))</syntaxhighlight>


=={{header|Nim}}==
=={{header|Nim}}==
A+B:
A+B:
<lang nim>
<syntaxhighlight lang="nim">
# Takes 2 inputs of Floats and adds them (which is not correct for the exercise, will revisit, Thank you
# Takes 2 inputs of Floats and adds them (which is not correct for the exercise, will revisit, Thank you


Line 3,807: Line 4,145:
let second: float = getnumber()
let second: float = getnumber()


echo("Result: " & formatFloat(aplusb(first, second), ffDecimal, 2))</lang>
echo("Result: " & formatFloat(aplusb(first, second), ffDecimal, 2))</syntaxhighlight>


The puzzle requires 1 input, 2 INTS separated by a space, than a+b
The puzzle requires 1 input, 2 INTS separated by a space, than a+b
Line 3,814: Line 4,152:
=={{header|Nit}}==
=={{header|Nit}}==
Generic non-robust version (source: [https://github.com/nitlang/nit/blob/master/examples/rosettacode/ab.nit the Nit’s official repository]):
Generic non-robust version (source: [https://github.com/nitlang/nit/blob/master/examples/rosettacode/ab.nit the Nit’s official repository]):
<lang nit>module ab
<syntaxhighlight lang="nit">module ab


var words = gets.split(" ")
var words = gets.split(" ")
Line 3,821: Line 4,159:
return
return
end
end
print words[0].to_i + words[1].to_i</lang>
print words[0].to_i + words[1].to_i</syntaxhighlight>


=={{header|NS-HUBASIC}}==
=={{header|NS-HUBASIC}}==
<lang NS-HUBASIC>10 INPUT "ENTER NUMBER A: ",A
<syntaxhighlight lang="ns-hubasic">10 INPUT "ENTER NUMBER A: ",A
20 INPUT "ENTER NUMBER B: ",B
20 INPUT "ENTER NUMBER B: ",B
30 PRINT A+B</lang>
30 PRINT A+B</syntaxhighlight>

=={{header|Nu}}==
<syntaxhighlight lang="nu">
input | parse "{a} {b}" | first | values | into int | math sum
</syntaxhighlight>

=={{header|Nutt}}==
<syntaxhighlight lang="Nutt">
module main
imports native.io{input.hear,output.say}

vals a=hear(Int),b=hear(Int)
say(a+b)

end
</syntaxhighlight>


=={{header|Nyquist}}==
=={{header|Nyquist}}==
===SAL Syntax===
===SAL Syntax===
<lang Nyquist>;nyquist plug-in
<syntaxhighlight lang="nyquist">;nyquist plug-in
;version 1
;version 1
;type tool
;type tool
Line 3,841: Line 4,195:
print a + b
print a + b
return ""</lang>
return ""</syntaxhighlight>


===Audacity plug-in (SAL syntax)===
===Audacity plug-in (SAL syntax)===
<lang Nyquist>;nyquist plug-in
<syntaxhighlight lang="nyquist">;nyquist plug-in
;version 1
;version 1
;type tool
;type tool
Line 3,855: Line 4,209:
print a + b
print a + b


return ""</lang>
return ""</syntaxhighlight>


=={{header|Oberon-2}}==
=={{header|Oberon-2}}==
<lang oberon2>MODULE ab;
<syntaxhighlight lang="oberon2">MODULE ab;


IMPORT In, Out;
IMPORT In, Out;
Line 3,869: Line 4,223:
Out.Int (A + B, 8);
Out.Int (A + B, 8);
Out.Ln
Out.Ln
END ab.</lang>
END ab.</syntaxhighlight>
Producing
Producing
<pre>
<pre>
Line 3,877: Line 4,231:


=={{header|Objeck}}==
=={{header|Objeck}}==
<lang objeck>bundle Default {
<syntaxhighlight lang="objeck">bundle Default {
class Vander {
class Vander {
function : Main(args : String[]) ~ Nil {
function : Main(args : String[]) ~ Nil {
Line 3,886: Line 4,240:
}
}
}
}
}</lang>
}</syntaxhighlight>


=={{header|OCaml}}==
=={{header|OCaml}}==
<lang ocaml>Scanf.scanf "%d %d" (fun a b -> Printf.printf "%d\n" (a + b))</lang>
<syntaxhighlight lang="ocaml">Scanf.scanf "%d %d" (fun a b -> Printf.printf "%d\n" (a + b))</syntaxhighlight>


=={{header|Oforth}}==
=={{header|Oforth}}==
Line 3,895: Line 4,249:
Works with any number of integers separated by a space.
Works with any number of integers separated by a space.


<lang Oforth>import: mapping
<syntaxhighlight lang="oforth">import: mapping


System.Console accept words map( #>integer) reduce( #+ ) printcr .</lang>
System.Console accept words map( #>integer) reduce( #+ ) printcr .</syntaxhighlight>


=={{header|Ol}}==
=={{header|Ol}}==
Note: input data must be separated by newline ([Enter] key press).
Note: input data must be separated by newline ([Enter] key press).


<lang ol>; simplest
<syntaxhighlight lang="ol">; simplest
(+ (read) (read))
(+ (read) (read))


Line 3,914: Line 4,268:


(print a " + " b " = " (+ a b)))
(print a " + " b " = " (+ a b)))
</syntaxhighlight>
</lang>


=={{header|Onyx}}==
=={{header|Onyx}}==


<lang onyx>$Prompt {
<syntaxhighlight lang="onyx">$Prompt {
`\nEnter two numbers between -1000 and +1000,\nseparated by a space: ' print flush
`\nEnter two numbers between -1000 and +1000,\nseparated by a space: ' print flush
} def
} def
Line 3,942: Line 4,296:
} def
} def


Prompt GetNumbers CheckInput Answer</lang>
Prompt GetNumbers CheckInput Answer</syntaxhighlight>


=={{header|ooRexx}}==
=={{header|ooRexx}}==
===version 1===
===version 1===
{{trans|REXX}}
{{trans|REXX}}
<lang oorexx>Numeric digits 1000 /*just in case the user gets ka-razy. */
<syntaxhighlight lang="oorexx">Numeric digits 1000 /*just in case the user gets ka-razy. */
Say 'enter some numbers to be summed:'
Say 'enter some numbers to be summed:'
parse pull y
parse pull y
Line 3,965: Line 4,319:
Parse arg list
Parse arg list
list=space(list)
list=space(list)
return translate(list,'+',' ')</lang>
return translate(list,'+',' ')</syntaxhighlight>
{{out}}
{{out}}
<pre>enter some numbers to be summed:
<pre>enter some numbers to be summed:
Line 3,971: Line 4,325:
===version 2===
===version 2===
extend for negative numbers
extend for negative numbers
<lang oorexx>Numeric digits 1000
<syntaxhighlight lang="oorexx">Numeric digits 1000
Say 'enter some numbers to be summed:'
Say 'enter some numbers to be summed:'
parse pull y
parse pull y
Line 3,991: Line 4,345:
End
End
Say yplus '=' sum/1
Say yplus '=' sum/1
Exit</lang>
Exit</syntaxhighlight>


=={{header|OpenEdge/Progress}}==
=={{header|OpenEdge/Progress}}==
<lang progress>DEFINE VARIABLE a AS INTEGER NO-UNDO FORMAT "->>>9".
<syntaxhighlight lang="progress">DEFINE VARIABLE a AS INTEGER NO-UNDO FORMAT "->>>9".
DEFINE VARIABLE b AS INTEGER NO-UNDO FORMAT "->>>9".
DEFINE VARIABLE b AS INTEGER NO-UNDO FORMAT "->>>9".


Line 4,005: Line 4,359:
UPDATE a b.
UPDATE a b.


MESSAGE a + b VIEW-AS ALERT-BOX</lang>
MESSAGE a + b VIEW-AS ALERT-BOX</syntaxhighlight>


=={{header|Openscad}}==
=={{header|Openscad}}==
There is no means of run-time input in Openscad
There is no means of run-time input in Openscad
<lang openscad>
<syntaxhighlight lang="openscad">
a = 5 + 4;
a = 5 + 4;
echo (a);
echo (a);
</syntaxhighlight>
</lang>


=={{header|Order}}==
=={{header|Order}}==
Line 4,018: Line 4,372:


To run this Order program, you must define the macros '''A''' and '''B''' to values of the form '''8int(SIGN, 8nat(VALUE))''', where SIGN is 1/0 to represent signed/unsigned numbers, and VALUES is any comma-separated list of decimal digits. For example, to evaluate the sum of A=-150, B=275, define A to be '''8int(1, 8nat(1,5,0))''' and B to be '''8int(0, 8nat(2,7,5))'''.
To run this Order program, you must define the macros '''A''' and '''B''' to values of the form '''8int(SIGN, 8nat(VALUE))''', where SIGN is 1/0 to represent signed/unsigned numbers, and VALUES is any comma-separated list of decimal digits. For example, to evaluate the sum of A=-150, B=275, define A to be '''8int(1, 8nat(1,5,0))''' and B to be '''8int(0, 8nat(2,7,5))'''.
<lang order>
<syntaxhighlight lang="order">
#define ORDER_PP_DEF_1int_is_positive \
#define ORDER_PP_DEF_1int_is_positive \
ORDER_PP_FN(8fn(8X, 8is_0(8tuple_at_0(8X))))
ORDER_PP_FN(8fn(8X, 8is_0(8tuple_at_0(8X))))
Line 4,055: Line 4,409:


ORDER_PP(8int_to_lit(8int_add(A, B)))
ORDER_PP(8int_to_lit(8int_add(A, B)))
</syntaxhighlight>
</lang>


=={{header|Oxygene}}==
=={{header|Oxygene}}==
<lang oxygene>
<syntaxhighlight lang="oxygene">
// Sum 2 integers read fron standard input
// Sum 2 integers read fron standard input
//
//
Line 4,091: Line 4,445:
end.
end.
</syntaxhighlight>
</lang>
Produces:
Produces:
<pre>
<pre>
Line 4,100: Line 4,454:


=={{header|Oz}}==
=={{header|Oz}}==
<lang oz>declare
<syntaxhighlight lang="oz">declare
class TextFile from Open.file Open.text end
class TextFile from Open.file Open.text end


Line 4,109: Line 4,463:
end
end
in
in
{Show {ReadInt}+{ReadInt}}</lang>
{Show {ReadInt}+{ReadInt}}</syntaxhighlight>


=={{header|PARI/GP}}==
=={{header|PARI/GP}}==
User input:
User input:
<lang parigp>input()+input()</lang>
<syntaxhighlight lang="parigp">input()+input()</syntaxhighlight>
File input:
File input:
<lang parigp>read("file1")+read("file2")</lang>
<syntaxhighlight lang="parigp">read("file1")+read("file2")</syntaxhighlight>


=={{header|Pascal}}==
=={{header|Pascal}}==
<lang pascal>var
<syntaxhighlight lang="pascal">var
a, b: integer;
a, b: integer;
begin
begin
readln(a, b);
readln(a, b);
writeln(a + b);
writeln(a + b);
end.</lang>
end.</syntaxhighlight>
Same with input from file <tt>input.txt</tt> and output from file <tt>output.txt</tt>.
Same with input from file <tt>input.txt</tt> and output from file <tt>output.txt</tt>.
<lang pascal>var
<syntaxhighlight lang="pascal">var
a, b: integer;
a, b: integer;
begin
begin
Line 4,134: Line 4,488:
close(input);
close(input);
close(output);
close(output);
end.</lang>
end.</syntaxhighlight>
===Version 2. Following the rules===
===Version 2. Following the rules===
<lang pascal>{ Task: A + B
<syntaxhighlight lang="pascal">{ Task: A + B
Sum of A + B while A, B >= -1000 and A,B <= 1000
Sum of A + B while A, B >= -1000 and A,B <= 1000
Author: Sinuhe Masan (2019) }
Author: Sinuhe Masan (2019) }
Line 4,153: Line 4,507:
writeln('The sum is: ', A + B);
writeln('The sum is: ', A + B);


end.</lang>
end.</syntaxhighlight>


=={{header|Perl}}==
=={{header|Perl}}==
<lang Perl>my ($a,$b) = split(' ', scalar(<STDIN>));
<syntaxhighlight lang="perl">my ($a,$b) = split(' ', scalar(<STDIN>));
print "$a $b " . ($a + $b) . "\n";</lang>
print "$a $b " . ($a + $b) . "\n";</syntaxhighlight>


=== using the List::Util module ===
=== using the List::Util module ===
<lang Perl>say sum split /\s+/, scalar <STDIN>;</lang>
<syntaxhighlight lang="perl">say sum split /\s+/, scalar <STDIN>;</syntaxhighlight>


=={{header|Phix}}==
=={{header|Phix}}==
<!--<lang Phix>-->
<!--<syntaxhighlight lang="phix">-->
<span style="color: #000080;font-style:italic;">-- demo\rosetta\AplusB.exw</span>
<span style="color: #000080;font-style:italic;">-- demo\rosetta\AplusB.exw</span>
<span style="color: #004080;">string</span> <span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">prompt_string</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"Enter two numbers separated by a space : "</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">string</span> <span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">prompt_string</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"Enter two numbers separated by a space : "</span><span style="color: #0000FF;">)</span>
Line 4,173: Line 4,527:
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"invalid input\n"</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"invalid input\n"</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<!--</lang>-->
<!--</syntaxhighlight>-->
{{out}}
{{out}}
<pre>
<pre>
Line 4,180: Line 4,534:
</pre>
</pre>
=== GUI version ===
=== GUI version ===
{{libheader|Phix/pGUI}}
<small>(The above console version is now just a comment in the distributed file.)</small>
<small>(The above console version is now just a comment in the distributed file.)</small>
<!--<lang Phix>(phixonline)-->
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #000080;font-style:italic;">-- demo\rosetta\AplusB.exw</span>
<span style="color: #000080;font-style:italic;">-- demo\rosetta\AplusB.exw</span>
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
Line 4,214: Line 4,569:
<span style="color: #000000;">main</span><span style="color: #0000FF;">()</span>
<span style="color: #000000;">main</span><span style="color: #0000FF;">()</span>
<!--</lang>-->
<!--</syntaxhighlight>-->


=={{header|Phixmonti}}==
=={{header|Phixmonti}}==
<lang Phixmonti>/# Rosetta Code problem: http://rosettacode.org/wiki/A+B
<syntaxhighlight lang="phixmonti">/# Rosetta Code problem: http://rosettacode.org/wiki/A+B
by Galileo, 05/2022 #/
by Galileo, 05/2022 #/


Line 4,233: Line 4,588:


over over + >ps
over over + >ps
nl "The sum of " print print " and " print print " is: " print ps> print</lang>
nl "The sum of " print print " and " print print " is: " print ps> print
/#
swap over over + >ps >ps >ps
nl ( "The sum of " ps> " and " ps> " is: " ps> ) lprint
#/</syntaxhighlight>
{{out}}
{{out}}
<pre>Enter two numbers (betwen -1000 ... +1000) separated by space: 2 3
<pre>Enter two numbers (betwen -1000 ... +1000) separated by space: 2 3
Line 4,240: Line 4,599:


=={{header|PHP}}==
=={{header|PHP}}==
<lang php>fscanf(STDIN, "%d %d\n", $a, $b); //Reads 2 numbers from STDIN
<syntaxhighlight lang="php">fscanf(STDIN, "%d %d\n", $a, $b); //Reads 2 numbers from STDIN
echo ($a + $b) . "\n";</lang>
echo ($a + $b) . "\n";</syntaxhighlight>
<lang php>$in = fopen("input.dat", "r");
<syntaxhighlight lang="php">$in = fopen("input.dat", "r");
fscanf($in, "%d %d\n", $a, $b); //Reads 2 numbers from file $in
fscanf($in, "%d %d\n", $a, $b); //Reads 2 numbers from file $in
fclose($in);
fclose($in);
Line 4,248: Line 4,607:
$out = fopen("output.dat", "w");
$out = fopen("output.dat", "w");
fwrite($out, ($a + $b) . "\n");
fwrite($out, ($a + $b) . "\n");
fclose($out);</lang>
fclose($out);</syntaxhighlight>


=={{header|Picat}}==
=={{header|Picat}}==
<syntaxhighlight lang="picat">
<lang Picat>
go =>
go =>
println("Write two integers (and CR)"),
println("Write two integers (and CR)"),
println(read_int()+read_int()).
println(read_int()+read_int()).
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 4,272: Line 4,631:


=={{header|PicoLisp}}==
=={{header|PicoLisp}}==
<lang PicoLisp>(+ (read) (read))
<syntaxhighlight lang="picolisp">(+ (read) (read))
3 4
3 4
-> 7</lang>
-> 7</syntaxhighlight>


=={{header|Piet}}==
=={{header|Piet}}==
[[File:Piet A+B.png]]
[[File:Piet A+B.png]]
The code is fairly straightforward. The individual commands are as follows:
The code is fairly straightforward. The individual commands are as follows:
<lang text>in(num)
<syntaxhighlight lang="text">in(num)
in(num)
in(num)
add
add
out(num)</lang>
out(num)</syntaxhighlight>


=={{header|Pike}}==
=={{header|Pike}}==
<lang Pike>string line = Stdio.stdin->gets();
<syntaxhighlight lang="pike">string line = Stdio.stdin->gets();
sscanf(line, "%d %d", int a, int b);
sscanf(line, "%d %d", int a, int b);
write(a+b +"\n");</lang>
write(a+b +"\n");</syntaxhighlight>


=={{header|PL/I}}==
=={{header|PL/I}}==
<lang pli>get (a, b);
<syntaxhighlight lang="pli">get (a, b);
put (a+b);</lang>
put (a+b);</syntaxhighlight>

=={{header|Plain English}}==
<syntaxhighlight lang="plainenglish">
To run:
Start up.
Read a number from the console.
Read another number from the console.
Output the sum of the number and the other number.
Wait for the escape key.
Shut down.

To output the sum of a number and another number:
If the number is not valid, write "Invalid input" to the console; exit.
If the other number is not valid, write "Invalid input" to the console; exit.
Write the number plus the other number then " is the sum." to the console.

To decide if a number is valid:
If the number is not greater than or equal to -1000, say no.
If the number is not less than or equal to 1000, say no.
Say yes.
</syntaxhighlight>


=={{header|Pony}}==
=={{header|Pony}}==
<lang pony>
<syntaxhighlight lang="pony">
actor Main
actor Main
let _env:Env
let _env:Env
Line 4,320: Line 4,700:
_env.out.print(sum.string())
_env.out.print(sum.string())


</syntaxhighlight>
</lang>


=={{header|PostScript}}==
=={{header|PostScript}}==
<lang postscript>(%stdin) (r) file % get stdin
<syntaxhighlight lang="postscript">(%stdin) (r) file % get stdin
dup
dup
token pop % read A
token pop % read A
Line 4,329: Line 4,709:
token pop % read B
token pop % read B
add
add
=</lang>
=</syntaxhighlight>


=={{header|Potion}}==
=={{header|Potion}}==
<lang potion># The numbers are entered, piped, or redirected in via STDIN and the format is proper (i.e., "%d %d").
<syntaxhighlight lang="potion"># The numbers are entered, piped, or redirected in via STDIN and the format is proper (i.e., "%d %d").
input = read
input = read
i = 0
i = 0
Line 4,344: Line 4,724:


# The numbers are manually inputted, but the format is improper (i.e., "%d\n%d\n").
# The numbers are manually inputted, but the format is improper (i.e., "%d\n%d\n").
(read number + read number) print</lang>
(read number + read number) print</syntaxhighlight>


=={{header|PowerShell}}==
=={{header|PowerShell}}==
<lang powershell>$a,$b = -split "$input"
<syntaxhighlight lang="powershell">$a,$b = -split "$input"
[int]$a + [int]$b</lang>
[int]$a + [int]$b</syntaxhighlight>
This solution does not work interactively, while the following ''only'' works interactively:
This solution does not work interactively, while the following ''only'' works interactively:
<lang powershell>$a,$b = -split (Read-Host)
<syntaxhighlight lang="powershell">$a,$b = -split (Read-Host)
[int]$a + [int]$b</lang>
[int]$a + [int]$b</syntaxhighlight>


I think this works better and doesn't require string input (following the task closer):
I think this works better and doesn't require string input (following the task closer):
<lang powershell>filter add {
<syntaxhighlight lang="powershell">filter add {
return [int]$args[0] + [int]$args[1]
return [int]$args[0] + [int]$args[1]
}</lang>
}</syntaxhighlight>


Can be called in one line with
Can be called in one line with
<lang powershell>add 2 3</lang>
<syntaxhighlight lang="powershell">add 2 3</syntaxhighlight>


=={{header|Processing}}==
=={{header|Processing}}==
===Rudimentary User Interface===
===Rudimentary User Interface===
Click on either side to add 1 to its value.
Click on either side to add 1 to its value.
<lang Processing>int a = 0;
<syntaxhighlight lang="processing">int a = 0;
int b = 0;
int b = 0;


Line 4,388: Line 4,768:
b++;
b++;
}
}
}</lang>
}</syntaxhighlight>


[https://i.imgur.com/QEHtMyA.jpg What the GUI looks like.]
[https://i.imgur.com/QEHtMyA.jpg What the GUI looks like.]
Line 4,394: Line 4,774:
=={{header|ProDOS}}==
=={{header|ProDOS}}==
With the math module:
With the math module:
<lang ProDOS>editvar /newvar /value=a /title=Enter an integer:
<syntaxhighlight lang="prodos">editvar /newvar /value=a /title=Enter an integer:
editvar /newvar /value=b /title=Enter another integer:
editvar /newvar /value=b /title=Enter another integer:
editvar /newvar /value=c
editvar /newvar /value=c
do add -a-,-b-=-c-
do add -a-,-b-=-c-
printline -c- </lang>
printline -c- </syntaxhighlight>
Without the math module:
Without the math module:
<lang ProDOS>editvar /newvar /value=a /title=Enter an integer:
<syntaxhighlight lang="prodos">editvar /newvar /value=a /title=Enter an integer:
editvar /newvar /value=b /title=Enter another integer:
editvar /newvar /value=b /title=Enter another integer:
editvar /newvar /value=c=-a-+-b-
editvar /newvar /value=c=-a-+-b-
printline -c- </lang>
printline -c- </syntaxhighlight>


=={{header|Prolog}}==
=={{header|Prolog}}==
{{Works with|SWI-Prolog}}
{{Works with|SWI-Prolog}}
<lang Prolog>plus :-
<syntaxhighlight lang="prolog">plus :-
read_line_to_codes(user_input,X),
read_line_to_codes(user_input,X),
atom_codes(A, X),
atom_codes(A, X),
Line 4,413: Line 4,793:
maplist(atom_number, L, LN),
maplist(atom_number, L, LN),
sumlist(LN, N),
sumlist(LN, N),
write(N).</lang>
write(N).</syntaxhighlight>
output :
output :
<lang Prolog>?- plus.
<syntaxhighlight lang="prolog">?- plus.
|: 4 5
|: 4 5
9
9
true.</lang>
true.</syntaxhighlight>


=={{header|Pure}}==
=={{header|Pure}}==
<lang pure>using system;
<syntaxhighlight lang="pure">using system;
printf "%d\n" (x+y) when x,y = scanf "%d %d" end;</lang>
printf "%d\n" (x+y) when x,y = scanf "%d %d" end;</syntaxhighlight>


=={{header|PureBasic}}==
=={{header|PureBasic}}==
===Console===
===Console===
<lang PureBasic>x$=Input()
<syntaxhighlight lang="purebasic">x$=Input()
a=Val(StringField(x$,1," "))
a=Val(StringField(x$,1," "))
b=Val(StringField(x$,2," "))
b=Val(StringField(x$,2," "))
PrintN(str(a+b))</lang>
PrintN(str(a+b))</syntaxhighlight>
===File===
===File===
<lang PureBasic>If ReadFile(0,"in.txt")
<syntaxhighlight lang="purebasic">If ReadFile(0,"in.txt")
x$=ReadString(0)
x$=ReadString(0)
a=Val(StringField(x$,1," "))
a=Val(StringField(x$,1," "))
Line 4,440: Line 4,820:
EndIf
EndIf
CloseFile(0)
CloseFile(0)
EndIf </lang>
EndIf </syntaxhighlight>


=={{header|Python}}==
=={{header|Python}}==
Line 4,449: Line 4,829:
The first two lines allow the program to be run in either Python 2 or 3. In Python 2, <code>raw_input</code> exists, and the lines are effectively skipped. In Python 3, calling <code>raw_input</code> triggers an error, so the <code>except</code> loop activates and assigns "raw_input" the value of Python 3's "input" function. Regardless of version, these two lines make sure that <code>raw_input</code> will return a string.
The first two lines allow the program to be run in either Python 2 or 3. In Python 2, <code>raw_input</code> exists, and the lines are effectively skipped. In Python 3, calling <code>raw_input</code> triggers an error, so the <code>except</code> loop activates and assigns "raw_input" the value of Python 3's "input" function. Regardless of version, these two lines make sure that <code>raw_input</code> will return a string.


<lang python>try: raw_input
<syntaxhighlight lang="python">try: raw_input
except: raw_input = input
except: raw_input = input


print(sum(map(int, raw_input().split())))</lang>
print(sum(map(int, raw_input().split())))</syntaxhighlight>


===File===
===File===
For Python 2.X and 3.X taking input from stdin stream which can be redirected to be file input under Unix
For Python 2.X and 3.X taking input from stdin stream which can be redirected to be file input under Unix
<lang python>import sys
<syntaxhighlight lang="python">import sys


for line in sys.stdin:
for line in sys.stdin:
print(sum(map(int, line.split())))</lang>
print(sum(map(int, line.split())))</syntaxhighlight>


===Console, Python 3 only===
===Console, Python 3 only===
<lang python>a = int(input("First number: "))
<syntaxhighlight lang="python">a = int(input("First number: "))
b = int(input("Second number: "))
b = int(input("Second number: "))
print("Result:", a+b)</lang>
print("Result:", a+b)</syntaxhighlight>


=={{header|QB64}}==
=={{header|QB64}}==
<lang QB64>DIM a AS INTEGER, b AS INTEGER
<syntaxhighlight lang="qb64">DIM a AS INTEGER, b AS INTEGER
DIM c AS LONG
DIM c AS LONG
INPUT "Enter A: ", a
INPUT "Enter A: ", a
Line 4,473: Line 4,853:
c = a + b
c = a + b
PRINT ""
PRINT ""
PRINT "A + B = " + LTRIM$(STR$(c)) </lang>
PRINT "A + B = " + LTRIM$(STR$(c)) </syntaxhighlight>


'''Fully implemented version:'''
'''Fully implemented version:'''
Line 4,483: Line 4,863:
** Integers between -1000 and +1000.
** Integers between -1000 and +1000.
<lang qbasic>START:
<syntaxhighlight lang="qbasic">START:
PRINT "Enter two integers between -1000 and +1000 separated by at least one space: "
PRINT "Enter two integers between -1000 and +1000 separated by at least one space: "
INPUT "> "; n$ ' | Enter two numbers with at least one space between.
INPUT "> "; n$ ' | Enter two numbers with at least one space between.
Line 4,497: Line 4,877:
b$ = LTRIM$(STR$(b)) ' | "
b$ = LTRIM$(STR$(b)) ' | "
sum$ = LTRIM$(STR$(a + b)) ' | "
sum$ = LTRIM$(STR$(a + b)) ' | "
PRINT "The sum of the two integers a + b = "; a$; " + "; b$; " = "; sum$</lang>
PRINT "The sum of the two integers a + b = "; a$; " + "; b$; " = "; sum$</syntaxhighlight>


=={{header|Quackery}}==
=={{header|Quackery}}==
Line 4,510: Line 4,890:


=={{header|Quite BASIC}}==
=={{header|Quite BASIC}}==
<lang Quite BASIC>10 input "Enter number A: ";a
<syntaxhighlight lang="quite basic">10 input "Enter number A: ";a
20 input "Enter number B: ";b
20 input "Enter number B: ";b
30 print a+b</lang>
30 print a+b</syntaxhighlight>


=={{header|R}}==
=={{header|R}}==
<lang r>sum(scan("", numeric(0), 2))</lang>
<syntaxhighlight lang="r">sum(scan("", numeric(0), 2))</syntaxhighlight>


=={{header|Ra}}==
=={{header|Ra}}==
<syntaxhighlight lang="ra">
<lang Ra>
class Sum
class Sum
**Adds two given integers**
**Adds two given integers**
Line 4,544: Line 4,924:
print to Console.error made !, "Numbers too large"
print to Console.error made !, "Numbers too large"
exit program with error code
exit program with error code
</syntaxhighlight>
</lang>


=={{header|Racket}}==
=={{header|Racket}}==


<lang racket>
<syntaxhighlight lang="racket">
#lang racket
#lang racket
(+ (read) (read))
(+ (read) (read))
</syntaxhighlight>
</lang>


Or, with additional error checking:
Or, with additional error checking:
<lang racket>
<syntaxhighlight lang="racket">
#lang racket
#lang racket
(define a (read))
(define a (read))
Line 4,561: Line 4,941:
(unless (number? b) (error 'a+b "number" b))
(unless (number? b) (error 'a+b "number" b))
(displayln (+ a b))
(displayln (+ a b))
</syntaxhighlight>
</lang>


=={{header|Raku}}==
=={{header|Raku}}==
Line 4,568: Line 4,948:


Short version with very little "line noise":
Short version with very little "line noise":
<lang perl6>get.words.sum.say;</lang>
<syntaxhighlight lang="raku" line>get.words.sum.say;</syntaxhighlight>
Reduction operator <code>[+]</code>, and <code>say</code> as a function:
Reduction operator <code>[+]</code>, and <code>say</code> as a function:
<lang perl6>say [+] get.words;</lang>
<syntaxhighlight lang="raku" line>say [+] get.words;</syntaxhighlight>
Long version:
Long version:
<lang perl6>my ($a, $b) = $*IN.get.split(" ");
<syntaxhighlight lang="raku" line>my ($a, $b) = $*IN.get.split(" ");
say $a + $b;</lang>
say $a + $b;</syntaxhighlight>


=={{header|REBOL}}==
=={{header|REBOL}}==
<lang rebol>forever [x: load input print x/1 + x/2]</lang>
<syntaxhighlight lang="rebol">forever [x: load input print x/1 + x/2]</syntaxhighlight>
{{Out}}
{{Out}}
<pre>1 2
<pre>1 2
Line 4,586: Line 4,966:


=={{header|Red}}==
=={{header|Red}}==
<lang Red>x: load input print x/1 + x/2</lang>
<syntaxhighlight lang="red">x: load input print x/1 + x/2</syntaxhighlight>
{{Out}}
{{Out}}
<pre>1 2
<pre>1 2
Line 4,596: Line 4,976:


Alternative implementations:
Alternative implementations:
<lang Red>print (first x: load input) + x/2</lang>
<syntaxhighlight lang="red">print (first x: load input) + x/2</syntaxhighlight>
<lang Red>print head insert load input 'add</lang>
<syntaxhighlight lang="red">print head insert load input 'add</syntaxhighlight>
<lang Red>print load replace input " " " + "</lang>
<syntaxhighlight lang="red">print load replace input " " " + "</syntaxhighlight>


=={{header|Relation}}==
=={{header|Relation}}==
<syntaxhighlight lang="relation">
<lang Relation>
set input = "2 2"
set input = "2 2"
set a = regexreplace(input,"^(-?\d+)\s+(-?\d+)+$","$1")
set a = regexreplace(input,"^(-?\d+)\s+(-?\d+)+$","$1")
set b = regexreplace(input,"^(-?\d+)\s+(-?\d+)+$","$2")
set b = regexreplace(input,"^(-?\d+)\s+(-?\d+)+$","$2")
echo a + b
echo a + b
</syntaxhighlight>
</lang>


=={{header|Retro}}==
=={{header|Retro}}==
<lang Retro>:try ("-n) s:get s:to-number s:get s:to-number + n:put ;</lang>
<syntaxhighlight lang="retro">:try ("-n) s:get s:to-number s:get s:to-number + n:put ;</syntaxhighlight>
<syntaxhighlight lang="retro">try
<lang Retro>try
1
1
2</lang>
2</syntaxhighlight>


=={{header|REXX}}==
=={{header|REXX}}==
===version 1, unnormalized===
===version 1, unnormalized===
The numbers can be any valid REXX number (integer, fixed point decimal, floating point (with exponential notation, ···).
The numbers can be any valid REXX number (integer, fixed point decimal, floating point (with exponential notation, ···).
<lang rexx>/*REXX program obtains two numbers from the input stream (the console), shows their sum.*/
<syntaxhighlight lang="rexx">/*REXX program obtains two numbers from the input stream (the console), shows their sum.*/
parse pull a b /*obtain two numbers from input stream.*/
parse pull a b /*obtain two numbers from input stream.*/
say a+b /*display the sum to the terminal. */
say a+b /*display the sum to the terminal. */
/*stick a fork in it, we're all done. */</lang>
/*stick a fork in it, we're all done. */</syntaxhighlight>
===version 2, normalizied===
===version 2, normalizied===
If the user entered &nbsp; '''4.00000''' &nbsp; and wanted to add &nbsp; '''5''' &nbsp; to that, and expects &nbsp; '''9''',
If the user entered &nbsp; '''4.00000''' &nbsp; and wanted to add &nbsp; '''5''' &nbsp; to that, and expects &nbsp; '''9''',
Line 4,629: Line 5,009:


Dividing by one normalizes the number.
Dividing by one normalizes the number.
<lang rexx>/*REXX program obtains two numbers from the input stream (the console), shows their sum.*/
<syntaxhighlight lang="rexx">/*REXX program obtains two numbers from the input stream (the console), shows their sum.*/
parse pull a b /*obtain two numbers from input stream.*/
parse pull a b /*obtain two numbers from input stream.*/
say (a+b) / 1 /*display normalized sum to terminal. */
say (a+b) / 1 /*display normalized sum to terminal. */
/*stick a fork in it, we're all done. */</lang>
/*stick a fork in it, we're all done. */</syntaxhighlight>


===version 3, extended precision===
===version 3, extended precision===
Using the &nbsp; '''numeric digits''' &nbsp; statement allows more decimal digits to be used, the default is &nbsp; '''9'''.
Using the &nbsp; '''numeric digits''' &nbsp; statement allows more decimal digits to be used, the default is &nbsp; '''9'''.
<lang rexx>/*REXX program obtains two numbers from the input stream (the console), shows their sum.*/
<syntaxhighlight lang="rexx">/*REXX program obtains two numbers from the input stream (the console), shows their sum.*/
numeric digits 300 /*the default is nine decimal digits.*/
numeric digits 300 /*the default is nine decimal digits.*/
parse pull a b /*obtain two numbers from input stream.*/
parse pull a b /*obtain two numbers from input stream.*/
z= (a+b) / 1 /*add and normalize sum, store it in Z.*/
z= (a+b) / 1 /*add and normalize sum, store it in Z.*/
say z /*display normalized sum Z to terminal.*/
say z /*display normalized sum Z to terminal.*/
/*stick a fork in it, we're all done. */</lang>
/*stick a fork in it, we're all done. */</syntaxhighlight>


===version 4, multiple numbers===
===version 4, multiple numbers===
This REXX version adds &nbsp; ''all'' &nbsp; the numbers entered &nbsp; (not just two).
This REXX version adds &nbsp; ''all'' &nbsp; the numbers entered &nbsp; (not just two).
<lang rexx>/*REXX program obtains some numbers from the input stream (the console), shows their sum*/
<syntaxhighlight lang="rexx">/*REXX program obtains some numbers from the input stream (the console), shows their sum*/
numeric digits 1000 /*just in case the user gets ka-razy. */
numeric digits 1000 /*just in case the user gets ka-razy. */
say 'enter some numbers to be summed:' /*display a prompt message to terminal.*/
say 'enter some numbers to be summed:' /*display a prompt message to terminal.*/
Line 4,655: Line 5,035:
end /*j*/
end /*j*/
/*stick a fork in it, we're all done. */
/*stick a fork in it, we're all done. */
say 'sum of ' many " numbers = " $/1 /*display normalized sum $ to terminal.*/</lang>
say 'sum of ' many " numbers = " $/1 /*display normalized sum $ to terminal.*/</syntaxhighlight>


===version 5, multiple numbers, tongue in cheek===
===version 5, multiple numbers, tongue in cheek===
<lang rexx>/*REXX program obtains some numbers from the input stream (the console), shows their sum*/
<syntaxhighlight lang="rexx">/*REXX program obtains some numbers from the input stream (the console), shows their sum*/
numeric digits 1000 /*just in case the user gets ka-razy. */
numeric digits 1000 /*just in case the user gets ka-razy. */
say 'enter some numbers to be summed:' /*display a prompt message to terminal.*/
say 'enter some numbers to be summed:' /*display a prompt message to terminal.*/
Line 4,665: Line 5,045:
y=translate(y,'+',' ')
y=translate(y,'+',' ')
Interpret 's='y
Interpret 's='y
say 'sum of ' many " numbers = " s/1 /*display normalized sum s to terminal.*/</lang>
say 'sum of ' many " numbers = " s/1 /*display normalized sum s to terminal.*/</syntaxhighlight>


=={{header|Ring}}==
=={{header|Ring}}==
<lang ring>give Numbers
<syntaxhighlight lang="ring">give Numbers
Numbers = split(Numbers)
Numbers = split(Numbers)
sum = 0
sum = 0
Line 4,676: Line 5,056:
func Split Str
func Split Str
for x in str if x = " " x = nl ok next
for x in str if x = " " x = nl ok next
return str2list(str)</lang>
return str2list(str)</syntaxhighlight>


=={{header|Robotic}}==
=={{header|Robotic}}==
<lang robotic>
<syntaxhighlight lang="robotic">
input string "Input A:"
input string "Input A:"
set "A" to "input"
set "A" to "input"
Line 4,686: Line 5,066:
* "('A' + 'B')"
* "('A' + 'B')"
end
end
</syntaxhighlight>
</lang>


Although the function in the first and third line asks for a string as the input, so long as the variable isn't made to store a string, it will default to an integer instead. Inserting a string to this will return a 0.
Although the function in the first and third line asks for a string as the input, so long as the variable isn't made to store a string, it will default to an integer instead. Inserting a string to this will return a 0.
Line 4,692: Line 5,072:
=={{header|Rockstar}}==
=={{header|Rockstar}}==
Minimized:
Minimized:
<syntaxhighlight lang="rockstar">
<lang Rockstar>
Listen to A number
Listen to A number
Listen to B
Listen to B
Say A number plus B
Say A number plus B
</syntaxhighlight>
</lang>
Idiomatic:
Idiomatic:
<syntaxhighlight lang="rockstar">
<lang Rockstar>
Listen to my voice
Listen to my voice
Listen to your thoughts
Listen to your thoughts
Shout your thoughts with my voice
Shout your thoughts with my voice
</syntaxhighlight>
</lang>

=={{header|RPL}}==
Related task is natively implemented in RPL.
+

2 2 +
2 3 +
{{out}}
<pre>
2: 4
1: 5
</pre>


=={{header|Ruby}}==
=={{header|Ruby}}==
<lang ruby>puts gets.split.sum(&:to_i)</lang>
<syntaxhighlight lang="ruby">puts gets.split.sum(&:to_i)</syntaxhighlight>


=={{header|Run BASIC}}==
=={{header|Run BASIC}}==
<lang runbasic>input, x$
<syntaxhighlight lang="runbasic">input, x$
print val(word$(x$,1)) + val(word$(x$,2))</lang>
print val(word$(x$,1)) + val(word$(x$,2))</syntaxhighlight>


=={{header|Rust}}==
=={{header|Rust}}==
<lang rust>use std::io;
<syntaxhighlight lang="rust">use std::io;


fn main() {
fn main() {
Line 4,723: Line 5,115:
}
}
println!("{}", i);
println!("{}", i);
}</lang>
}</syntaxhighlight>


or
or


<lang rust>use std::io;
<syntaxhighlight lang="rust">use std::io;


fn main() {
fn main() {
Line 4,737: Line 5,129:
.sum();
.sum();
println!("{}", sum);
println!("{}", sum);
}</lang>
}</syntaxhighlight>


=={{header|S-lang}}==
=={{header|S-lang}}==
<lang C>% A+B from stdin, sans error checking
<syntaxhighlight lang="c">% A+B from stdin, sans error checking
variable input, a, b;
variable input, a, b;


Line 4,746: Line 5,138:
input = strtrim_end(input, "\n");
input = strtrim_end(input, "\n");
() = sscanf(input, "%d%d", &a, &b);
() = sscanf(input, "%d%d", &a, &b);
print(a + b);</lang>
print(a + b);</syntaxhighlight>


{{out}}
{{out}}
Line 4,752: Line 5,144:
46</pre>
46</pre>


<lang C>% A+B from stdin, basic validity testing
<syntaxhighlight lang="c">% A+B from stdin, basic validity testing
variable input, a, b, rc;
variable input, a, b, rc;


Line 4,762: Line 5,154:
} else {
} else {
message("input invalid or out of range (-1000,1000): $input"$);
message("input invalid or out of range (-1000,1000): $input"$);
}</lang>
}</syntaxhighlight>


=={{header|Scala}}==
=={{header|Scala}}==
<lang scala>println(readLine().split(" ").map(_.toInt).sum)</lang>
<syntaxhighlight lang="scala">println(readLine().split(" ").map(_.toInt).sum)</syntaxhighlight>


This will work if the input is exactly as specified, with no extra whitespace. A slightly more robust version:
This will work if the input is exactly as specified, with no extra whitespace. A slightly more robust version:


<lang scala>val s = new java.util.Scanner(System.in)
<syntaxhighlight lang="scala">val s = new java.util.Scanner(System.in)
val sum = s.nextInt() + s.nextInt()
val sum = s.nextInt() + s.nextInt()
println(sum)</lang>
println(sum)</syntaxhighlight>


or
or


<lang scala>println(readLine().split(" ").filter(_.length>0).map(_.toInt).sum)</lang>
<syntaxhighlight lang="scala">println(readLine().split(" ").filter(_.length>0).map(_.toInt).sum)</syntaxhighlight>


=={{header|Scheme}}==
=={{header|Scheme}}==
<lang scheme>(display (+ (read) (read)))</lang>
<syntaxhighlight lang="scheme">(display (+ (read) (read)))</syntaxhighlight>


=={{header|Scratch}}==
=={{header|Scratch}}==
Line 4,787: Line 5,179:
=={{header|sed}}==
=={{header|sed}}==
Sed is for string processing and has no facility for manipulating numbers as numeric values. However, being Turing complete, sed can be coerced into performing mathematics.
Sed is for string processing and has no facility for manipulating numbers as numeric values. However, being Turing complete, sed can be coerced into performing mathematics.
<lang sed>: Loop
<syntaxhighlight lang="sed">: Loop
# All done
# All done
/^-*00* /s///
/^-*00* /s///
Line 4,812: Line 5,204:
# Decrement 2nd
# Decrement 2nd
s/\([^0]\)\(0*\);[^0]*\1\(.\).*\2\(9*\).*/\3\4/
s/\([^0]\)\(0*\);[^0]*\1\(.\).*\2\(9*\).*/\3\4/
t Loop</lang>
t Loop</syntaxhighlight>


Another method, based off of [http://unix.stackexchange.com/a/36959/11750 this StackExchange answer]:
Another method, based off of [http://unix.stackexchange.com/a/36959/11750 this StackExchange answer]:
<lang sed>#!/bin/sed -f
<syntaxhighlight lang="sed">#!/bin/sed -f


# Add a marker in front of each digit, for tracking tens, hundreds, etc.
# Add a marker in front of each digit, for tracking tens, hundreds, etc.
Line 4,853: Line 5,245:
s/</|/g
s/</|/g
t back
t back
s/^$/0/</lang>
s/^$/0/</syntaxhighlight>


=={{header|Seed7}}==
=={{header|Seed7}}==
<lang seed7>$ include "seed7_05.s7i";
<syntaxhighlight lang="seed7">$ include "seed7_05.s7i";


const proc: main is func
const proc: main is func
Line 4,866: Line 5,258:
read(b);
read(b);
writeln(a + b);
writeln(a + b);
end func;</lang>
end func;</syntaxhighlight>


=={{header|Self}}==
=={{header|Self}}==
Works with positive and negative integers, and also more than two integers.
Works with positive and negative integers, and also more than two integers.


<lang self>((stdin readLine splitOn: ' ') mapBy: [|:e| e asInteger]) sum printLine.</lang>
<syntaxhighlight lang="self">((stdin readLine splitOn: ' ') mapBy: [|:e| e asInteger]) sum printLine.</syntaxhighlight>


=={{header|SenseTalk}}==
=={{header|SenseTalk}}==
<lang sensetalk>ask "Enter the first number:"
<syntaxhighlight lang="sensetalk">ask "Enter the first number:"
put it into a
put it into a


Line 4,880: Line 5,272:
put it into b
put it into b


put a + b</lang>
put a + b</syntaxhighlight>
<lang sensetalk>put file "input.txt" into inputFile
<syntaxhighlight lang="sensetalk">put file "input.txt" into inputFile
split inputFile by space
split inputFile by space
put sum of inputFile</lang>
put sum of inputFile</syntaxhighlight>


=={{header|SequenceL}}==
=={{header|SequenceL}}==
<lang sequencel>import <Utilities/Conversion.sl>;
<syntaxhighlight lang="sequencel">import <Utilities/Conversion.sl>;


main(args(2)) := stringToInt(args[1]) + stringToInt(args[2]);</lang>
main(args(2)) := stringToInt(args[1]) + stringToInt(args[2]);</syntaxhighlight>


{{Out}}
{{Out}}
Line 4,901: Line 5,293:


=={{header|SETL}}==
=={{header|SETL}}==
<lang setl>read(A, B);
<syntaxhighlight lang="setl">read(A, B);
print(A + B);</lang>
print(A + B);</syntaxhighlight>


=={{header|Shiny}}==
=={{header|Shiny}}==
<lang shiny>if (io.line 'stdin').match ~(\d+)\s+(\d+)~
<syntaxhighlight lang="shiny">if (io.line 'stdin').match ~(\d+)\s+(\d+)~
say "$a $b %(a+b)d"
say "$a $b %(a+b)d"
end</lang>
end</syntaxhighlight>


=={{header|Sidef}}==
=={{header|Sidef}}==
Works with both positive and negative integers.
Works with both positive and negative integers.
<lang ruby>say STDIN.readline.words.map{.to_i}.sum</lang>
<syntaxhighlight lang="ruby">say STDIN.readline.words.map{.to_i}.sum</syntaxhighlight>


More idiomatically:
More idiomatically:
<lang ruby>say read(String).words»to_i»()«+»</lang>
<syntaxhighlight lang="ruby">say read(String).words»to_i()»«+»</syntaxhighlight>


Explicit summation:
Explicit summation:
<lang ruby>var (a, b) = read(String).words.map{.to_i}...
<syntaxhighlight lang="ruby">var (a, b) = read(String).words.map{.to_i}...
say a+b</lang>
say a+b</syntaxhighlight>


=={{header|Simula}}==
=={{header|Simula}}==
<lang simula>BEGIN
<syntaxhighlight lang="simula">BEGIN
WHILE NOT LASTITEM DO
WHILE NOT LASTITEM DO
BEGIN
BEGIN
Line 4,928: Line 5,320:
END;
END;
END.
END.
</syntaxhighlight>
</lang>


=={{header|Smalltalk}}==
=={{header|Smalltalk}}==
Most Smalltalk implementations do not have the notion of a standard input stream, since it has always been a GUI based programming environment. I've included test methods to demonstrate one way to create an input stream with two integers can be created. Opening a text file would be another.
Most Smalltalk implementations do not have the notion of a standard input stream, since it has always been a GUI based programming environment. I've included test methods to demonstrate one way to create an input stream with two integers can be created. Opening a text file would be another.
<lang smalltalk>'From Squeak3.7 of ''4 September 2004'' [latest update: #5989] on 8 August 2011 at 3:50:55 pm'!
<syntaxhighlight lang="smalltalk">'From Squeak3.7 of ''4 September 2004'' [latest update: #5989] on 8 August 2011 at 3:50:55 pm'!
Object subclass: #ABTask
Object subclass: #ABTask
instanceVariableNames: ''
instanceVariableNames: ''
Line 4,961: Line 5,353:
test3Plus2
test3Plus2
^ self
^ self
sum: (ReadStream on: '3 2')! !</lang>
sum: (ReadStream on: '3 2')! !</syntaxhighlight>


but all have a stream hierarchy, so the task could be restated to pass input and output as stream arguments:
but all have a stream hierarchy, so the task could be restated to pass input and output as stream arguments:
{{works with|Smalltalk/X}}
{{works with|Smalltalk/X}}
{{works with|VisualWorks Smalltalk}}
{{works with|VisualWorks Smalltalk}}
<lang smalltalk>|task|
<syntaxhighlight lang="smalltalk">|task|
task := [:inStream :outStream |
task := [:inStream :outStream |
|processLine|
|processLine|
Line 4,984: Line 5,376:
].
].


task value: ( 'dataIn.txt' asFilename readStream) value:Transcript.</lang>
task value: ( 'dataIn.txt' asFilename readStream) value:Transcript.</syntaxhighlight>
or:
or:
<lang smalltalk>task value: Stdin value: Stdout.</lang>
<syntaxhighlight lang="smalltalk">task value: Stdin value: Stdout.</syntaxhighlight>


=={{header|smart BASIC}}==
=={{header|smart BASIC}}==
<lang qbasic>INPUT n$
<syntaxhighlight lang="qbasic">INPUT n$
PRINT VAL(LEFT$(n$,(LEN(STR$(VAL(n$))))))+VAL(RIGHT$(n$,(LEN(n$)-LEN(STR$(VAL(n$)))-1)))</lang>
PRINT VAL(LEFT$(n$,(LEN(STR$(VAL(n$))))))+VAL(RIGHT$(n$,(LEN(n$)-LEN(STR$(VAL(n$)))-1)))</syntaxhighlight>


<b>NOTE:</b> This is a horribly forced way of doing this. smart BASIC has commands to SPLIT strings. Surely someone can provide better code than what I've written here. ;@)
<b>NOTE:</b> This is a horribly forced way of doing this. smart BASIC has commands to SPLIT strings. Surely someone can provide better code than what I've written here. ;@)
Line 4,998: Line 5,390:
A FAR more elegant solution was provided by "Dutchman" on the smart [http://kibernetik.pro/forum/viewforum.php?f=2 BASIC Support Forum]:
A FAR more elegant solution was provided by "Dutchman" on the smart [http://kibernetik.pro/forum/viewforum.php?f=2 BASIC Support Forum]:


<lang qbasic>INPUT n$
<syntaxhighlight lang="qbasic">INPUT n$
SPLIT n$ TO m$,n WITH " "
SPLIT n$ TO m$,n WITH " "
PRINT m$(0),m$(1),m$(0)+m$(1)</lang>
PRINT m$(0),m$(1),m$(0)+m$(1)</syntaxhighlight>


<b>NOTE:</b> smart BASIC will intelligently interpret the contents of a string as a numeric value if necessary. Other versions of BASIC would require the values stored in a string to be converted to numeric values before calculation.
<b>NOTE:</b> smart BASIC will intelligently interpret the contents of a string as a numeric value if necessary. Other versions of BASIC would require the values stored in a string to be converted to numeric values before calculation.


=={{header|SmileBASIC}}==
=={{header|SmileBASIC}}==
<lang smilebasic>INPUT A
<syntaxhighlight lang="smilebasic">INPUT A
INPUT B
INPUT B
PRINT A+B
PRINT A+B
</syntaxhighlight>
</lang>


=={{header|SNOBOL4}}==
=={{header|SNOBOL4}}==
Simple-minded solution (literally "two somethings separated by space")
Simple-minded solution (literally "two somethings separated by space")
<lang snobol> input break(" ") . a " " rem . b
<syntaxhighlight lang="snobol"> input break(" ") . a " " rem . b
output = a + b
output = a + b
end</lang>
end</syntaxhighlight>
"Integer aware" solution:
"Integer aware" solution:
<lang snobol> nums = "0123456789"
<syntaxhighlight lang="snobol"> nums = "0123456789"
input span(nums) . a break(nums) span(nums) . b
input span(nums) . a break(nums) span(nums) . b
output = a + b
output = a + b
end</lang>
end</syntaxhighlight>


=={{header|SPAD}}==
=={{header|SPAD}}==
Line 5,026: Line 5,418:
{{works with|Axiom}}
{{works with|Axiom}}
One of several possibilities:
One of several possibilities:
<lang SPAD>(1) -> integer READ()$Lisp + integer READ()$Lisp
<syntaxhighlight lang="spad">(1) -> integer READ()$Lisp + integer READ()$Lisp
333 444
333 444


(1) 777
(1) 777
Type: PositiveInteger</lang>
Type: PositiveInteger</syntaxhighlight>


Domain:[http://fricas.github.io/api/SExpression.html?highlight=lisp SExpression]
Domain:[http://fricas.github.io/api/SExpression.html?highlight=lisp SExpression]

=={{header|SparForte}}==
As a structured script.
<syntaxhighlight lang="ada">#!/usr/local/bin/spar
pragma annotate( summary, "aplusb" )
@( description, "A+B - in programming contests, classic problem, which is given so" )
@( description, "contestants can gain familiarity with online judging system being used. " )
@( description, "A+B is one of few problems on contests, which traditionally lacks fabula." )
@( description, "Given 2 integer numbers, A and B. One needs to find their sum. " )
@( category, "tutorials" )
@( author, "Ken O. Burtch" )
@( see_also, "http://rosettacode.org/wiki/A%2BB" );
pragma license( unrestricted );

pragma software_model( nonstandard );
pragma restriction( no_external_commands );

procedure aplusb is
s : string;
a : integer;
b : integer;
begin
s := get_line;
a := numerics.value( strings.field( s, 1, ' ' ) );
b := numerics.value( strings.field( s, 2, ' ' ) );
? a+b;
end aplusb;</syntaxhighlight>


=={{header|SPARK}}==
=={{header|SPARK}}==
<lang Ada>-- By Jacob Sparre Andersen
<syntaxhighlight lang="ada">-- By Jacob Sparre Andersen
-- Validates with SPARK GPL 2010's Examiner/Simplifier
-- Validates with SPARK GPL 2010's Examiner/Simplifier


Line 5,078: Line 5,497:
Stop => 0);
Stop => 0);
end if;
end if;
end A_Plus_B;</lang>
end A_Plus_B;</syntaxhighlight>


=={{header|SPL}}==
=={{header|SPL}}==
<lang spl>n = #.split(#.input("Input two numbers, separated by space:")," ")
<syntaxhighlight lang="spl">n = #.split(#.input("Input two numbers, separated by space:")," ")
#.output(n[1],"+",n[2],"=",#.val(n[1])+#.val(n[2]))</lang>
#.output(n[1],"+",n[2],"=",#.val(n[1])+#.val(n[2]))</syntaxhighlight>
{{in}}
{{in}}
<pre>
<pre>
Line 5,094: Line 5,513:


=={{header|SQL}}==
=={{header|SQL}}==
<lang sql>select A+B</lang>
<syntaxhighlight lang="sql">select A+B</syntaxhighlight>
Example:
Example:
<lang sql>select 2+3</lang>
<syntaxhighlight lang="sql">select 2+3</syntaxhighlight>
This should produce a result set containing the value 5.
This should produce a result set containing the value 5.


Line 5,104: Line 5,523:
{{works with|Db2 LUW}}
{{works with|Db2 LUW}}
With SQL only:
With SQL only:
<lang sql pl>
<syntaxhighlight lang="sql pl">


CREATE OR REPLACE FUNCTION splitadd (instring VARCHAR(255))
CREATE OR REPLACE FUNCTION splitadd (instring VARCHAR(255))
Line 5,119: Line 5,538:
return first + second;
return first + second;
END
END
</syntaxhighlight>
</lang>
Output:
Output:
<pre>
<pre>
Line 5,130: Line 5,549:
=={{header|SSEM}}==
=={{header|SSEM}}==
The SSEM has no Add instruction, so we rely on the fact that <i>a</i> + <i>b</i> = -(-<i>a</i> - <i>b</i>).
The SSEM has no Add instruction, so we rely on the fact that <i>a</i> + <i>b</i> = -(-<i>a</i> - <i>b</i>).
<lang ssem>10100000000000100000000000000000 0. -5 to c acc = -A
<syntaxhighlight lang="ssem">10100000000000100000000000000000 0. -5 to c acc = -A
01100000000001010000000000000000 1. Sub. 6 acc -= B
01100000000001010000000000000000 1. Sub. 6 acc -= B
11100000000001100000000000000000 2. c to 7 X = acc
11100000000001100000000000000000 2. c to 7 X = acc
Line 5,137: Line 5,556:
10100100000000000000000000000000 5. 37 A
10100100000000000000000000000000 5. 37 A
00111000000000000000000000000000 6. 28 B
00111000000000000000000000000000 6. 28 B
00000000000000000000000000000000 7. 0 X</lang>
00000000000000000000000000000000 7. 0 X</syntaxhighlight>


=={{header|Standard ML}}==
=={{header|Standard ML}}==
<lang sml>(*
<syntaxhighlight lang="sml">(*
* val split : string -> string list
* val split : string -> string list
* splits a string at it spaces
* splits a string at it spaces
Line 5,161: Line 5,580:
in
in
(sum o List.mapPartial Int.fromString o split) input
(sum o List.mapPartial Int.fromString o split) input
end</lang>
end</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 5,172: Line 5,591:
{{works with|Swift|2}}
{{works with|Swift|2}}
Requires sending EOF.
Requires sending EOF.
<lang Swift>import Foundation
<syntaxhighlight lang="swift">import Foundation


let input = NSFileHandle.fileHandleWithStandardInput()
let input = NSFileHandle.fileHandleWithStandardInput()
Line 5,183: Line 5,602:
let b = (nums[1] as String).toInt()!
let b = (nums[1] as String).toInt()!


print(" \(a + b)")</lang>
print(" \(a + b)")</syntaxhighlight>


{{works with|Swift|3}}
{{works with|Swift|3}}
Line 5,189: Line 5,608:
Swift 4 and no requirement to send EOF (press enter/send newline like you normally would)
Swift 4 and no requirement to send EOF (press enter/send newline like you normally would)


<syntaxhighlight lang="swift">
<lang Swift>
import Foundation
import Foundation


Line 5,204: Line 5,623:


print(" \(a + b)")
print(" \(a + b)")
</syntaxhighlight>
</lang>


=={{header|Symsyn}}==
=={{header|Symsyn}}==
<syntaxhighlight lang="symsyn">
<lang Symsyn>


[] $s
[] $s
Line 5,215: Line 5,634:
y []
y []


</syntaxhighlight>
</lang>


=={{header|Tailspin}}==
=={{header|Tailspin}}==
<lang tailspin>
<syntaxhighlight lang="tailspin">
composer nums
composer nums
[ (<WS>?) <INT> (<WS>) <INT> (<WS>?) ]
[ (<WS>?) <INT> (<WS>) <INT> (<WS>?) ]
Line 5,225: Line 5,644:
$IN::lines -> nums -> $(1) + $(2) -> '$;
$IN::lines -> nums -> $(1) + $(2) -> '$;
' -> !OUT::write
' -> !OUT::write
</syntaxhighlight>
</lang>


Alternatively
Alternatively
<lang tailspin>
<syntaxhighlight lang="tailspin">
composer nums
composer nums
(<WS>?) (def a: <INT>;) (<WS>) <INT> -> $a + $ (<WS>?)
(<WS>?) (def a: <INT>;) (<WS>) <INT> -> $a + $ (<WS>?)
Line 5,235: Line 5,654:
$IN::lines -> nums -> '$;
$IN::lines -> nums -> '$;
' -> !OUT::write
' -> !OUT::write
</syntaxhighlight>
</lang>


=={{header|Tcl}}==
=={{header|Tcl}}==
<lang tcl>scan [gets stdin] "%d %d" x y
<syntaxhighlight lang="tcl">scan [gets stdin] "%d %d" x y
puts [expr {$x + $y}]</lang>
puts [expr {$x + $y}]</syntaxhighlight>
Alternatively:
Alternatively:
<lang tcl>puts [tcl::mathop::+ {*}[gets stdin]]</lang>
<syntaxhighlight lang="tcl">puts [tcl::mathop::+ {*}[gets stdin]]</syntaxhighlight>
To/from a file:
To/from a file:
<lang tcl>set in [open "input.txt"]
<syntaxhighlight lang="tcl">set in [open "input.txt"]
set out [open "output.txt" w]
set out [open "output.txt" w]
scan [gets $in] "%d %d" x y
scan [gets $in] "%d %d" x y
puts $out [expr {$x + $y}]
puts $out [expr {$x + $y}]
close $in
close $in
close $out</lang>
close $out</syntaxhighlight>

=={{header|Terraform}}==
<syntaxhighlight lang="hcl">
#Aamrun, August 15th, 2022

variable "a" {
type = number
}

variable "b" {
type = number
}

output "a_plus_b" {
value = var.a + var.b
}
</syntaxhighlight>
{{out}}
<pre>
$ terraform apply -var="a=136" -var="b=745" -auto-approve

Changes to Outputs:
+ a_plus_b = 881

You can apply this plan to save these new output values to the Terraform state, without changing any real infrastructure.

Apply complete! Resources: 0 added, 0 changed, 0 destroyed.

Outputs:

a_plus_b = 881
$
</pre>


=={{header|TI-83 BASIC}}==
=={{header|TI-83 BASIC}}==
<lang ti83b>:Prompt A,B
<syntaxhighlight lang="ti83b">:Prompt A,B
:Disp A+B</lang>
:Disp A+B</syntaxhighlight>


=={{header|TI-83 Hex Assembly}}==
=={{header|TI-83 Hex Assembly}}==
Line 5,258: Line 5,710:
Note: Comments (after the semicolons) are just for explanation -- TI-83 hex assembly does not allow comments in program source code.
Note: Comments (after the semicolons) are just for explanation -- TI-83 hex assembly does not allow comments in program source code.


<lang ti83b>PROGRAM:APLUSB
<syntaxhighlight lang="ti83b">PROGRAM:APLUSB
:AsmPrgm
:AsmPrgm
:
:
Line 5,274: Line 5,726:
:F7 ; rst FPAdd
:F7 ; rst FPAdd
:EFBF4A ; StoAns
:EFBF4A ; StoAns
:C9 ; ret</lang>
:C9 ; ret</syntaxhighlight>


Store the inputs in the 'A' and 'B' OS variables. Run it with Asm(prgmAPLUSB) and the output will be stored in the Ans OS variable.
Store the inputs in the 'A' and 'B' OS variables. Run it with Asm(prgmAPLUSB) and the output will be stored in the Ans OS variable.


=={{header|TI-89 BASIC}}==
=={{header|TI-89 BASIC}}==
<lang ti89b>:aplusb(a,b)
<syntaxhighlight lang="ti89b">:aplusb(a,b)
:a+b</lang>
:a+b</syntaxhighlight>


=={{header|TorqueScript}}==
=={{header|TorqueScript}}==
Since torque is not compatible with standard input, I will show the closest to that.
Since torque is not compatible with standard input, I will show the closest to that.
It's a function that takes a single string input, that will contain the 2 numbers.
It's a function that takes a single string input, that will contain the 2 numbers.
<lang Torque>Function aPlusB(%input)
<syntaxhighlight lang="torque">Function aPlusB(%input)
{
{
return getWord(%input, 0) + getWord(%input, 1);
return getWord(%input, 0) + getWord(%input, 1);
}</lang>
}</syntaxhighlight>


=={{header|Transd}}==
=={{header|Transd}}==
<lang scheme>#lang transd
<syntaxhighlight lang="scheme">#lang transd


MainModule : {
MainModule : {
Line 5,297: Line 5,749:
b: Int(),
b: Int(),
_start: (lambda (textout (+ (read a) (read b))))
_start: (lambda (textout (+ (read a) (read b))))
}</lang>
}</syntaxhighlight>


=={{header|TSE SAL}}==
=={{header|TSE SAL}}==
<syntaxhighlight lang="tsesal">
<lang TSESAL>
INTEGER PROC FNMathGetSumAPlusBI( INTEGER A, INTEGER B )
INTEGER PROC FNMathGetSumAPlusBI( INTEGER A, INTEGER B )
RETURN( A + B )
RETURN( A + B )
Line 5,312: Line 5,764:
Message( FNMathGetSumAPlusBI( Val( s1 ), Val( s2 ) ) ) // gives e.g. 5
Message( FNMathGetSumAPlusBI( Val( s1 ), Val( s2 ) ) ) // gives e.g. 5
END
END
</syntaxhighlight>
</lang>
{{out}} <pre>
{{out}} <pre>
output
output
Line 5,319: Line 5,771:


=={{header|TUSCRIPT}}==
=={{header|TUSCRIPT}}==
<lang tuscript>$$ MODE TUSCRIPT
<syntaxhighlight lang="tuscript">$$ MODE TUSCRIPT
SET input="1 2"
SET input="1 2"
SET input=SPLIT(input,": :")
SET input=SPLIT(input,": :")
SET input=JOIN (input)
SET input=JOIN (input)
SET output=SUM(input)</lang>
SET output=SUM(input)</syntaxhighlight>


=={{header|TXR}}==
=={{header|TXR}}==
Line 5,340: Line 5,792:
=={{header|UNIX Shell}}==
=={{header|UNIX Shell}}==
{{works with|Bourne Shell}}
{{works with|Bourne Shell}}
<lang sh>#!/bin/sh
<syntaxhighlight lang="sh">#!/bin/sh
read a b || exit
read a b || exit
echo `expr "$a" + "$b"`</lang>
echo `expr "$a" + "$b"`</syntaxhighlight>


{{works with|bash}}
{{works with|bash}}
Line 5,349: Line 5,801:
{{works with|zsh}}
{{works with|zsh}}
Script "a+b.sh":
Script "a+b.sh":
<lang bash>#!/bin/bash
<syntaxhighlight lang="bash">#!/bin/bash
read a b || exit
read a b || exit
echo $(( a + b ))</lang>
echo $(( a + b ))</syntaxhighlight>
{{Out}}
{{Out}}
<lang bash>echo 2 3 | ksh a+b.sh
<syntaxhighlight lang="bash">echo 2 3 | ksh a+b.sh
5</lang>
5</syntaxhighlight>


One liner :
One liner :


<lang bash>
<syntaxhighlight lang="bash">
a=0;b=0;read a;read b;echo "Sum of $a and $b is "$((a+b))
a=0;b=0;read a;read b;echo "Sum of $a and $b is "$((a+b))
</syntaxhighlight>
</lang>
Sample run :
Sample run :
<pre>
<pre>
Line 5,369: Line 5,821:


==={{header|C Shell}}===
==={{header|C Shell}}===
<lang csh>set line=$<
<syntaxhighlight lang="csh">set line=$<
set input=($line)
set input=($line)
@ sum = $input[1] + $input[2]
@ sum = $input[1] + $input[2]
echo $sum</lang>
echo $sum</syntaxhighlight>


=={{header|Ursa}}==
=={{header|Ursa}}==
<lang>#
<syntaxhighlight lang="text">#
# a + b
# a + b
#
#
Line 5,389: Line 5,841:


# output the sum
# output the sum
out sum endl console</lang>
out sum endl console</syntaxhighlight>


=={{header|Ultimate++}}==
=={{header|Ultimate++}}==


<syntaxhighlight lang="cpp">
<lang Cpp>
#include <Core/Core.h>
#include <Core/Core.h>
#include <stdio.h>
#include <stdio.h>
Line 5,414: Line 5,866:




</syntaxhighlight>
</lang>




=={{header|Ursala}}==
=={{header|Ursala}}==
Using standard input and output streams:
Using standard input and output streams:
<lang Ursala>#import std
<syntaxhighlight lang="ursala">#import std
#import int
#import int


#executable&
#executable&


main = %zP+ sum:-0+ %zp*FiNCS+ sep` @L</lang>
main = %zP+ sum:-0+ %zp*FiNCS+ sep` @L</syntaxhighlight>
Overwriting a text file named as a command line parameter:
Overwriting a text file named as a command line parameter:
<lang Ursala>#import std
<syntaxhighlight lang="ursala">#import std
#import int
#import int


#executable -[parameterized]-
#executable -[parameterized]-


main = ~command.files.&h; <.contents:= %zP+ sum:-0+ %zp*FiNCS+ sep` @L+ ~contents></lang>
main = ~command.files.&h; <.contents:= %zP+ sum:-0+ %zp*FiNCS+ sep` @L+ ~contents></syntaxhighlight>
Creating a new file named after the input file with suffix <code>.out</code>:
Creating a new file named after the input file with suffix <code>.out</code>:
<lang Ursala>#import std
<syntaxhighlight lang="ursala">#import std
#import int
#import int


Line 5,442: Line 5,894:
~command.files.&h; ~&iNC+ file$[
~command.files.&h; ~&iNC+ file$[
contents: %zP+ sum:-0+ %zp*FiNCS+ sep` @L+ ~contents,
contents: %zP+ sum:-0+ %zp*FiNCS+ sep` @L+ ~contents,
path: ~path; ^|C\~& ~=`.-~; ^|T/~& '.out'!]</lang>
path: ~path; ^|C\~& ~=`.-~; ^|T/~& '.out'!]</syntaxhighlight>


=={{header|Vala}}==
=={{header|Vala}}==
Read from stdin while program running:
Read from stdin while program running:
<lang vala>Using GLib;
<syntaxhighlight lang="vala">Using GLib;


int main (string[] args) {
int main (string[] args) {
Line 5,456: Line 5,908:
return 0;
return 0;
}
}
</syntaxhighlight>
</lang>


=={{header|VBA}}==
=={{header|VBA}}==
A simple version:
A simple version:
<lang VBA>Sub AplusB()
<syntaxhighlight lang="vba">Sub AplusB()
Dim s As String, t As Variant, a As Integer, b As Integer
Dim s As String, t As Variant, a As Integer, b As Integer
s = InputBox("Enter two numbers separated by a space")
s = InputBox("Enter two numbers separated by a space")
Line 5,467: Line 5,919:
b = CInt(t(1))
b = CInt(t(1))
MsgBox a + b
MsgBox a + b
End Sub</lang>
End Sub</syntaxhighlight>
An other version:
An other version:
<lang VBA>Sub Rosetta_AB()
<syntaxhighlight lang="vba">Sub Rosetta_AB()
Dim stEval As String
Dim stEval As String
stEval = InputBox("Enter two numbers, separated only by a space", "Rosetta Code", "2 2")
stEval = InputBox("Enter two numbers, separated only by a space", "Rosetta Code", "2 2")
Line 5,475: Line 5,927:
"VBA converted this input to " & Replace(stEval, " ", "+") & vbCr & vbCr & _
"VBA converted this input to " & Replace(stEval, " ", "+") & vbCr & vbCr & _
"And evaluated the result as " & Evaluate(Replace(stEval, " ", "+")), vbInformation + vbOKOnly, "XLSM"
"And evaluated the result as " & Evaluate(Replace(stEval, " ", "+")), vbInformation + vbOKOnly, "XLSM"
End Sub</lang>
End Sub</syntaxhighlight>


=={{header|VBScript}}==
=={{header|VBScript}}==
A simple version:
A simple version:
<lang vb>s=InputBox("Enter two numbers separated by a blank")
<syntaxhighlight lang="vb">s=InputBox("Enter two numbers separated by a blank")
t=Split(s)
t=Split(s)
a=CInt(t(0))
a=CInt(t(0))
b=CInt(t(1))
b=CInt(t(1))
c=a+b
c=a+b
MsgBox c </lang>
MsgBox c </syntaxhighlight>
An other version:
An other version:
<lang vb>Option Explicit
<syntaxhighlight lang="vb">Option Explicit
Dim a, b
Dim a, b
Select Case WScript.Arguments.Count
Select Case WScript.Arguments.Count
Line 5,522: Line 5,974:
.Close
.Close
End With
End With
end if</lang>
end if</syntaxhighlight>

=={{header|Vedit macro language}}==
This version implements the task as specified in the task description.
<syntaxhighlight lang="vedit">// Input two values on single line in text format
Get_Input(10, "Enter two integers separated by a space: ")

// Extract two numeric values from the text
Buf_Switch(Buf_Free)
Reg_Ins(10)
BOF
#1 = Num_Eval(ADVANCE)
#2 = Num_Eval()
Buf_Quit(OK)

// Calculate and display the results
Num_Type(#1 + #2)</syntaxhighlight>

A simpler version that prompts for the two numbers separately:
<syntaxhighlight lang="vedit">#1 = Get_Num("Enter number A: ")
#2 = Get_Num("Enter number B: ")
Num_Type(#1 + #2)</syntaxhighlight>


=={{header|Verilog}}==
=={{header|Verilog}}==
<lang Verilog>module TEST;
<syntaxhighlight lang="verilog">module TEST;


reg signed [11:0] y;
reg signed [11:0] y;
Line 5,543: Line 6,016:
endfunction
endfunction
endmodule</lang>
endmodule</syntaxhighlight>


=={{header|VHDL}}==
=={{header|VHDL}}==
<lang VHDL>LIBRARY std;
<syntaxhighlight lang="vhdl">LIBRARY std;
USE std.TEXTIO.all;
USE std.TEXTIO.all;


Line 5,568: Line 6,041:
wait; -- needed to stop the execution
wait; -- needed to stop the execution
end process;
end process;
end architecture beh;</lang>
end architecture beh;</syntaxhighlight>


=={{header|Visual Basic .NET}}==
=={{header|Visual Basic .NET}}==
<lang vbnet>Module Module1
<syntaxhighlight lang="vbnet">Module Module1


Sub Main()
Sub Main()
Line 5,580: Line 6,053:
End Sub
End Sub


End Module</lang>
End Module</syntaxhighlight>


=={{header|Vlang}}==
=={{header|V (Vlang)}}==
<lang go>import os
<syntaxhighlight lang="go">import os


fn main() {
fn main() {
Line 5,597: Line 6,070:
println('$a + $b = ${a+b}')
println('$a + $b = ${a+b}')
}</lang>
}</syntaxhighlight>
Read from stdin
Read from stdin
{{out}}
{{out}}
Line 5,607: Line 6,080:


=={{header|Wee Basic}}==
=={{header|Wee Basic}}==
<lang Wee Basic>Print 1 "Enter number A:"
<syntaxhighlight lang="wee basic">Print 1 "Enter number A:"
input a
input a
Print 1 "Enter number B:"
Print 1 "Enter number B:"
Line 5,613: Line 6,086:
let c=a+b
let c=a+b
print 1 c
print 1 c
end</lang>
end</syntaxhighlight>


=={{header|Whitespace}}==
=={{header|Whitespace}}==
<lang whitespace>
<syntaxhighlight lang="whitespace">
Line 5,628: Line 6,101:




</syntaxhighlight>
</lang>


=={{header|Wisp}}==
=={{header|Wisp}}==
{{trans|Scheme}}
{{trans|Scheme}}
<lang scheme>
<syntaxhighlight lang="scheme">
display : + (read) (read)
display : + (read) (read)


Line 5,639: Line 6,112:
315
315
;; displays 629
;; displays 629
</syntaxhighlight>
</lang>


=={{header|Wren}}==
=={{header|Wren}}==
<lang ecmascript>import "io" for Stdin, Stdout
<syntaxhighlight lang="wren">import "io" for Stdin, Stdout


while (true) {
while (true) {
Line 5,656: Line 6,129:
return
return
}
}
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 5,667: Line 6,140:
=={{header|X86 Assembly}}==
=={{header|X86 Assembly}}==
{{works with|NASM|Linux}}
{{works with|NASM|Linux}}
<lang asm>section .text
<syntaxhighlight lang="asm">section .text
global _start
global _start
Line 5,726: Line 6,199:
a resd 1
a resd 1
b resd 1
b resd 1
sum resd 1</lang>
sum resd 1</syntaxhighlight>
This will not work on numbers over 0(from 1 to 0). This is due to the fact, numbers higher than 0(10,11, etc) are in fact strings when taken from the keyboard. A much longer conversion code is required to loop through and treat each number in the string as separate numbers. For example, The number '10' would have to be treated as a 1 and a 0.
This will not work on numbers over 0(from 1 to 0). This is due to the fact, numbers higher than 0(10,11, etc) are in fact strings when taken from the keyboard. A much longer conversion code is required to loop through and treat each number in the string as separate numbers. For example, The number '10' would have to be treated as a 1 and a 0.


=={{header|XBS}}==
=={{header|XBS}}==
Since XBS is written in Javascript, we have to use the Javascript prompt function to get inputs.
Since XBS is written in Javascript, we have to use the Javascript prompt function to get inputs.
<lang xbs>const Amount:number = toint(window.prompt("Input an amount"));
<syntaxhighlight lang="xbs">const Amount:number = toint(window.prompt("Input an amount"));
set Stream = [];
set Stream = [];
<|(*1..Amount)=>Stream.push(window.prompt("Input a number"));
<|(*1..Amount)=>Stream.push(window.prompt("Input a number"));
Line 5,738: Line 6,211:
set Result = 0;
set Result = 0;
<|(*Inputs)Result+=_;
<|(*Inputs)Result+=_;
log(Result);</lang>
log(Result);</syntaxhighlight>
{{out}}
{{out}}
If we input an amount of "2", then input "1" and "2", the output will be "3".
If we input an amount of "2", then input "1" and "2", the output will be "3".
Line 5,746: Line 6,219:


=={{header|xEec}}==
=={{header|xEec}}==
<lang xEec>i# i# ma h#10 r o# p o$ p</lang>
<syntaxhighlight lang="xeec">i# i# ma h#10 r o# p o$ p</syntaxhighlight>


=={{header|XLISP}}==
=={{header|XLISP}}==
<lang xlisp>(DEFUN A-PLUS-B ()
<syntaxhighlight lang="xlisp">(DEFUN A-PLUS-B ()
(DISPLAY "Enter two numbers separated by a space.")
(DISPLAY "Enter two numbers separated by a space.")
(NEWLINE)
(NEWLINE)
Line 5,755: Line 6,228:
(DEFINE A (READ))
(DEFINE A (READ))
(DEFINE B (READ))
(DEFINE B (READ))
(+ A B))</lang>
(+ A B))</syntaxhighlight>
{{out}}
{{out}}
<pre>(A-PLUS-B)
<pre>(A-PLUS-B)
Line 5,764: Line 6,237:


=={{header|Xojo}}==
=={{header|Xojo}}==
<lang xojo>var inp as string
<syntaxhighlight lang="xojo">var inp as string
var strVals() as string
var strVals() as string


Line 5,790: Line 6,263:
exit
exit
loop
loop
</syntaxhighlight>
</lang>


=={{header|XPL0}}==
=={{header|XPL0}}==
<lang XPL0>include c:\cxpl\codes;
<syntaxhighlight lang="xpl0">include c:\cxpl\codes;
int A, B;
int A, B;
[A:= IntIn(0);
[A:= IntIn(0);
Line 5,799: Line 6,272:
IntOut(0, A+B);
IntOut(0, A+B);
CrLf(0);
CrLf(0);
]</lang>
]</syntaxhighlight>


=={{header|XQuery}}==
=={{header|XQuery}}==
<lang xquery>
<syntaxhighlight lang="xquery">
(:
(:
Using the EXPath File Module, which is built into most XQuery processors
Using the EXPath File Module, which is built into most XQuery processors
Line 5,818: Line 6,291:
let $result := xs:numeric($numbers[1]) + xs:numeric($numbers[2])
let $result := xs:numeric($numbers[1]) + xs:numeric($numbers[2])
return file:write-text($out, xs:string($result))
return file:write-text($out, xs:string($result))
</syntaxhighlight>
</lang>


=={{header|Yabasic}}==
=={{header|Yabasic}}==
<lang Yabasic>repeat
<syntaxhighlight lang="yabasic">repeat
input "Enter two numbers (betwen -1000 ... +1000): " a, b
input "Enter two numbers (betwen -1000 ... +1000): " a, b
until(valid(a) and valid(b))
until(valid(a) and valid(b))
Line 5,828: Line 6,301:
sub valid(x)
sub valid(x)
return x >= -1000 and x <= 1000
return x >= -1000 and x <= 1000
end sub</lang>
end sub</syntaxhighlight>


=={{header|Yorick}}==
=={{header|Yorick}}==
<lang yorick>a = b = 0;
<syntaxhighlight lang="yorick">a = b = 0;
read, a, b;
read, a, b;
write, a + b;</lang>
write, a + b;</syntaxhighlight>


=={{header|ZED}}==
=={{header|ZED}}==
Source -> http://ideone.com/WLtEfe
Source -> http://ideone.com/WLtEfe
Compiled -> http://ideone.com/fMt6ST
Compiled -> http://ideone.com/fMt6ST
<lang zed>(A+B)
<syntaxhighlight lang="zed">(A+B)
comment:
comment:
#true
#true
Line 5,851: Line 6,324:
comment:
comment:
#true
#true
(001) "read"</lang>
(001) "read"</syntaxhighlight>


=={{header|zkl}}==
=={{header|zkl}}==
<lang zkl>do(2){ask("A B: ").split(" ").filter().sum().println()}</lang>
<syntaxhighlight lang="zkl">do(2){ask("A B: ").split(" ").filter().sum().println()}</syntaxhighlight>
<pre>
<pre>
A B: 123 567
A B: 123 567
Line 5,864: Line 6,337:


=={{header|Zoea}}==
=={{header|Zoea}}==
<lang Zoea>program: a_plus_b
<syntaxhighlight lang="zoea">program: a_plus_b
input: '7 11'
input: '7 11'
output: 18
output: 18
</syntaxhighlight>
</lang>


=={{header|Zoea Visual}}==
=={{header|Zoea Visual}}==
Line 5,873: Line 6,346:


=={{header|zonnon}}==
=={{header|zonnon}}==
<lang zonnon>
<syntaxhighlight lang="zonnon">
module ABProblem;
module ABProblem;
var
var
Line 5,881: Line 6,354:
writeln(a+b)
writeln(a+b)
end ABProblem.
end ABProblem.
</syntaxhighlight>
</lang>
<pre>
<pre>
1 2
1 2
Line 5,888: Line 6,361:


=={{header|ZX Spectrum Basic}}==
=={{header|ZX Spectrum Basic}}==
<lang zxbasic>10 PRINT "Input two numbers separated by"'"space(s) "
<syntaxhighlight lang="zxbasic">10 PRINT "Input two numbers separated by"'"space(s) "
20 INPUT LINE a$
20 INPUT LINE a$
30 GO SUB 90
30 GO SUB 90
Line 5,897: Line 6,370:
80 REM LTrim operation
80 REM LTrim operation
90 IF a$(1)=" " THEN LET a$=a$(2 TO ): GO TO 90
90 IF a$(1)=" " THEN LET a$=a$(2 TO ): GO TO 90
100 RETURN</lang>
100 RETURN</syntaxhighlight>


Another solution
Another solution


<lang zxbasic>10 PRINT "Input two numbers separated by"'"space(s) "
<syntaxhighlight lang="zxbasic">10 PRINT "Input two numbers separated by"'"space(s) "
20 INPUT LINE a$
20 INPUT LINE a$
30 LET ll=10e10: LET ls=0: LET i=1
30 LET ll=10e10: LET ls=0: LET i=1
Line 5,909: Line 6,382:
70 LET i=i+1: GO TO 40
70 LET i=i+1: GO TO 40
80 LET a=VAL a$( TO i): LET b=VAL a$(i TO )
80 LET a=VAL a$( TO i): LET b=VAL a$(i TO )
90 PRINT a;" + ";b;" = ";a+b</lang>
90 PRINT a;" + ";b;" = ";a+b</syntaxhighlight>


<pre>
<pre>

Revision as of 13:29, 5 April 2024

Task
A+B
You are encouraged to solve this task according to the task description, using any language you may know.

A+B   ─── a classic problem in programming contests,   it's given so contestants can gain familiarity with the online judging system being used.


Task

Given two integers,   A and B.

Their sum needs to be calculated.


Input data

Two integers are written in the input stream, separated by space(s):


Output data

The required output is one integer:   the sum of A and B.


Example
input   output  
2 2 4
3 2 5



0815

|x|+%

11l

Translation of: Python
print(sum(input().split(‘ ’, group_delimiters' 1B).map(i -> Int(i))))

360 Assembly

*        A+B                       29/08/2015
APLUSB   CSECT
         USING  APLUSB,R12
         LR     R12,R15
         OPEN   (MYDATA,INPUT)
LOOP     GET    MYDATA,PG          read a single record
         XDECI  R4,PG              input A, in register 4
         XDECI  R5,PG+12           input B, in register 5
         AR     R4,R5              A+B, add register 5 to register 4, R4=R4+R
         XDECO  R4,PG+24           edit A+B
         XPRNT  PG,36              print A+B
         B      LOOP               repeat     
ATEND    CLOSE  MYDATA
RETURN   XR     R15,R15
         BR     R14
         LTORG
MYDATA   DCB    LRECL=24,RECFM=FT,EODAD=ATEND,DDNAME=MYFILE
PG       DS     CL24               record
         DC     CL12' '
         YREGS
         END    APLUSB
Input:
          27          53
         123         321
         999           1
Output:
          27          53          80
         123         321         444
         999           1        1000

8th

gets dup . space eval n:+ . cr

8080 Assembly

As often happens with assembly of any kind, dealing with the I/O requirements turns the whole task into a grand tour of the language and environment, as one needs to read and parse decimal numbers, and then write back another decimal number. But simple addition is easy, even 16-bit addition. The 8080 is otherwise an 8-bit processor, but it includes a 16-bit add instruction (and only an add, not even a subtract), namely dad (for "double add"), which can take four forms:

	dad	b	; HL += BC (i.e., add BC reg pair to HL reg pair)
	dad	d	; HL += DE
	dad	h	; HL += HL (also known as "mul HL by two")
	dad	sp	; HL += SP (actually the only way to get at SP at all)

Merely doing A+B, with 16-bit numbers so that will fit, would look like this:

	lxi	h,123
	lxi	d,456
	dad	d
	; HL is now 579

Then, the following is what is required to wrap it all in a CP/M command line utility. Computers based on the 8080 (or processors that are backwards compatible with it, such as the 8085 and Z80) usually ran the CP/M operating system (or something that is backwards compatible with it, such as MSX-DOS or ZSDOS). This program assembles to an 128-byte binary, which fits exactly in one CP/M block.

fcb1n:	equ	5Ch+1	; "Filename" in first FCB
fcb2n:	equ	6Ch+1	; "Filename" in second FCB
puts:	equ	9	; CP/M call to write string to console
bdos:	equ	5	; CP/M syscall address
	org	100h
	lxi	d,fcb1n	; Get first "file name" (i.e, first number on cmdline)
	call	parse	; Parse it
	push	h	; Store the number on the stack
	lxi	d,fcb2n	; Get the second one
	call	parse	; Parse that one too
	pop	d	; Retrieve our first number and put it in DE
	dad	d 	; <-- add DE to HL, giving our answer, then fall into:
	;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
	;;;	Routine: print the signed integer in HL. 		    ;;;
	;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
puthl:	mov	a,h	; Get the sign bit of the integer,
	ral		; which is the top bit of the high byte
	sbb	a	; A=00 if positive, FF if negative
	sta	negf	; Store it as the negative flag
	cnz	neghl	; And if HL was negative, make it positive
	lxi	d,num	; Load pointer to end of number string
	push	d	; Onto the stack
	lxi	b,-10	; Divide by ten (by trial subtraction)
digit:	lxi	d,-1	; DE = quotient. There is no 16-bit subtraction,
dgtdiv:	dad	b	; so we just add a negative value,
	inx	d
	jc	dgtdiv	; while that overflows.
	mvi	a,'0'+10	; The loop runs once too much so we're 10 out
	add	l 	; The remainder (minus 10) is in L
	xthl		; Swap HL with top of stack (i.e., the string pointer)
	dcx	h	; Go back one byte
	mov	m,a	; And store the digit
	xthl		; Put the pointer back on the stack
	xchg		; Do all of this again with the quotient
	mov	a,h	; If it is zero, we're done
	ora	l
	jnz	digit	; But if not, there are more digits
	mvi	c,puts	; Prepare to call CP/M and print the string
	pop	d	; Put the string pointer from the stack in DE
	lda	negf	; See if the number was supposed to be negative
	inr	a
	jnz	bdos	; If not, print the string we have and return
	dcx	d	; But if so, we need to add a minus in front
	mvi	a,'-'
	stax	d
	jmp	bdos	; And only then print the string
	;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
	;;;	Routine: parse (possibly negative) 16-bit integer at [DE],  ;;;
	;;;	result in HL.                                               ;;;
	;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
parse:	lxi	h,negf	; Zero out the negative flag
	mvi	m,0
	ldax	d	; Get first byte of number string
	cpi	'-'	; If minus, it should be negative
	jnz	prspos	; If not, parse as positive number
	inr	m	; Set negative flag
	inx	d	; The actual number starts one byte further on
prspos:	lxi	h,0	; Set our 16-bit accumulator to zero
prsdgt:	ldax	d	; Get current digit
	sui	'0'	; It's ASCII, so subtract '0'
	cpi	10	; Check if it is a valid digit (<10)
	jnc	prsdon	; If not, that was the last character, we're done
	dad	h	; Multiply accumulator by ten
	mov	b,h	; There is no MUL instruction, but 10*HL = 5*(2*HL),
	mov	c,l	; = 2*HL + 8*HL. BC=2*HL
	dad	h	; HL *= 2
	dad	h	; HL *= 2
	dad	b	; HL += BC
	mov	c,a	; Then, add the digit, extended to 16 bits
	mvi	b,0	; by setting the top byte to zero.
	dad	b
	inx	d	; Then, get the next digit
	jmp	prsdgt
prsdon:	lda	negf	; Check if the result was supposed to be negative
	dcr	a
	rnz		; If not, we're done, otherwise, fall through into...
	;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
	;;;	Routine: negate the 16-bit integer in HL. 		    ;;;
	;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
neghl:	mov	a,h	; HL = -HL; i.e. HL = (~HL) + 1
	cma		; Get bitwise complement of the high byte,
	mov	h,a
	mov	a,l	; And the low byte
	cma		; We have to do it byte for byte since it is an 8-bit
	mov	l,a	; processor.
	inx	h	; Then add one
	ret		
negf:	db	0	; Space for negative flag
	db	'-00000'
num:	db	'$'	; Space for number
Output:
A>add 10 10
20
A>add 10 -5
5
A>add -1000 1000
0
A>add -1234 5678
4444


AArch64 Assembly

Works with: as version Raspberry Pi 3B version Buster 64 bits
/* ARM assembly AARCH64 Raspberry PI 3B */
/*  program addAetB.s   */

/*******************************************/
/* Constantes                              */
/*******************************************/
.equ STDOUT, 1                // linux output
.equ WRITE,  64               // call system Linux 64 bits 
.equ EXIT,   93               // call system Linux 64 bits 

/*******************************************/
/* Initialized data                        */
/*******************************************/
.data
szMessError:     .asciz "Error : addAetB <number1> <number2>\n"
szMessResult:  .asciz "Result = "
szRetourLigne: .asciz "\n"
/*******************************************/
/* Uninitialized data                       */
/*******************************************/
.bss
sZoneConv:                   .skip 100
.text
.global main 
main:
    mov fp,sp                     // fp <- adresse début
    ldr x0,[fp]                   // load parameters number in command line
    cmp x0,3                      // number in command line
    blt 99f                       // no -> error
    ldr x0,[fp,16]                // recup address of number 1 in command line
    bl conversionAtoD             // convert string in number in registre x0
    mov x1,x0                     // save number1
    ldr x0,[fp,24]                // recup address of number 2 in command line
    bl conversionAtoD             // convert string in number in registre x0
    mov x2,x0                     // save number2
 
    add x0,x1,x2                  // addition number1 number2
    ldr x1,qAdrsZoneConv
    bl conversion10S              // result decimal conversion
    ldr x0,qAdrszMessResult
    bl affichageMess              // call function display
    ldr x0,qAdrsZoneConv
    bl affichageMess              // call function display
    ldr x0, qAdrszRetourLigne
    bl affichageMess
    mov x0,0                      // return code OK
    b 100f
99:
    ldr x0, qAdrszMessError       // adresse of message
    bl affichageMess              // call function
    mov x0,1                      // return code error
100:                              // standard end programm
    mov x8,EXIT                   // request to exit program
    svc 0                         // perform the system call
qAdrszMessError:             .quad szMessError
qAdrszMessResult:            .quad szMessResult
qAdrsZoneConv:               .quad sZoneConv
qAdrszRetourLigne:           .quad szRetourLigne
/******************************************************************/
/*     String display with  size compute                          */ 
/******************************************************************/
/* x0 contains string address (string ended with zero binary) */
affichageMess:
    stp x0,x1,[sp,-16]!        // save  registers
    stp x2,x8,[sp,-16]!        // save  registers
    mov x2,0                   // size counter
1:                             // loop start
    ldrb w1,[x0,x2]            // load a byte
    cbz w1,2f                  // if zero -> end string
    add x2,x2,#1               // else increment counter
    b 1b                       // and loop
2:                             // x2 =  string size
    mov x1,x0                  // string address
    mov x0,STDOUT              // output Linux standard
    mov x8,WRITE               // code call system "write"
    svc 0                      // call systeme Linux
    ldp x2,x8,[sp],16          // restaur  2 registres
    ldp x0,x1,[sp],16          // restaur  2 registres
    ret                        // retour adresse lr x30
/******************************************************************/
/*     Decimal conversion signed                             */ 
/******************************************************************/
/* x0 contains the value  */
/* x1 contains the address of receiving area  length >= 21 */
/* the receiving area return a string ascii left aligned */
/* et avec un zero final */
/* x0 return length string whitout zero final  */
.equ LGZONECONV,   21
conversion10S:
    stp x5,lr,[sp,-16]!        // save  registers
    stp x3,x4,[sp,-16]!        // save  registers
    stp x1,x2,[sp,-16]!        // save  registers
    cmp x0,0                   // is negative ?
    bge 11f                    // no 
    mov x3,'-'                 // yes
    neg x0,x0                  // number inversion 
    b 12f
11:
    mov x3,'+'                 // positive number
12:
    strb w3,[x1]
    mov x4,#LGZONECONV         // position last digit
    mov x5,#10                 // decimal conversion 
1:                             // loop conversion start
    mov x2,x0                  // copy starting number or successive quotients
    udiv x0,x2,x5              // division by ten
    msub x3,x0,x5,x2           //compute remainder
    add x3,x3,#48              // conversion ascii
    sub x4,x4,#1               // previous position
    strb w3,[x1,x4]            // store digit
    cbnz x0,1b                 // end if quotient = zero

    mov x2,LGZONECONV          // compute string length (21 - dernière position)
    sub x0,x2,x4               // no instruction rsb in 64 bits !!!
                               // move result to area begin
    cmp x4,1
    beq 3f                     // full area ?
    mov x2,1                   // no -> begin area 
2:    
    ldrb w3,[x1,x4]            // load a digit
    strb w3,[x1,x2]            // and store at begin area
    add x4,x4,#1               // last position
    add x2,x2,#1               // et begin last postion
    cmp x4,LGZONECONV - 1      // end ?
    ble 2b                     // no -> loop 
3: 
    mov w3,0
    strb w3,[x1,x2]            // zero final
    add x0,x0,1                // string length must take into account the sign
100:
    ldp x1,x2,[sp],16          // restaur  2 registers
    ldp x3,x4,[sp],16          // restaur  2 registers
    ldp x5,lr,[sp],16          // restaur  2 registers
    ret                        // return address lr x30
/******************************************************************/
/*     conversion ascii string to number                          */ 
/******************************************************************/
/* x0 contains string address ended by 0x0 or 0xA */
/* x0 return the number  */ 
conversionAtoD:
    stp x5,lr,[sp,-16]!        // save  registers
    stp x3,x4,[sp,-16]!        // save  registers
    stp x1,x2,[sp,-16]!        // save  registers
    mov x1,#0
    mov x2,#10             // factor ten
    mov x4,x0              // save address in x4
    mov x3,#0              // positive signe by default
    mov x0,#0              // init résult to zéro
    mov x5,#0
1:                         // loop to remove space at begin of string
    ldrb w5,[x4],1         // load in w5 string octet 
    cbz w5,100f            // string end -> end routine
    cmp w5,#0x0A           // string end -> end routine
    beq 100f
    cmp w5,#' '            // space ?
    beq 1b                 // yes -> loop
2:
    cmp x5,#'-'            // first character is -
    bne 3f
    mov x3,#1              // negative number
    b 4f                   // previous position
3:                         // begin loop compute digit
    cmp x5,#'0'            // character not a digit
    blt 4f
    cmp x5,#'9'            // character not a digit
    bgt 4f
                           // character is a digit
    sub w5,w5,#48

    mul x0,x2,x0           // multiply last result by factor
    smulh x1,x2,x0         // hight 
    cbnz x1,99f            // overflow ?
    add x0,x0,x5           // no -> add to result
4:
    ldrb w5,[x4],1         // load new octet and increment to one
    cbz w5,5f              // string end -> end routine
    cmp w5,#0xA            // string end ?
    bne 3b                 // no -> loop
5:
    cmp x3,#1              // test register x3 for signe
    cneg x0,x0,eq          // if equal egal negate value
    cmn x0,0               // carry to zero no error
    b 100f
99:                        // overflow
    adr x0,szMessErrDep
    bl  affichageMess
    cmp x0,0               // carry to one  error
    mov x0,#0              // if error return zéro
100:
    ldp x1,x2,[sp],16      // restaur  2 registers
    ldp x3,x4,[sp],16      // restaur  2 registers
    ldp x5,lr,[sp],16      // restaur  2 registers
    ret                    // retur address lr x30
szMessErrDep:      .asciz "Number too large: overflow of 64 bits. :\n"
.align 4                   // instruction to realign the following routines

ABAP

report z_sum_a_b.
data: lv_output type i.
selection-screen begin of block input.
  parameters:
    p_first type i,
    p_second type i.
selection-screen end of block input.

at selection-screen output.
  %_p_first_%_app_%-text  = 'First Number: '.
  %_p_second_%_app_%-text = 'Second Number: '.

start-of-selection.
  lv_output = p_first + p_second.
  write : / lv_output.

Acornsoft Lisp

Translation of: Common Lisp
Evaluate: (print (plus (read) (read)))
3 2
5

Action!

BYTE FUNC Find(CHAR ARRAY s CHAR c BYTE POINTER err)
  BYTE i
  FOR i=1 TO s(0)
  DO
    IF s(i)=c THEN
      err^=0 RETURN (i)
    FI
  OD
  err^=1
RETURN (0)

INT FUNC Decode(CHAR ARRAY s BYTE start,stop BYTE POINTER err)
  CHAR ARRAY tmp(20),tmp2(20)
  INT value

  IF s(start)='+ THEN
    start==+1
  FI
  SCopyS(tmp,s,start,stop)
  value=ValI(tmp)
  
  ;Check if conversion failed
  IF value=0 AND s(start)#'0 THEN
    err^=1 RETURN (0)
  FI

  ;Check if value is out of range
  IF value<-1000 OR value>1000 THEN
    err^=1 RETURN (0)
  FI

  err^=0
RETURN (value)

PROC Main()
  CHAR ARRAY s(20)
  BYTE pos,err,err2,value
  INT a,b,sum

  DO
    PrintE("Enter two integer numbers between -1000 and 1000, separated by a space or Q for quit")
    InputS(s)
    IF s(0)=1 AND (s(1)='Q OR s(1)='q) THEN
      EXIT
    FI
  
    pos=Find(s,' ,@err)
    IF err=0 THEN
      a=Decode(s,1,pos-1,@err)
      b=Decode(s,pos+1,s(0),@err2)
      err=err OR err2
    FI

    IF err=0 THEN
      sum=a+b
      PrintF("Their sum is %I%E",sum)
    ELSE
      PrintE("Invalid input!")
    FI
    PutE();
  OD
RETURN
Output:

Screenshot from Atari 8-bit computer

Enter two integer numbers between -1000 and 1000, separated by a space or Q for quit
-320 547
Their sum is 227

Enter two integer numbers between -1000 and 1000, separated by a space or Q for quit
512 -1234
Invalid input!

Enter two integer numbers between -1000 and 1000, separated by a space or Q for quit

Ada

-- Standard I/O Streams

with Ada.Integer_Text_Io;
procedure APlusB is
   A, B : Integer;
begin
   Ada.Integer_Text_Io.Get (Item => A);
   Ada.Integer_Text_Io.Get (Item => B);
   Ada.Integer_Text_Io.Put (A+B);
end APlusB;

Using appropriate user defined types:

with Ada.Text_IO;

procedure A_Plus_B is
   type Small_Integers is range -2_000 .. +2_000;
   subtype Input_Values is Small_Integers range -1_000 .. +1_000;
   package IO is new Ada.Text_IO.Integer_IO (Num => Small_Integers);
   A, B : Input_Values;
begin
   IO.Get (A);
   IO.Get (B);
   IO.Put (A + B, Width => 4, Base => 10);
end A_Plus_B;

Agena

Tested with Agena 2.9.5 Win32

scope
    local f := trim( io.read() ) split " "; # read a line and split into fields
    local a := tonumber( f[ 1 ] );
    local b := tonumber( f[ 2 ] );
    print( a + b )
epocs

Aime

file f;
list l;

f_affix(f, "/dev/stdin");
f_list(f, l, 0);
o_integer(atoi(l[0]) + atoi(l[1]));
o_newline();

ALGOL 60

Works with: A60
begin
    comment A+B;
    integer a,b;
    ininteger(0,a); ininteger(0,b); 
    outinteger(1,a+b)
end
Input:
1 2
Output:
 3


ALGOL 68

Translation of: python
Works with: ALGOL 68 version Standard - no extensions to language used
Works with: ALGOL 68G version Any - tested with release 1.18.0-9h.tiny

Console

print((read int + read int))

Input:

1 2
Output:
         +3

File

open(stand in, "input.txt", stand in channel);
open(stand out, "output.txt", stand out channel);
print((read int + read int))

Input "input.txt":

3 4

Output "output.txt":

         +7

ALGOL W

begin
    integer a, b;
    read( a, b );
    write( a + b )
end.

Amazing Hopper

#include <hbasic.h>

#import lib/input.bas.lib
#include include/input.h

Begin
  Token Init
  Cls
  Locate(5,1),Print(Utf8$("Ingrese dos números, separados por espacio: "))
  msg=""
  LocCol(45),Let( msg := ReadString(msg))
  Token Sep(" ")
  Print("Suma : ", Token(1),Val(Token$(msg)) Plus (Token(2),Val(Token$(msg))), Newl)
End
Output:
Ingrese dos números, separados por espacio: -200 10 
Suma : -190
Press any key to continue...

Version dos: hopper-BASIC acepta "programación fluída"

#include <hbasic.h>

#import lib/input.bas.lib
#include include/input.h

#define getValueOf(__X__)  Token(__X__),Val(Token$(msg))   
#define-a  »»(__X__) ;Move to(__X__)

Begin
  Token Init
  Cls
  Locate(5,1),Print(Utf8$("Ingrese dos números, separados por espacio: "))
  msg=""
  LocCol(45),Let( msg := ReadString(msg))
  Token Sep(" ")
  A=0, get Value Of(1)»»(A), CLamp(-1000,1000,A)
  B=0, get Value Of(2)»»(B), CLamp(-1000,1000,B)
  Print("Suma : ")
  Take(A, B), and Add It; then Print It with a Newl
End
Output:
Ingrese dos números, separados por espacio: -1005 500 
Suma : -500
Press any key to continue...

ANTLR

aplusb
aplusb
aplusb
aplusb


Apex

static Integer sumOfTwoNums(Integer A, Integer B) {
    return A + B;
}

System.debug('A = 50 and B = 25: ' + sumOfTwoNums(50, 25));
System.debug('A = -50 and B = 25: ' +sumOfTwoNums(-50, 25));
System.debug('A = -50 and B = -25: ' +sumOfTwoNums(-50, -25));
System.debug('A = 50 and B = -25: ' +sumOfTwoNums(50, -25));

'''Output'''
A = 50 and B = 25: 75
A = -50 and B = 25: -25
A = -50 and B = -25: -75
A = 50 and B = -25: 25

APL

 +

AppleScript

Open the AppleScript Editor and save this as A+B.scpt on your Desktop

on run argv
    try
        return ((first item of argv) as integer) + (second item of argv) as integer
    on error
        return "Usage with -1000 <= a,b <= 1000: " & tab & " A+B.scpt a b"
    end try
end run

To make this run in Terminal open the Terminal.app and type osascript ~/Desktop/A+B.scpt -3 78 followed by enter.

Result: 75

Arc

(prn (+ (read)
        (read)))

Argile

Translation of: C
Works with: Argile version 1.0.0
(: Standard input-output streams :)
use std, array
Cfunc scanf "%d%d" (&val int a) (&val int b)
printf "%d\n" (a + b)
(: Input file : input.txt :)
(: Output file: output.txt :)
use std, array
let  in = fopen "input.txt" "r"
let out = fopen "output.txt" "w"
let int x, y.
Cfunc fscanf in "%d%d" (&x) (&y) (:fscanf not yet defined in std.arg:)
fprintf out "%d\n" (x+y)
fclose in
fclose out

ARM Assembly

Works with: gcc version Linux

Exploiting C standard library functions (scanf and printf). Requires arm-linux-gnueabi-gcc and qemu-arm. Compile with:

arm-linux-gnueabi-as src.s -o src.o && arm-linux-gnueabi-gcc -static src.o -o run && qemu-arm run
.text
.global main
.extern printf
.extern scanf

main:
        push {lr}
        ldr r0, =scanf_lit
        ldr r1, =num_a
        ldr r2, =num_b
        bl scanf             // scanf("%d %d", &num_a, &num_b);
        ldr r0, =printf_lit
        ldr r1, =num_a
        ldr r1, [r1]
        ldr r2, =num_b
        ldr r2, [r2]
        add r1, r1, r2
        bl printf            // printf("%d\n", num_a + num_b);
        pop {pc}

.data
scanf_lit:      .asciz "%d %d"
printf_lit:     .asciz "%d\n"
.align 4
.bss
num_a:  .skip 4
num_b:  .skip 4
Works with: gcc version Linux

Todo: -need to print numbers w/o the leading 0's. Replace them with spaces, so alignment is still the same.

Read two strings from stdin, convert to integers calculate their sum, print to stdout. A valid int is a value between -2^31 (-2147483647) and 2^31-1 (2147483647). We do not allow -2147483648 as input, but it is a valid result. E.g. -1 -2147483647. Maximum number of digits is 10. Leading 0's are counted as number length. We read signed values. We ignore leading '+'s and allow '-' for negative values. If multiple plus or minus signs precede a number, only the last one counts. minval and maxval can be used to specify any valid range, (e.g. -1000 and +1000). The range is inclusive. If 0 is specified for both ranges, range checks are not done.

Tested on RaspberryPi model B (GNU/Linux, ARMv6) Save in ab.S Build with:

as -o ab.o ab.S
ld -o a.out ab.o
.data
   .align   2
   .code 32

.section .rodata
   .align   2
   .code 32

overflow_msg:  .ascii  "Invalid number. Overflow.\n"
overflow_msglen = . - overflow_msg
bad_input_msg:  .ascii  "Invalid input. NaN.\n"
bad_input_msglen = . - bad_input_msg
range_err_msg:  .ascii  "Value out of range.\n"
range_err_msglen = . - range_err_msg
io_error_msg:  .ascii  "I/O error.\n"
io_error_msglen = . - range_err_msg

sys_exit  = 1
sys_read  = 3
sys_write = 4
max_rd_buf = 14
lf = 10
m10_9 = 0x3b9aca00
maxval = 1000
minval = -1000

.text

@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@ void main()
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
   .align   2
   .code 32
   .type _start STT_FUNC
   .global _start
_start:
   stmfd   sp!, {r4,r5,lr}

.read_lhs:
   ldr r0, =max_rd_buf
   bl readint
   mov r4, r0
   bl printint
   mov r0, r4
   bl range_check

.read_rhs:
   ldr r0, =max_rd_buf
   bl readint
   mov r5, r0
   bl printint
   mov r0, r5
   bl range_check

.sum_and_print:
   adds r0, r4, r5
   bvs overflow
   bl printint

.main_exit:
   mov r0, #0
   bl exit
   ldmfd   sp!, {r4,r5,pc}

@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@ Read from stdin until we encounter a non-digit, or we have read bytes2rd digits.
@@ Ignore leading spaces.
@@ Return value to the caller converted to a signed int.
@@ We read positive values, but if we read a leading '-' sign, we convert the
@@ return value to two's complement.
@@ The argument is max number of bytes to read from stdin.
@@ int readint(int bytes2rd)
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
   .align   2
   .code 32
   .type readint STT_FUNC
   .global readint
readint:
   stmfd   sp!, {r4,r5,r6,r7,lr}
   @@@@@@@@@@@@@@@
   @@ r0 : #0 for stdin arg to read.
   @@ r1 : ptr to current pos in local buffer.
   @@ r2 : #1 to read one byte at a time.
   @@ r3,r7 : tmp.
   @@ r4 : number of bytes read.
   @@ r5 : value of current byte.
   @@ r6 : 0 while we are reading leading spaces.
   @@@@@@@@@@@@@@@
   sub sp, sp, r0
   mov r1, sp
   mov r3, #0
   push {r3}        @ sp,#4: local var @isnegative. return in r1. Default value is 0/false. Positive number.
   push {r0}        @ sp,#0: local var @maxbytes. const.
   mov r2, #1
   mov r4, #0

   mov r6, #0
   b .rd
@ we get here if r6 is 0.
@ if space, goto .rd.
@ else set r6 to 1 and goto .noleading.
.leadchk:
   mov r0, r5
   bl isspace
   cmp r0, #1
   beq .rd

.sign_chk:
   mov r0, r5
   push {r1}
   bl issign
   cmp r0, #1
   streq r0, [sp,#8]   @ sp,#4 + 4 for the pushed r1.
   movhi r1, #0
   strhi r1, [sp,#8]   @ sp,#4 + 4 for the pushed r1.
   pop {r1}
   bhs .rd

   mov r6, #1
   b .noleading

.rd:
   mov r0, #0
   bl read
   cmp r0, #1
   bne .sum_digits_eof  @ eof
   mov r5, #0
   ldrb r5, [r1]
   cmp r6, #0
   beq .leadchk

.noleading:
   mov r0, r5
   bl isdigit
   cmp r0, #1
   bne .sum_digits_nan @ r5 is non-digit

   add r4, r4, #1
   add r1, r1, #1
   @ max chars to read is received in arg[0], stored in local var at sp.
   @ Only 10 can be valid, so the default of 12 leaves space for separator.
   ldr r3, [sp]
   cmp r4, r3
   beq .sum_digits_maxrd  @ max bytes read.
   b .rd


   @@@@@@@@@@@@@@@
   @ We have read r4 (0..arg[0](default 12)) digits when we get here. Go through them
   @ and add/mul them together to calculate a number.
   @ We multiply and add the digits in reverse order to simplify the multiplication.
   @@@@@@@@@@@@@@@
   @ r0: return value.
   @ r1: local variable for read buffer.
   @ r2: tmp for conversion.
   @ r3,r6,r7: tmp
   @ r4: number of chars we have read.
   @ r5: multiplier 1,10,100.
   @@@@@@@@@@@@@@@
.sum_digits_nan:
   mov r0, r5
   bl isspace
   cmp r0, #1
   bne bad_input
.sum_digits_maxrd:
.sum_digits_eof:
   mov r0, #0
   mov r5, #1
.count:
   cmp r4, #0
   beq .readint_ret
   sub r4, r4, #1
   sub r1, #1
   ldrb r2, [r1]
   sub r2, r2, #48
   mov r3, r2

   @ multiply r3 (char value of digit) with r5 (multiplier).
   @ possible overflow.
   @ MI means negative.
   @ smulls multiples two signed 32 bit vals and returns a 64 bit result.
   @ If we get anything in r7, the value has overflowed.
   @ having r2[31] set is overflow too.
   smulls r2, r7, r3, r5
   cmp r7, #0
   bne overflow
   cmp r2, #0
   bmi overflow

   @@ possible overflow.
   adds r0, r0, r2
   bvs overflow
   bmi overflow

   @@ end of array check.
   @@ check is needed here too, for large numbers, since 10 billion is not a valid 32 bit val.
   cmp r4, #0
   beq .readint_ret

   @@ multiple multiplier by 10.
   @@ possible overflow.
   @@ too many digits is input. happens if input is more than 10 digits.
   mov r3, #10
   mov r6, r5
   smulls r5, r7, r3, r6
   cmp r7, #0
   bne overflow
   cmp r5, #0
   bmi overflow
   b .count

.readint_ret:
   ldr r1, [sp,#4] @ read isnegative value.
   cmp r1, #0
   rsbne r0, r0, #0
   pop {r2}
   add sp, sp, #4
   add sp, sp, r2
   ldmfd   sp!, {r4,r5,r6,r7,pc}

@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@ int isdigit(int)
@@ #48..#57 ascii range for '0'..'9'.
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
   .align   2
   .code 32
   .type isdigit STT_FUNC
   .global isdigit
isdigit:
   stmfd   sp!, {r1,lr}
   cmp r0, #48
   blo .o_range
   cmp r0, #57
   bhi .o_range
   mov r0, #1
   ldmfd   sp!, {r1,pc}
.o_range:
   mov r0, #0
   ldmfd   sp!, {r1,pc}

@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@ int isspace(int)
@@ ascii space = 32, tab = 9, newline 10, cr = 13.
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
   .align   2
   .code 32
   .type isspace STT_FUNC
   .global isspace
isspace:
   stmfd   sp!, {lr}
   cmp   r0, #32
   cmpne r0, #9
   cmpne r0, #10
   cmpne r0, #13
   beq .is_space
   mov r0, #0
   ldmfd   sp!, {pc}
.is_space:
   mov r0, #1
   ldmfd   sp!, {pc}

@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@ Return value is 1 for '-' 2 for '+'.
@@ int isspace(int)
@@ '+' = 43 and '-' = 45.
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
   .align   2
   .code 32
   .type issign STT_FUNC
   .global issign
issign:
   stmfd   sp!, {lr}
   cmp   r0, #43
   beq .plus_sign
   cmp r0, #45
   beq .minus_sign
   mov r0, #0
   ldmfd   sp!, {pc}
.plus_sign:
   mov r0, #2
   ldmfd   sp!, {pc}
.minus_sign:
   mov r0, #1
   ldmfd   sp!, {pc}

@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@ ARGS:
@@ r0 : in out arg (current int value)
@@ r1 : in out arg (ptr to current pos in buffer)
@@ r2 : in arg (const increment. 1000_000_000, 100_000_000, 10_000_000, 1000_000, 100_000, 10_000, 1000, 100, 10, 1.)
@@
@@ r4 : tmp local. Outer scope must init to #10 and count down to #0.
@@      Special case is INTMAX. Must init to 5 if r4 >= 1000_000_000 (0x3b9aca00 = m10_9).
@@ r5: tmp
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
   .align   2
   .code 32
   .type get_digit STT_FUNC
   .global get_digit
get_digit:
   stmfd  sp!, {r2,r4,r5,lr}
   ldr r5, =m10_9
   cmp r2, r5
   movlo r4, #10
   movhs r4, #5
.get_digit_loop:
   sub r4, #1
   mul r5, r4, r2
   cmp r0, r5
   blo .get_digit_loop
   sub r0, r5
   add r4, r4, #48
   strb r4, [r1], #1
   ldmfd   sp!, {r2,r4,r5,pc}

@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@ A quick way to divide (numbers evenly divisible by 10) by 10.
@@ Most ARM cpus don't have a divide instruction,
@@ so this will always work.
@@ A generic div function is long and not needed here.
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
   .align   2
.div_r2_10:
   stmfd   sp!, {r0,r1,r3,lr}
   mov r0, #1
   mov r1, #10
.find_x:
   mul r3, r0, r1;
   cmp r3, r2
   movlo r0, r3
   blo .find_x
   mov r2, r0
   ldmfd   sp!, {r0,r1,r3,pc}

@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
   .align   2
.print_neg_sign:
   stmfd   sp!, {r0,r1,r2,lr}
   @ 45 = '-'
   mov r1, #45
   push {r1}
   mov r2, #1
   @ r1 is ptr to our local variable (holding '-').
   mov r1, sp
   mov r0, #1
   bl write
   cmp r0, #0
   blne io_error
   pop {r1}
   ldmfd   sp!, {r0,r1,r2,pc}

@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@ void printint(int val)
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
   .align   2
   .code 32
   .type printint STT_FUNC
   .global printint
printint:
   stmfd   sp!, {r4,r5,r6,lr}
   mov r1, #1
   ands r1, r1, r0, LSR #31
   rsbne r0, r0, #0
   blne .print_neg_sign
   sub sp, sp, #20
   mov r1, sp
   mov r3, sp

   ldr r2, =m10_9
.getc_loop:
   bl get_digit
   cmp r2, #1
   beq .exit_getc_loop
   bl .div_r2_10
   b .getc_loop
.exit_getc_loop:
   ldr r0, =lf
   strb r0, [r1], #1

   sub r2, r1, r3
   mov r1, r3
   mov r0, #1
   bl write
   cmp r0, #0
   blne io_error
   add sp, sp, #20
   ldmfd   sp!, {r4,r5,r6,pc}

@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
   .align   2
range_check:
   stmfd   sp!, {r4,r5,lr}
   ldr r4, =minval
   ldr r5, =maxval
   cmp   r4, #0
   cmpeq r5, #0
   beq .skip_range_check
   cmp r0, r4
   bllt range_err
   cmp r0, r5
   blgt range_err
.skip_range_check:
   ldmfd   sp!, {r4,r5,pc}

@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@ void range_err()
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
   .align   2
range_err:
   stmfd   sp!, {lr}
   ldr r2, =range_err_msglen
   ldr r1, =range_err_msg
   mov r0, #2
   bl write
   mov   r0, #-1
   bl exit
   ldmfd   sp!, {pc}

@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@ void overflow()
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
   .align   2
overflow:
   stmfd   sp!, {lr}
   ldr r2, =overflow_msglen
   ldr r1, =overflow_msg
   mov r0, #2
   bl write
   mov   r0, #-1
   bl exit
   ldmfd   sp!, { pc}

@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@ void bad_input()
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
   .align   2
bad_input:
   stmfd   sp!, {lr}
   ldr r2, =bad_input_msglen
   ldr r1, =bad_input_msg
   mov r0, #2
   bl write
   mov   r0, #-1
   bl exit
   ldmfd   sp!, {pc}

@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@ void io_error()
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
   .align   2
io_error:
   stmfd   sp!, {lr}
   ldr r2, =io_error_msglen
   ldr r1, =io_error_msg
   mov r0, #2
   bl write
   mov   r0, #-1
   bl exit
   ldmfd   sp!, {pc}

@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@ void exit(int)
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
   .align   2
   .code 32
   .type _start STT_FUNC
   .global exit
exit:
   stmfd   sp!, {r7, lr}
   ldr r7, =sys_exit
   svc #0
   ldmfd   sp!, {r7, pc}

@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@ int write(int fd,char*buf,int len)
@ Return 0 if we successfully write all bytes. Otherwise return the error code.
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
   .align   2
   .code 32
   .type _start STT_FUNC
   .global write
write:
   stmfd   sp!, {r4,r7, lr}
   mov r4, r2
.wr_loop:
   ldr r7, =sys_write
   svc #0
   @ If r0 is negative, it is more than r4 with LO (unsigned <).
   cmp r0, r4
   sublo r4, r0
   blo .wr_loop
   moveq r0, #0
   ldmfd   sp!, {r4,r7, pc}

@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@ int read(int fd,char*buf,int len)
@ Return number of bytes successfully read. Ignore errors.
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
   .align   2
   .code 32
   .type _start STT_FUNC
   .global read
read:
   stmfd   sp!, {r7, lr}
   ldr r7, =sys_read
   svc #0
   cmp r0, #0
   movlt r0, #0
   ldmfd   sp!, {r7, pc}

Arturo

while ø [
	x: map split.words input "give me 2 numbers:" 'x -> to :integer x
	print add x\0 x\1
]
Output:
give me 2 numbers:3 4
7
give me 2 numbers:2 5
7

AsciiDots

<

 &-#$-\
.-#?-[+]
.-#?--/

ATS

(* ****** ****** *)
//                                                                                                                                                     
#include
"share/atspre_staload.hats"
//                                                                                                                                                     
staload UN = $UNSAFE
//                                                                                                                                                     
(* ****** ****** *)

staload "libc/SATS/stdio.sats"

(* ****** ****** *)

implement
main0() = let
  var A: int
  var B: int
  val () =
  $extfcall
    (void, "scanf", "%d%d", addr@A, addr@B)
  // end of [val]                                                                                                                                      
in
   println! ($UN.cast2int(A) + $UN.cast2int(B))
end // end of [main0]                                                                                                                                  

(* ****** ****** *)

AutoHotkey

This handles more than two inputs

Gui, Add, Edit, vEdit ;Enter your A+B, i.e. 5+3 or 5+3+1+4+6+2
Gui, Add, Button, gAdd, Add
Gui, Add, Edit, ReadOnly x+10 w80
Gui, Show
return

Add:
Gui, Submit, NoHide
Loop, Parse, Edit, + ;its taking each substring separated by "+" and its storing it in A_LoopField
	var += A_LoopField ;here its adding it to var
GuiControl, Text, Edit2, %var% ;here it displays var in the second edit control
var := 0 ;here it makes sure var is 0 so it won't contain the value from the previous addition
return

AutoIt

;AutoIt Version: 3.2.10.0
$num = "45  54" 
consolewrite ("Sum of " & $num & " is: " & sum($num))
Func sum($numbers)
   $numm = StringSplit($numbers," ")
   Return $numm[1]+$numm[$numm[0]]
EndFunc

Example2

This version can handle any amount of numbers in the input:

ConsoleWrite("# A+B:" & @CRLF)

Func Sum($inp)
	Local $num = StringSplit($inp, " "), $sum = 0
	For $i = 1 To $num[0]
;~ 		ConsoleWrite("# num["&$i&"]:" & $num[$i] & @CRLF)  ;;
		$sum = $sum + $num[$i]
	Next
	Return $sum
EndFunc ;==>Sum

$inp = "17  4"
$res = Sum($inp)
ConsoleWrite($inp & " --> " & $res & @CRLF)

$inp = "999 42 -999"
ConsoleWrite($inp & " --> " & Sum($inp) & @CRLF)

; In calculations, text counts as 0,
; so the program works correctly even with this input:
Local $inp = "999x y  42 -999", $res = Sum($inp)
ConsoleWrite($inp & " --> " & $res & @CRLF)
Output:
# A+B:
17  4 --> 21
999 42 -999 --> 42
999x y  42 -999 --> 42

AWK

{print $1 + $2}

BabyCobol

      * NB: COBOL's ACCEPT does not work with multiple identifiers
       IDENTIFICATION DIVISION.
           PROGRAM-ID. PLUS.
       DATA DIVISION.
       01 A PICTURE IS S9999.
       01 B LIKE A.
       PROCEDURE DIVISION.
           DISPLAY "Enter two numbers: " WITH NO ADVANCING.
           ACCEPT A B.
           ADD A TO B.
           DISPLAY "A+B =" B.

BASIC

DEFINT A-Z

tryagain:
backhere = CSRLIN
INPUT "", i$
i$ = LTRIM$(RTRIM$(i$))
where = INSTR(i$, " ")
IF where THEN
    a = VAL(LEFT$(i$, where - 1))
    b = VAL(MID$(i$, where + 1))
    c = a + b
    LOCATE backhere, LEN(i$) + 1
    PRINT c
ELSE
    GOTO tryagain
END IF

Applesoft BASIC

10 BH = PEEK(37)
20 INPUT ""; A$ : I$ = A$ : VTAB BH : A = PEEK(40) + PEEK(41) * 256 : FOR S  = 0 TO 39 : IF PEEK(A + S) = 160 THEN NEXT S : S = 0
40 IF LEN(I$) THEN IF MID$(I$, LEN(I$), 1) = " " THEN I$ = MID$(I$, 1, LEN(I$) - 1) : GOTO 40RTRIM
50 IF LEN(I$) < 3 THEN 10"TRY AGAIN
60 FOR WHERE = 1 TO LEN(I$) : IF MID$(I$, WHERE, 1) <> " " THEN NEXT WHERE : GOTO 10"TRY AGAIN
70 A% = VAL(LEFT$(I$, WHERE - 1))
80 B% = VAL(MID$(I$, WHERE + 1, LEN(I$)))
90 C% = A% + B%
100 VTAB BH
110 HTAB LEN(A$) + 2 + S
120 PRINT C%

BaCon

' A+B
INPUT d$
PRINT VAL(TOKEN$(d$, 1)) + VAL(TOKEN$(d$, 2))

BASIC256

dim a(2)
input "Enter two numbers separated by a space?", t$
a = explode(t$," ")
print t$  &  " " & int(a[0]) + int(a[1])

BBC BASIC

      REPEAT
        hereY% = VPOS
        INPUT LINE "" q$
        hereX% = LEN(q$) + 1
        WHILE LEFT$(q$, 1) = " "
          q$ = MID$(q$, 2)
        ENDWHILE
        space% = INSTR(q$, " ")
        IF space% THEN
          a = VAL(LEFT$(q$, space% - 1))
          b = VAL(MID$(q$, space% + 1))
          PRINT TAB(hereX%, hereY%) ; a + b
        ENDIF
      UNTIL FALSE

That seems overly complicated. What's wrong with:

      REPEAT
        INPUT LINE "" q$
        space% = INSTR(q$," ")
        PRINT VAL LEFT$(q$,space%-1) + VAL MID$(q$,space%+1)
      UNTIL FALSE

Chipmunk Basic

Works with: Chipmunk Basic version 3.6.4
Works with: Applesoft BASIC
Works with: GW-BASIC
Works with: MSX_BASIC
Works with: PC-BASIC version any
Works with: QBasic
10 CLS : rem  10 HOME for Applesoft BASIC
20 PRINT "ENTER TWO NUMBERS, SEPARATED BY A SPACE: ";
30 INPUT X$
40 I = 1 : N = LEN(X$)
50 IF MID$(X$, I, 1) <> " " AND I < N THEN I = I + 1 : GOTO 50
60 A = VAL(LEFT$(X$, I))
70 B = VAL(RIGHT$(X$, N - 1))
80 PRINT A + B
90 END

Commodore BASIC

10 PRINT "ENTER TWO NUMBERS, SEPARATED BY A SPACE: ";
20 INPUT X$
30 I = 1 : N = LEN(X$)
40 IF MID$(X$,I,1)<>" " AND I<N THEN I = I+1 : GOTO 40
50 A = VAL(LEFT$(X$,I))
60 B = VAL(RIGHT$(X$,N-1))
70 PRINT A+B

FreeBASIC

' fb 1.05.0 Win64

Dim As Integer a, b
Do
  Print "Enter two integers separated by a space : ";
  Input "", a, b
  If Abs(a) > 1000 OrElse Abs(b) > 1000 then
    Print "Both numbers must be in the interval [-1000, 1000] - try again"
    Print
  Else
    Print "Their sum is"; a + b
    Exit Do
  End If
Loop
Print
Print "Press any key to quit the program"
Sleep

GW-BASIC

The Chipmunk Basic solution works without any changes.

FUZE BASIC

INPUT n$
PRINT VAL(LEFT$(n$,(LEN(STR$(VAL(n$))))))+VAL(RIGHT$(n$,(LEN(n$)-LEN(STR$(VAL(n$)))-1)))
END

IS-BASIC

100 DO
110   INPUT PROMPT "Ener two integers separated by a comma: ":A,B
120   IF ABS(A)>1000 OR ABS(B)>1000 OR IP(A)<>A OR IP(B)<>B THEN
130     PRINT "Both integers must be in the interval [-1000..1000] - try again.":PRINT 
140   ELSE
150     PRINT "Their sum is";A+B
160     EXIT DO
170   END IF
180 LOOP

Liberty BASIC

input, n$
print  eval(word$(n$,1);" + ";word$(n$,2))

Minimal BASIC

Works with: QBasic
Works with: QuickBasic
Works with: Applesoft BASIC
Works with: BASICA
Works with: Chipmunk Basic
Works with: GW-BASIC
Works with: IS-BASIC
Works with: MSX Basic
Works with: Just BASIC
Works with: Liberty BASIC
Works with: Run BASIC
Works with: Yabasic
10 PRINT "ENTER NUMBER A";
20 INPUT A
30 PRINT "ENTER NUMBER B";
40 INPUT B
50 PRINT A+B
60 END

MSX Basic

The Chipmunk Basic solution works without any changes.

OxygenBasic

uses console
int i
string s
do
  print "Enter 2 numbers separated by space "
  s=input
  s=ltrim(s)
  exit if not s
  i=instr(s," ")
  exit if i<2
  print val(s)+val(mid(s,i))+cr
loop

Sinclair ZX81 BASIC

10 INPUT A$
20 LET I=1
30 IF A$(I)=" " THEN GOTO 60
40 LET I=I+1
50 GOTO 30
60 PRINT VAL A$( TO I-1)+VAL A$(I+1 TO )

SmallBASIC

input "Enter number A: "; a
input "Enter number B: "; b
print "A + B = "; a + b

Tiny BASIC

REM Rosetta Code problem: https://rosettacode.org/wiki/A+B
REM by Jjuanhdez, 06/2022

10  LET C = 0
    LET D = 0
    PRINT "Enter an integer: "
    INPUT A
    IF A < 0 THEN LET C = A * -1
    PRINT "Enter other integer: "
    INPUT B
    IF B < 0 THEN LET D = B * -1
    IF C > 1000 THEN GOTO 60
    IF D > 1000 THEN GOTO 60
50  PRINT "Their sum is ", A + B
    GOTO 70
60  PRINT "Both integers must be in the range [-1000..1000] - try again."
    GOTO 10
70  END

True BASIC

DO
   INPUT PROMPT "Enter two integers separated by a comma: ": A, B
   IF ABS(A)>1000 OR ABS(B)>1000 OR IP(A)<>A OR IP(B)<>B THEN
      PRINT "Both integers must be in the interval [-1000..1000] - try again."
      PRINT
   ELSE
      PRINT "Their sum is";A+B
      EXIT DO
   END IF
LOOP
END

uBasic/4tH

s = FUNC(_GetInt(1000)) + FUNC(_GetInt(1000))
Print "The sum is: ";s
End

_GetInt
  Param (1)
  Local (1)
  
  Do
    Input "Enter a value: ", b@
  Until (b@ > -a@-1 ) * (b@ < a@+1)
    Print "Wrong, must be between "; -a@; " and "; a@; ". Try again.."
  Loop
Return (b@)

XBasic

Works with: Windows XBasic
PROGRAM	"A+B"
VERSION	"0.0000"

DECLARE FUNCTION  Entry ()

FUNCTION  Entry ()
  a$ = INLINE$("Enter integer A: ")
  a = SLONG(a$)
  b$ = INLINE$("Enter integer B: ")
  b = SLONG(b$)
  DO WHILE 1
    IF ABS(a) > 1000 OR ABS(b) > 1000 THEN
      PRINT "Both integers must be in the interval [-1000..1000] - try again."
      PRINT
    ELSE
      PRINT "Their sum is"; a + b
      EXIT DO
    END IF
  LOOP
END FUNCTION
END PROGRAM

Batch File

Prompts version

::aplusb.cmd
@echo off
setlocal
set /p a="A: "
set /p b="B: "
set /a c=a+b
echo %c%
endlocal

All on the commandline version

::aplusb.cmd
@echo off
setlocal
set a=%1
set b=%2
set /a c=a+b
echo %c%
endlocal

Formula on the command line version

::aplusb.cmd
@echo off
setlocal
set /a c=%~1
echo %c%
endlocal

Example of 'Formula on the command line version'

>aplusb 123+456
579
>aplusb "1+999"
1000

Parse the input stream version (thanks to Tom Lavedas on alt.msdos.batch.nt)

::aplusb.cmd
@echo off
setlocal
set /p a="Input stream: "
call :add %a%
echo %res%
endlocal
goto :eof

:add
set /a res=res+%1
shift
if "%1" neq "" goto :add

Example of 'parse the input stream version'

>aplusb
Input stream: 1234 5678
6912
>aplusb
Input stream: 123 234 345 456 567 678 789 890
4082

bc

Works with: GNU bc
read() + read()

Befunge

&&+.@

Bird

use Console Math

define Main
    $a Console.Read
    $b Console.Read
    Console.Println Math.Add $a $b
end

BlooP

BlooP and FlooP can't actually read from stdin, but here's the procedure it would use, if it could.

DEFINE PROCEDURE ''ADD'' [A, B]:
BLOCK 0: BEGIN
    OUTPUT <= A + B;
BLOCK 0: END.

bootBASIC

Both numbers are entered separately.

10 print "Number 1";
20 input a
30 print "Number 2";
40 input b
50 print a+b

BQN

Works with: [CBQN]
#!/usr/bin/env bqn

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

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

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

# •GetLine and •_while_ are nonstandard CBQN extensions.
{•Show +´ ParseNums 𝕩  •GetLine@} •_while_ (@) •GetLine@

Bracmat

filter is a pattern that checks that input is a non-fractional number not less than -1000 and not greater than 1000. The filter is applied to each input.

( out
$ (   put$"Enter two integer numbers between -1000 and 1000:"
    & (filter=~/#%:~<-1000:~>1000)
    & get':(!filter:?a) (!filter:?b)
    & !a+!b
  | "Invalid input. Try again"
  )
);

Brainf***

INPUT AND SUMMATION
TODO if first symbol is a minus sign print Qgo awayQ
+>                                                  initialize sum to one
++[                                                 loop for each input ie twice
    [>>,----------[----------------------[-<+>]]<]      eat digits until space or newline
    <[<]>>>
    >[<                                                 until no next digit
        ----------------                                    subtract ascii zero minus what we subtracted above
        [->++++++++++<]                                     add ten timess that to the next digit
        <[->+<]<[->+<]>>                                    shift sum and loop counter
        >>
    ]
    <----------------                                   subtract as above from last digit as well
    [-<<+>>]                                            add to sum
    <-
]
<-                                                  subtract original one from sum

OUTPUT
[                                                                                                   while a number divided by ten is bigger than zero
    [->+<[->+<[->+<[->+<[->+<[->+<[->+<[->+<[->+<[->--------->+<<[->>>+<<<]]]]]]]]]]>>>[-<<<+>>>]<<<]   divide by ten
    >++++++++++++++++++++++++++++++++++++++++++++++++>                                                  convert remainder to ascii digit
]
<[.<<]                                                                                              print ascii digits

Brat

numbers = g.split[0,1].map(:to_i)
p numbers[0] + numbers[1]  #Prints the sum of the input

Bruijn

:import std/Combinator .
:import std/String .
:import std/Number .
:import std/Char C

main (split-by (C.eq? ' ')) → &(add ⋔ string→number)

Burlesque

ps++

C

// Standard input-output streams
#include <stdio.h>
int main()
{
   int a, b;
   scanf("%d%d", &a, &b);
   printf("%d\n", a + b);
   return 0;
}
// Input file: input.txt
// Output file: output.txt
#include <stdio.h>
int main()
{
   freopen("input.txt", "rt", stdin);
   freopen("output.txt", "wt", stdout);
   int a, b;
   scanf("%d%d", &a, &b);
   printf("%d\n", a + b);
   return 0;
}
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv) //not sure if argv counts as input stream... certainly it is brought here via input stream.
{
   printf("%d\n", atoi(*(argv+1)) + atoi(*(argv+2)));
   return 0;
}

C#

using System;
using System.Linq;

class Program
{
    static void Main()
    {
        Console.WriteLine(Console.ReadLine().Split().Select(int.Parse).Sum());
    }
}

Another way (not recommended since it does not work with more than two numbers):

using System;

class Program
{
    static void Main()
    {
        string input = Console.ReadLine();
        int index = input.IndexOf(" ");
        int num1 = int.Parse(input.Substring(0, index));
        int num2 = int.Parse(input.Substring(index + 1));
        int sum = num1 + num2;
        Console.WriteLine(sum.ToString());
    }
}

C++

// Standard input-output streams
#include <iostream>
using namespace std;
int main()
{
   int a, b;
   cin >> a >> b;
   cout << a + b << endl;
}
// Input file: input.txt
// Output file: output.txt
#include <fstream>
using namespace std;
int main()
{
   ifstream in("input.txt");
   ofstream out("output.txt");
   int a, b;
   in >> a >> b;
   out << a + b << endl;
   return 0;
}

Ceylon

shared void run() {

    print("please enter two numbers for me to add");
    value input = process.readLine();
    if (exists input) {
        value tokens = input.split().map(Integer.parse);
        if (tokens.any((element) => element is ParseException)) {
            print("numbers only, please");
            return;
        }
        value numbers = tokens.narrow<Integer>();
        if (numbers.size != 2) {
            print("two numbers, please");
        }
        else if (!numbers.every((Integer element) => -1k <= element <= 1k)) {
            print("only numbers between -1000 and 1000, please");
        }
        else if (exists a = numbers.first, exists b = numbers.last) {
            print(a + b);
        }
        else {
            print("something went wrong");
        }
    }
}

CFEngine

There is no concept of CFEngine policy reading from stdin so I will read from a file.

$ cat sum.cf
bundle agent main  
{
  vars:
    "line_count" int => readintarray(
      "input",
      "${this.promise_dirname}${const.dirsep}input.txt",
      "#[^\n]*",
      " ",
      "inf",
      "inf"
    );
    "indices" slist => getindices( "input" );
  reports:
    "${with}" with => format( "%d", eval( "${input[${indices}][0]} + ${input[${indices}][1]}" ));
    DEBUG::
      "line_count is ${line_count}";
      "input is ${with}" with => storejson( "input" );
      "input[${indices}] is ${with}" with => storejson( "input[${indices}]" );
}

$ cat input.txt
2 3
2 2

$ cf-agent -KIf ./sum.cf
R: 5
R: 4

The "R:" prefix is for a report promise and the only way to output to stdout with policy. You could also output to a file I suppose.

Clojure

(println (+ (Integer/parseInt (read-line)) (Integer/parseInt (read-line))))
3
4
=>7
(eval (read-string (str "(+ " (read-line) " )") ))
3 3
6

Translation of Common Lisp version:

(println (+ (read) (read)))
3 4
7


Safely and without reader tricks:

(let [ints (map #(Integer/parseInt %) (clojure.string/split (read-line) #"\s") )] 
  (println (reduce + ints)))
3 4
=>7

or same as above, but without "let":

(println (reduce + (map #(Integer/parseInt %) (clojure.string/split (read-line) #"\s") )))

3 4
=>7

COBOL

       IDENTIFICATION DIVISION.
       PROGRAM-ID. A-Plus-B.

       DATA DIVISION.
       WORKING-STORAGE SECTION.
       01  A       PIC S9(5).
       01  B       PIC S9(5).

       01  A-B-Sum PIC S9(5).

       PROCEDURE DIVISION.
           ACCEPT A
           ACCEPT B

           ADD A TO B GIVING A-B-Sum

           DISPLAY A-B-Sum

           GOBACK
           .

A second version.

       IDENTIFICATION DIVISION.
       PROGRAM-ID. A-Plus-B.
       AUTHOR.  Bill Gunshannon.
       INSTALLATION.  Home.
       DATE-WRITTEN.  25 December 2021.
      ************************************************************
      ** Program Abstract:
      **   A re-worked version that more closely matches the
      **     desired format. Both numbers are taken in on one
      **     line separated by spaces. Sum is formated to remove
      **     leading zeros and/or spaces.
      ************************************************************

 
       DATA DIVISION.
       WORKING-STORAGE SECTION.
       01  Input-Data   PIC X(16).
       01  A            PIC S9(5).
       01  B            PIC S9(5).
 
       01  A-B-Sum PIC -----9.
 
       PROCEDURE DIVISION.
           DISPLAY "Input pairs of numbers separated by spaces."
           DISPLAY "Enter q to exit."
           PERFORM WITH TEST BEFORE
                   UNTIL Input-Data = "q" or Input-Data = "Q"
           ACCEPT Input-Data
                IF Input-Data NOT = "q" and Input-Data NOT = "Q"
                  UNSTRING Input-Data DELIMITED BY SPACES
                        INTO A B
                  ADD A TO B GIVING A-B-Sum
 
                  DISPLAY "Sum = " FUNCTION TRIM(A-B-Sum)
                END-IF
           END-PERFORM.
 
           STOP RUN.

CoffeeScript

Translation of: JavaScript
<html>
<script type="text/javascript" src="http://jashkenas.github.com/coffee-script/extras/coffee-script.js"></script>
<script type="text/coffeescript">
a = window.prompt 'enter A number', ''
b = window.prompt 'enter B number', ''
document.getElementById('input').innerHTML = a + ' ' + b
sum = parseInt(a) + parseInt(b)
document.getElementById('output').innerHTML = sum
</script>
<body>
<div id='input'></div>
<div id='output'></div>
</body>
</html>
Works with: Node.js
{ stdin } = process
sum = ( a, b ) -> a + b

display = ( messages... ) -> console.log messages...

parse = ( input ) ->
    parseInt x for x in ( x.trim() for x in input.split ' ' ) when x?.length

check = ( numbers... ) ->
    return no for x in numbers when isNaN x
    return no for x in numbers when not ( -1000 < x < 1000 )
    yes

prompt = ->
    display 'Please enter two integers between -1000 and 1000, separated by a space:'
    stdin.once 'data', ( data ) ->
        [ a, b ] = parse data
        if check a, b
            display "#{ a } + #{ b } = #{ sum a, b }"
        else
            display "Invalid input: #{ a }, #{ b }"
        do prompt
        return

# Resume input and set the incoming encoding.
stdin.resume()
stdin.setEncoding 'utf8'

# Start the main loop.
do prompt

Common Lisp

(write (+ (read) (read)))

Component Pascal

BlackBox Component Builder

MODULE AB;
IMPORT StdLog, DevCommanders,TextMappers;

PROCEDURE DoAB(x,y: INTEGER);
BEGIN
        StdLog.Int(x);StdLog.Int(y);StdLog.Int(x + y);StdLog.Ln;
END DoAB;

PROCEDURE Go*;
VAR
                params: DevCommanders.Par;
                s: TextMappers.Scanner;
                p : ARRAY 2 OF INTEGER;
                current: INTEGER;
BEGIN
        current := 0;
        params := DevCommanders.par;
        s.ConnectTo(params.text);
        s.SetPos(params.beg);
        s.Scan;
        WHILE(~s.rider.eot) DO
                IF (s.type = TextMappers.int) THEN
                        p[current] := s.int; INC(current);
                END;
                s.Scan;
        END;
        IF current = 2 THEN DoAB(p[0],p[1]) END;
END Go;
END AB.

Execute: AB.Go 12 23 ~

Output:
12 23 35

Computer/zero Assembly

        STP      ; wait for input
a:           0
b:           0
        LDA  a
        ADD  b
        STP

Crystal

puts gets.not_nil!.split.map(&.to_i).sum

The not_nil! call on gets is needed because gets might return nil and the compiler forces us to deal with it. In the case of nil a runtime exception will be thrown.

To handle the nil case we could do:

if line = gets
  puts line.split.map(&.to_i).sum
else
  puts "No input"
end

D

From Console

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

void main() {
    string[] r;
    try
        r = readln().split();
    catch (StdioException e)
        r = ["10", "20"];

    writeln(to!int(r[0]) + to!int(r[1]));
}
Output:
30

From File

void main() {
    import std.stdio, std.file;

    immutable ab = "sum_input.txt".slurp!(int, int)("%d %d")[0];
    "sum_output.txt".File("w").writeln(ab[0] + ab[1]);
}

Dart

import 'dart:io';

// a little helper function that checks if the string only contains
// digits and an optional minus sign at the front
bool isAnInteger(String str) => str.contains(new RegExp(r'^-?\d+$'));

void main() {
  while(true) {
    String input = stdin.readLineSync();
    var chunks = input.split(new RegExp(r'[ ]+')); // split on 1 or more spaces
    if(!chunks.every(isAnInteger)) { 
      print("not an integer!");
    } else if(chunks.length > 2) {
      print("too many numbers!");
    } else if(chunks.length < 2) {
      print('not enough numbers!');
    } else {
      // parse the strings into integers 
      var nums = chunks.map((String s) => int.parse(s));
      if(nums.any((num) => num < -1000 || num > 1000)) {
        print("between -1000 and 1000 please!");
      } else {
        print(nums.reduce((a, b) => a + b));
      }
    }
  }
}
Output:
1 2
3
3 4
7

dc

? + psz

The question mark ? reads and executes a line of input. The user must enter a dc program that pushes two numbers to the stack, such as 2 3 or 5 _1. (The user must use underscore _ for negative numbers.)

DCL

$ read sys$command line
$ a = f$element( 0, " ", line )
$ b = f$element( 1, " ", line )
$ write sys$output a, "+", b, "=", a + b

Delphi

Console version.

program SUM;

{$APPTYPE CONSOLE}

uses
  SysUtils;

procedure
var
  s1, s2:string;
begin
  ReadLn(s1);
  Readln(s2);
  Writeln(StrToIntDef(s1, 0) + StrToIntDef(s2,0));
end.

Diego

set_namespace(rosettacode)_me();
    
begin_instuct(A + B);
    ask_human()_msg(Please enter two integers between -1000 and 1000, separated by a space:)_split( )_var(A, B);
    with_var(A, B)_trim()_parse({integer})_test([A]<=-1000)_test([B]>=1000)
        : with_human[]_msg(Invalid input: [A], [B]); 
          exec_instruct[];
    ;
    add_var(sum)_calc([A]+[B]);
    with_human[]_msg([A] + [B] = [sum]);
end_instruct[];

exec_instruct(A + B)_me();

reset_namespace[];

DMS

number a = GetNumber( "Please input 'a'", a, a )    // prompts for 'a'
number b = GetNumber( "Please input 'b'", b, b )    // prompts for 'b'
Result( a + b + "\n" )

Dragon

select "graphic"
select "types"

a = int(prompt("Enter A number"))
b = int(prompt("Enter B number"))

showln a + b

DWScript

Ghetto GUI version

var a := StrToInt(InputBox('A+B', 'Enter 1st number', '0'));
var b := StrToInt(InputBox('A+B', 'Enter 2nd number', '0'));
ShowMessage('Sum is '+IntToStr(a+b));

Déjà Vu

Translation of: Python

Console

0
for k in split !prompt "" " ":
	+ to-num k
!print

EasyLang

a$ = input
repeat
   i += 1
   until i > len a$ or substr a$ i 1 = " "
.
a = number substr a$ 1 i
b = number substr a$ i 99
print a + b

EchoLisp

(+ (read-number 1 "value for A") (read-number 2 "value for B"))

EDSAC order code

The EDSAC does not support input of data while a program is running, so A and B are pre-set to 37 and 28. Other values can of course be substituted: note the slightly idiosyncratic format in which integer data is written (the least significant bit set using an alphabetic character). The result of the computation is displayed in binary in the first address of storage tank 3.

[ A plus B
  ========
  
  A program for the EDSAC
  
  Adds two integers & displays
  the sum at the top of storage
  tank 3

  Works with Initial Orders 2 ]

[ Set load point & base address ]

T56K  [ Load at address 56 ]
GK    [ Base addr (theta) here ]

[ Orders ]

T96F  [ Clear accumulator    ]
A5@   [ Acc += C(theta + 5)  ]
A6@   [ Acc += C(theta + 6)  ]
T96F  [ C(96) = Acc; Acc = 0 ]

ZF    [ Halt ]

[ Pseudo-orders (data) ]

P18D  [ 5@: 18*2 + 1 = 37 ]
P14F  [ 6@: 14*2 + 0 = 28 ]

[ When loading is finished: ]

EZPF  [ Branch to load point ]
Output:
00000000001000001

Alternative

This is a more elaborate solution, to demonstrate how the same program can be applied to different sets of data (cf. Wilkes, Wheeler and Gill, 1951 edition, page 47).

In the program below, the two integers to be added are placed at the end. On the original EDSAC, they would be on the same paper tape as the program. With Martin Campbell-Kelly's EdsacPC simulator, reading the data from a separate tape can be simulated as follows:

1. Remove the two integers from the end of this program and store them, or another pair of integers, in a separate text file. Each integer must be terminated by a non-digit or a blank tape row (represented by a full stop in the simulator).

2. Run the altered program. The simulator will stop with a message "End of input tape encountered".

3. Dismiss the message, make the file with the two integers the active file, and click Reset. The simulator will continue, read the integers, and print them together with their sum.

 [A + B for Rosetta Code.
  Read two integers and find their sum.
  EDSAC program, Initial Orders 2.]
  
 [Print signed number, up to 10 digits, right-justified.
  Modification of library subroutine P7.
  55 locations, load at even address.]
            T   56 K
  GKA3FT42@A47@T31@ADE10@T31@A48@T31@SDTDH44#@NDYFLDT4DS43@TF
  H17@S17@A43@G23@UFS43@T1FV4DAFG50@SFLDUFXFOFFFSFL4FT4DA49@T31@
  A1FA43@G20@XFP1024FP610D@524D!FO46@O26@XFO46@SFL8FT4DE39@

 [Subroutine to read signed number from input, up to 10 digits.
  Partly based on library subroutine R2. Result in 4D.
  Working registers: 0F = dump to clear acc
                     1F < 0 if number starts with minus, = 0 if not.
                     6D = character code, as double-word value]
            T  120 K
            G      K
            A    3 F  [make link for return]
            T   36 @  [plant in code; clear acc]
            H    7 @  [mult reg := 10/32]
            T    4 D  [initialize result to 0]
            T    1 F  [no minus sign yet]
            T    6 D  [ensure 7F and sandwich bit are 0]
          [Loop until find valid first character of integer, namely
           decimal digit (char codes 0..9), plus (13), or minus (22).]
      [6]   I    6 F  [char code from input]
      [7]   T      F  [clear acc; also serves as constant 10/32]
            S    6 F  [load negative of char code]
            A   39 @  [add 9]
            E   24 @  [if decimal digit, out]
            A   38 @  [add 3]
            E    6 @  [if 10..12, try again]
            A   37 @  [add 1]
            E   20 @  [if plus, out with acc = 0]
            A   39 @  [add 9]
            G    6 @  [if 23..31, try again]
            S   37 @  [subtract 1]
            E    6 @  [if 14..21, try again]
            T    1 F  [minus, acc = -1, store in sign]
           [Loop to read characters after first. Assumes acc = 0 here.]
     [20]   I    6 F  [next char from input]
            S    6 F  [negative to acc]
            A   39 @  [add 9]
            G   30 @  [finished if not digit]
     [24]   T      F  [clear acc]
            V    4 D  [acc := 10/32 times partial sum]
            L    8 F  [shift 5 left]
            A    6 D  [add latest digit]
            T    4 D  [update partial sum]
            E   20 @  [loop for next char]
           [Here when no more digits]
     [30]   T      F  [clear acc]
            A    1 F  [load sign of result]
            E   36 @  [exit (with acc = 0) if >= 0]
            T      F  [< 0, clear acc]
            S    4 D  [subtract number]
            T    4 D  [store back negated; clear acc]
     [36]   E      F  [exit with acc = 0 (EDSAC convention)]
  [Constants]
     [37]   P      D  [1]
     [38]   P    1 D  [3]
     [39]   P    4 D  [9]

  [Main routine]
            T  200 K
            G      K
  [Variables]
      [0]   P F   P F [integer A]
      [2]   P F   P F [integer B]
  [Constants]
      [4]   #      F  [figures]
      [5]   @      F  [carriage return]
      [6]   &      F  [line feed]
      [7]   K 4096 F  [null char]
           [Enter with acc = 0]
      [8]   O    4 @  [set teleprinter to figures]
            A    9 @
            G  120 F  [read integer A from input]
            A    4 D  [load]
            U     #@  [save]
            T      D  [to 0D for printing]
            A   14 @
            G   56 F  [print A]
            O    5 @  [followed by new line]
            O    6 @
            A   18 @
            G  120 F  [read integer B from input]
            A    4 D  [load]
            U    2#@  [save]
            T      D  [to 0D for printing]
            A   23 @
            G   56 F  [print B]
            O    5 @  [followed by new line]
            O    6 @
            A     #@  [load A]
            A    2#@  [add B]
            T      D  [A + B to 0D for printing]
            A   30 @
            G   56 F  [print A + B]
            O    5 @  [followed by new line]
            O    6 @
            O    7 @  [print null to flush teleprinter buffer]
            Z      F  [stop]
            E    8 Z
            P      F
-987.123.
Output:
       -987
        123
       -864

EGL

package programs;

// basic program
// 
program AplusB type BasicProgram {}
	function main()
		try
			arg1 string = SysLib.getCmdLineArg(1);
			arg2 string = SysLib.getCmdLineArg(2);
			int1 int = arg1;
			int2 int = arg2;
			sum int = int1 + int2;
			SysLib.writeStdout("sum1: " + sum);
		onException(exception AnyException)
			SysLib.writeStdout("No valid input. Provide 2 integer numbers as arguments to the program.");
		end
	end
end

Eiffel

argument(0) contains the path of the executable - thus we start at argument(1)

class
	APPLICATION
inherit
	ARGUMENTS
create
	make
feature {NONE} -- Initialization
	make
			-- Run application.
		do
			print(argument(1).to_integer +	argument(2).to_integer)
		end
end

Alternatively ...

	make
			-- Run application.
		note
			synopsis: "[
				The specification implies command line input stream and also
				implies a range for both `A' and `B' (e.g. (-1000 <= A,B <= +1000)).
				To test in Eiffel Studio workbench, one can set Execution Parameters
				of "2 2", where the expected output is 4. One may also create other
				test Execution Parameters where the inputs are out-of-bounds and
				confirm the failure.
				]"
		do
			if attached {INTEGER} argument (1).to_integer as a and then
				attached {INTEGER} argument (2).to_integer as b and then
				(a >= -1000 and b >= -1000 and a <= 1000 and b <= 1000) then
				print (a + b)
			else
				print ("Either argument 1 or 2 is out-of-bounds. Ensure: (-1000 <= A,B <= +1000)")
			end
		end

Ela

open monad io string list

a'b() = do
  str <- readStr
  putStrLn <| show <| sum <| map gread <| string.split " " <| str

a'b() ::: IO
Output:
1 2 3 4 5 6
21

Elena

ELENA 6.0 :

import extensions;
 
public program()
{
    var A := Integer.new();
    var B := Integer.new();
 
    console.loadLine(A,B).printLine(A + B)
}

Or more generic solution:

import system'routines;
import extensions;

public program()
{
    console.printLine(console.readLine()
                              .split()
                              .selectBy(mssgconst toInt<intConvertOp>[1])
                              .summarize())
}

Elixir

IO.gets("Enter two numbers seperated by a space: ") 
  |> String.split
  |> Enum.map(&String.to_integer(&1))
  |> Enum.sum
  |> IO.puts

Elm

--To write this function directly run cmd
--Type elm-repl to start
--Next enter this code
sum x y=x+y

--This creates a sum function 
--When you enter sum A B
--You get output as A+B : number
--Task done!
--END

Emacs Lisp

(let* ((input (read-from-minibuffer ""))
       (numbers (mapcar #'string-to-number (split-string input)))
       (a (car numbers))
       (b (cadr numbers)))
  (message "%d" (+ a b)))

EMal

fun main = int by List args
  text input = when(args.length == 1, args[0], ask(text, "Enter n integers separated by a space: "))
  int sum, count
  for each text word in input.split(" ")
    word = word.trim()
    if word.isEmpty() do continue end # ignore empty words
    int nr = int!word # this can raise an exception
    if abs(nr) > 1000
      Event.error(0, "Integers must be in the interval [-1000, 1000]").raise()
    end
    sum += nr
    ++count
  end
  if count < 2 do Event.error(1, "At least two integers must be provided").raise() end
  writeLine("The sum of " + count + " integers is: " + sum)
  return 0
end
exit main(Runtime.args)
Output:
emal.exe Org\RosettaCode\Aplusb.emal "  9   8 "
The sum of 2 integers is: 17

Emojicode

🏁🍇
  🆕🔡▶️👂🏼❗️ ➡️ input 💭 Get numbers as input string
  🔫 input 🔤 🔤❗ ➡️ nums 💭 Split numbers by space
  🍺🔢 🐽 nums 0❗ 10❗ ➡️ A 💭 Retrieve first number
  🍺🔢 🐽 nums 1❗ 10❗ ➡️ B 💭 Retrieve second number
  😀 🔤🧲A➕B🧲🔤 ❗ 💭 Output sum
🍉️

Erlang

-module(aplusb).
-export([start/0]).

start() ->
    case io:fread("","~d~d") of
        eof -> ok;
        {ok, [A,B]} ->
            io:format("~w~n",[A+B]),
            start()
    end.

ERRE

PROGRAM SUM2

BEGIN

  LOOP
    INPUT(LINE,Q$)
    EXIT IF Q$=""
    SP%=INSTR(Q$," ")
    PRINT(VAL(LEFT$(Q$,SP%-1))+VAL(MID$(Q$,SP%+1)))
  END LOOP

END PROGRAM

Euler

begin
    out in + in
end $

Euler Math Toolbox

>s=lineinput("Two numbers seperated by a blank");
 Two numbers seperated by a blank? >4 5
>vs=strtokens(s)
 4
 5
>vs[1]()+vs[2]()
 9

Euphoria

include get.e

function snd(sequence s)
    return s[2]
end function

integer a,b

a = snd(get(0))
b = snd(get(0))

printf(1," %d\n",a+b)

Excel

Take any 3 columns of any row or rows. Let's say A1,B1 and C1 are taken. In C1 type in :

=A1+B1

The value of C1 will change as the values of A1 and B1 are changed

1	2	3

F#

open System

let SumOf(str : string) =
    str.Split() |> Array.sumBy(int)

[<EntryPoint>]
let main argv = 
    Console.WriteLine(SumOf(Console.ReadLine()))
    0

Factor

USING: math.parser splitting ;
: a+b ( -- )
    readln " " split1
    [ string>number ] bi@ +
    number>string print ;
( scratchpad ) a+b
2 2
4

FALSE

[0[^$$'9>'0@>|~]['0-\10*+]#%]n:  {read an integer}
n;!n;!+.

Fantom

class APlusB
{
  public static Void main () 
  {
    echo ("Enter two numbers: ")
    Str input := Env.cur.in.readLine
    Int sum := 0
    input.split.each |n| { sum += n.toInt }
    echo (sum)
  }
}

FBSL

Using stdin and stdout

#APPTYPE CONSOLE

DIM %a, %b
SCANF("%d%d", @a, @b)
PRINT a, "+", b, "=", a + b

PAUSE

Fennel

Translation of: Lua
(let [(a b) (io.read :*number :*number)]
  (print (+ a b)))

Fhidwfe

function listint scanint (num:ptr) {// as of writing, fhidwfe has no builtin int scanning
 reset negative
 read = num
 num1 = 0
 num2 = 0
 while ~ = deref_ubyte$ read ' ' {
  char = deref_ubyte$ read
  if = char '-' {
   set negative
  } {
   num1 = + * 10 num1 as - char '0' int
  }
  read = + read 1u
 }
 if negative {
  num1 = !num1
 } ;
 reset negative
 read = + read 1u
 while ~ = deref_ubyte$ read 0ub {
  char2 = deref_ubyte$ read
  if = char2 '-' {
   set negative
  } {
   num2 = + * 10 num2 as - char2 '0' int
  }
  read = + read 1u
 }
 if negative {
  num2 = !num2
 } ;
 return (num1 num2)
}

//the real program
text = malloc$ 12u//worst input is -1000 -1000, or 11 bytes + null terminator
getline$ text
inp = scanint$ text
free$ text
puti$ + access_word$ inp 0u access_word$ inp 1u
free$ inp

Fish

i:o:"-"=?v1$68*-v
v        >~01-0 >
>i:o:" "=?v68*-$a*+
          >~*i:o:"-"=?v1$68*-v
v                     >~01-0 >
>i:o:d=?v68*-$a*+
        >~*+aonao;

Forth

pad dup 80 accept evaluate + .

Fortran

program a_plus_b
  implicit none
  integer :: a,b
  read (*, *) a, b
  write (*, '(i0)') a + b
end program a_plus_b

And in Fortran 77

      READ  (1,100) I,J
 100  FORMAT(2I5)
      WRITE (2,200) I+J
 200  FORMAT(1X,I5)
      END

Free Pascal

program SUMA;
uses
  SysUtils;
var
  s1, s2:integer;
begin
  ReadLn(s1);
  Readln(s2);
  WriteLn(IntToStr(s1 + s2));
end.


Frink

This program handles arbitrarily-large integers, or even floating-point or rational numbers or complex numbers (as long as they're not internally separated with spaces, of course, which are the delimiters for this task.) It can even handle units of measure (with no embedded spaces) such as "3.3meter 2feet" and does the right thing when summing those units. It can handle any number of arbitrary whitespace characters separating the numbers. It also works whether the input is user-interactive, or input comes from stdin or a pipe. (It will bring up a user dialog for input when run in a graphical environment.)

sum[eval[split[%r/\s+/, input[""]]]]

FunL

println( sum(map(int, readLine().split(' +'))) )

Furor

cin sto mystring
#s dec mystring @mystring sprintnl
#g ."The length of the input is: " @mystring~ print ." characters.\n"
mylist @mystring 32 strtolist
."Quantity of the items: " mylist~ printnl
mylist~ mem sto nums
mylist 10 ![
."Item #" [:] #g print ." = " [|] sprintnl
@nums [:] [|] #s (#g) [^] ]
."Sum = "
0 #g mylist~ {| @nums {} [] + |}
printnl
@nums free @mystring free @mylist free
end
{ „mystring” }
{ „mylist” }
{ „nums” }
Output:
echo "23 6 11 7" | furor aplusb.upu 
23 6 11 7
The length of the input is: 9 characters.
Quantity of the items: 4
Item #0 = 23
Item #1 = 6
Item #2 = 11
Item #3 = 7
Sum = 47

echo "20 11" | furor aplusb.upu 
20 11
The length of the input is: 5 characters.
Quantity of the items: 2
Item #0 = 20
Item #1 = 11
Sum = 31




FutureBasic

The input statement was removed from FB several years ago. However, it's trivial to write our own input field which compiles as a stand-alone Macintosh application.

_window = 1
begin enum 1
  _label
  _input
  _result
end enum

void local fn BuildWindow
  window _window, @"A + B", ( 0, 0, 260, 200 )
  textlabel _label, @"Enter two signed integers separated by a comma, space/s or plus sign. Enter return to calculate.", ( 20, 130, 220, 48 ), _window
  textfield _input,,,( 20, 90, 220, 24 ), _window
  TextFieldSetMaximumNumberOfLines( _input, 1 )
  ControlSetFormat( _input, @"0123456789 ,+-", YES, 0, NULL )
  ControlSetAlignment( _input, NSTextAlignmentCenter )
  textlabel _result,, ( 20, 50, 220, 24 ), _window
  ControlSetAlignment( _result, NSTextAlignmentRight )
  WindowMakeFirstResponder( _window, _input )
end fn

local fn DoCalc
  NSInteger value1, value2
  CFStringRef calcStr = fn ControlStringValue( _input )
  calcStr = fn StringByReplacingOccurrencesOfString( calcStr, @",", @"\t" )
  calcStr = fn StringByReplacingOccurrencesOfString( calcStr, @"+", @"\t" )
  calcStr = fn StringByReplacingOccurrencesOfString( calcStr, @" ", @"\t" )
  CFArrayRef calcArr = fn StringComponentsSeparatedByString( calcStr, @"\t" )
  value1 = fn StringIntegerValue( fn ArrayFirstObject( calcArr ) )
  value2 = fn StringIntegerValue( fn ArrayLastObject(  calcArr ) )
  ControlSetStringValue( _result, fn StringWithFormat( @"%ld + %ld = %ld", value1, value2, value1 + value2 ) )
end fn

void local fn DoDialog( ev as long, tag as long, wnd as long )
  select ( ev )
    case _textFieldDidEndEditing : fn DoCalc
    case _windowWillClose        : end
  end select
end fn

on dialog fn DoDialog
fn BuildWindow

HandleEvents
Output:
-250 1000 = 750
or
-250,1000 = 750
or
-250 + 1000 = 750

Gambas

Public Sub Main()
Dim sInput As String = InputBox("Input 2 numbers seperated by a space", "A + B")

Print Split(sInput, " ")[0] & " + " & Split(sInput, " ")[1] & " = " & Str(Val(Split(sInput, " ")[0]) + Val(Split(sInput, " ")[1]))

End

Output:

999 + 888 = 1887

Gastona

Taking A and B from command line arguments

#listix#

   <main>
      "@<p1> + @<p2> = "
      =, p1 + p2

Using Graphical interface

#javaj#

   <layout of main>
      EVALAYOUT, 6, 6, 3,
         , A   , A
         , lA  , eA
         , lB  , eB
         , bSum, eRes

#listix#
   
   <-- bSum>
      MSG, eRes data!,, @<suma>
      
   <suma> =, eA + eB

GDScript

Requires Godot 4. Runs as a tool script using the input and output properties. Does not check for zero lines of input.

@tool
extends Node

@export var input: String:
	set(value):
		input = value # Save the input field

		var fields := value.split(" ", false) # Split by spaces
		if len(fields) == 2: # Basic input validation
			output = str(int(fields[0]) + int(fields[1]))
		else: # Invalid input
			output = ""

@export var output: String

Gema

<D> <D>=@add{$1;$2}

Genie

[indent=4]
/*
  A+B in Genie
  valac aplusb-genie.gs
  ./aplusb-genie
*/
init
    a:int64 = 0
    b:int64 = 0
    leftover:string = ""

    print "Enter A and B, two numbers separated by space"
    line:string = stdin.read_line()
    res:bool = int64.try_parse(line, out a, out leftover)
    res = int64.try_parse(leftover, out b)

    warning:string = " outside range (-1000, 1000), but it's ok, no one will tell"
    if a < -1000 or a > 1000
        print "A" + warning
    if b < -1000 or b > 1000
        print "B" + warning

    print "From %s\nA + B = %llu", line, a+b
Output:
prompt$ valac aplusb-genie.gs
prompt$ ./aplusb-genie
Enter A and B, two numbers separated by space
20 22
From 20 22
A + B = 42
prompt$ echo '123 234' | ./aplusb-genie
Enter A and B, two numbers separated by space
From 123 234
A + B = 357
prompt$ echo '123 2345' | ./aplusb-genie
Enter A and B, two numbers separated by space
B outside range (-1000, 1000), but it's ok, no one will tell
From 123 2345
A + B = 2468

GML

var add, a, b;
add = argument0; // get the string with the numbers to add
a = real(string_copy(add, 1, string_pos(" ", add)));
b = real(string_copy(add, string_pos(" ", add) + 1, string_length(add) - string_pos(" ", add)));
return(a + b);

Go

package main

import "fmt"

func main() {
    var a, b int
    fmt.Scan(&a, &b)
    fmt.Println(a + b)
}

Golfscript

~+

Golo

#!/usr/bin/env golosh
----
This module asks for two numbers, adds them, and prints the result.
----
module Aplusb

import gololang.IO

function main = |args| {

  let line = readln("Please enter two numbers (just leave a space in between them) ")
  let numbers = line: split("[ ]+"): asList()

  require(numbers: size() == 2, "we need two numbers")

  try {
    
    let a, b = numbers: map(|i| -> i: toInt())

    require(a >= -1000 and a <= 1000 and b >= -1000 and b <= 1000, "both numbers need to be between -1000 and 1000")

    println(a + b)
    
  } catch (e) {
    println("they both need to be numbers for this to work")
  }
}

Gosu

uses java.io.InputStreamReader
uses java.util.Scanner
uses java.lang.System

var scanner = new Scanner( new InputStreamReader( System.in ) )
var a = scanner.nextInt()
var b = scanner.nextInt()

print( a + b )

Groovy

def abAdder = {
    def reader = new Scanner(System.in)
    def a = reader.nextInt();
    def b = reader.nextInt();
    assert (-1000..1000).containsAll([a,b]) : "both numbers must be between -1000 and 1000 (inclusive)"
    a + b
}
abAdder()

GUISS

We cannot use variables, but we can find the sum of two numbers.Here we add 3 + 2:

Start,Programs,Accessories,Calculator,Button:3,Button:[plus],
Button:2,Button:[equals]

Harbour

PROCEDURE Main()
   LOCAL GetList := {}
   LOCAL bValid := { |n| iif(n>-1001, iif(n<1001, .T.,.F.),.F.) }
   LOCAL a := 0 , b := 0
   
   SetColor( "G+/N" )
   CLS
   @ 10, 01 SAY "Enter two integers (range -1000...+1000):" GET a VALID Eval(bValid,a)
   @ Row(), Col() + 1 GET b VALID Eval(bValid,b)
   READ
   @ 12, 01 SAY "Sum of given numbers is " +  hb_ntos(a+b)

   RETURN

Screen output:

Enter two numbers (range -1000...+1000): -56 98

Sum of given numbers is 42


Haskell

main =  print . sum . map read . words =<< getLine

hexiscript

fun split s delim
  let ret    dict 32
  let l      len s
  let j      0
  let ret[0] ""
  for let i 0; i < l; i++
    if s[i] = delim
      if len ret[j] > 0
        let ret[++j] ""
      endif
      continue
    endif
    let ret[j] (ret[j] + s[i])
  endfor
  return ret
endfun

let nums split (scan str) ' '
let a    tonum nums[0]
let b    tonum nums[1]
println a + b

HicEst

A and B are input via edit controls with spinners limiting inputs to +-1000.

DLG(Edit=A, DNum, MIn=-1000, MAx=1000, E=B, DN, MI=-1000, MA=1000)
WRITE(Messagebox, Name) A, B, "Sum = ", A+B

Hoon

|=  [a=@ud b=@ud]  (add a b)

Hope

This being my first hope program, and having no clue how to (have hope) read from stdin, I installed hope (but not hopeless) from https://github.com/dmbaturin/hope, read the Byte magazine article from 1980s which is a recast of the tutorial found in the github archive. Congratulations, the program worked on my first attempt.

$ cd lib
$ ../src/hope 
>: dec add : num # num -> num;
>: --- add(a,b) <= a + b;
>: add(3,99)
>: ^D
>> 102 : num

Huginn

import Algorithms as algo;
import Text as text;

main() {
  print(
    "{}\n".format(
      algo.reduce(
        algo.map(
          text.split( input().strip(), " " ),
          integer
        ),
        @( x, y ){ x + y; }
      )
    );
  );
}

Hy

(print (sum (map int (.split (input)))))

Alternatively, with the "threading tail" macro:

(->> (input) (.split) (map int) (sum) (print))

i

main: print(integer(in(' '))+integer(in('\n'))); ignore

Icon and Unicon

procedure main()
     numChars := '-'++&digits
     read() ? {
         A := (tab(upto(numChars)), integer(tab(many(numChars))))
         B := (tab(upto(numChars)), integer(tab(many(numChars))))
         }
     write((\A + \B) | "Bad input")
end

Idris

main : IO()
main = do
  line <- getLine
  print $ sum $ map cast $ words line

Insitux

(+ (to-num (prompt "Enter first number: "))
   (to-num (prompt "Enter second number: ")))

J

Typically, in J, you would find the sum of two numbers (let us say 2 and 3) by entering both of them on a line with a + sign between them:

   2+3
5

Next we describe then implement a command line program to add some numbers.

1) In the following expression, 1!:1(3) reads a line from STDIN; -.LF drops the line ending character; ". converts the remaining text to a sequence of numbers which are then summed using +/.

+/". (1!:1(3))-.LF

2) Here's a little script, called "a+b.ijs":

#!/usr/bin/ijconsole
echo +/". (1!:1(3))-.LF
exit ''

3) Here is an execution of the script:

echo 2 3 | ./a+b.ijs
5

Note: under OSX, you should probably install a symbolic link at /usr/bin/ijconsole which links to something like /Applications/j602/bin/jconsole.

Java

The task description is somewhat vague, if the 'input stream' is in reference to the data provided at the command line, then Java will parse these values into a String array, accessible via the args parameter of the main method.

public static void main(String[] args) {
    int A = Integer.parseInt(args[0]);
    int B = Integer.parseInt(args[1]);
    System.out.println(A + B);
}

If the 'input stream' is the standard-in, you can use the following.
The Scanner class can be used to "scan" the standard-in stream from left to right, returning the next value requested.

public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    int A = scanner.nextInt();
    int B = scanner.nextInt();
    System.out.println(A + B);
}

If the 'input stream' is referring to any abstraction, then you can use the following.
In this example, the data is considered to be under a specific charset, so the integer values are parsed using UTF-8.

import static java.nio.charset.StandardCharsets.UTF_8;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
int sum(InputStream input) throws IOException {
    BufferedReader reader = new BufferedReader(new InputStreamReader(input));
    String line = reader.readLine();
    reader.close();
    /* split parameter here is a regex */
    String[] values = line.split(" +");
    int A = Integer.parseInt(values[0]);
    int B = Integer.parseInt(values[1]);
    return A + B;
}


An alternate implemenation

import java.util.Scanner;

public class Sum2 {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in); // Standard input
        System.out.println(in.nextInt() + in.nextInt()); // Standard output
    }
}

Object of class Scanner works slow enough, because of that contestants prefer to avoid its use. Often, longer solution works faster and easily scales to problems.

import java.io.*;
import java.util.*;

public class SumDif {
   StreamTokenizer in;
   PrintWriter out;

   public static void main(String[] args) throws IOException {
      new SumDif().run();
   }

   private int nextInt() throws IOException {
      in.nextToken();
      return (int)in.nval;
   }

   public void run() throws IOException {
      in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in))); // Standard input
      out = new PrintWriter(new OutputStreamWriter(System.out)); // Standard output
      solve();
      out.flush();
   }

   private void solve() throws IOException {
      out.println(nextInt() + nextInt());
   }
}

The following code uses a StreamTokenizer instead of a Scanner.

import java.io.*;
import java.nio.charset.Charset;

public class AplusB {
    public static void main(String[] args) throws IOException {
        StreamTokenizer in = new StreamTokenizer(new InputStreamReader(System.in, Charset.defaultCharset()));
        in.nextToken();
        int a = (int) in.nval;
        in.nextToken();
        int b = (int) in.nval;

        try (Writer out = new OutputStreamWriter(System.out, Charset.defaultCharset())) {
            out.write(Integer.toString(a + b));
        }
    }
}


grammar aplusb ;

options {
	language = Java;
}

aplusb	:	(WS* e1=Num WS+ e2=Num NEWLINE {System.out.println($e1.text + " + " + $e2.text + " = " + (Integer.parseInt($e1.text) + Integer.parseInt($e2.text)));})+
	;
Num	:	'-'?('0'..'9')+
	;
WS	:	(' ' | '\t')
	;
NEWLINE	:	WS* '\r'? '\n'
        ;

Produces:

>java Test
1 2
23 89
13 567
-75 6
-75 -29
^Z
1 + 2 = 3
23 + 89 = 112
13 + 567 = 580
-75 + 6 = -69
-75 + -29 = -104

JavaScript

ES5

Client side:

<html>
<body>
<div id='input'></div>
<div id='output'></div>
<script type='text/javascript'>
var a = window.prompt('enter A number', '');
var b = window.prompt('enter B number', '');
document.getElementById('input').innerHTML = a + ' ' + b;

var sum = Number(a) + Number(b);
document.getElementById('output').innerHTML = sum;
</script>
</body>
</html>

Server side (with node.js):

process.openStdin().on (
    'data',
    function (line) {
        var xs = String(line).match(/^\s*(\d+)\s+(\d+)\s*/)
        console.log (
            xs ? Number(xs[1]) + Number(xs[2]) : 'usage: <number> <number>'
        )
        process.exit()
    }
)
$ node io.js
2 3
5
$ node io.js
x 3
usage: <integer> <integer>

ES6

Node.js in a terminal:

process.stdin.on("data", buffer => {
  console.log(
    (buffer + "").trim().split(" ").map(Number).reduce((a, v) => a + v, 0)
  );
});
 $ node io.js
 2 3
 5

JScript Windows Script Host Version 5.8

var a = WScript.StdIn.ReadLine();
var b = WScript.StdIn.ReadLine();
WSH.echo(a, " + " , b , " = " , Number(a)+Number(b));

Joy

Console

get get +.

File

"input.txt" include
"output.txt" "w" fopen
get get + fput pop quit.

jq

Since the given task is simply to add two numbers, the simplest approach in jq is illustrated by the following transcript:

$ jq -s add
3 2
5

This will work provided the numbers are neither too small nor too large. However, the above program will add **all** the numbers presented on the stream (assuming only numbers are presented). If the task were to add consecutive pairs of numbers, then the approach illustrated in the following transcript can be used, in conjunction with the jq "-s" option:

def addpairs:
  if length < 2 then empty
  else (.[0] + .[1]), (.[2:] | addpairs)
  end;

addpairs

For example, here is a transcript that assumes the program is in a file named AB.jq:

$ jq -s -f AB.jq
1 2 3 4 5 6
3
7
11

Jsish

/* A+B in Jsish */
var line = console.input();
var nums = line.match(/^\s*([+-]?[0-9]+)\s+([+-]?[0-9]+)\s*/);
if (nums) {
    var A = Number(nums[1]);
    var B = Number(nums[2]);
    if (A <= 1000 && A >= -1000 && B <= 1000 && B >= -1000) {
        printf("%d\n", A + B);
    } else {
        puts("error: A and B both need to be in range -1000 thru 1000 inclusive");
    }
} else {
    puts("error: A+B requires two numbers separated by space");
}
Output:
prompt$ jsish A+B.jsi
a b
error: A+B requires two numbers separated by space
prompt$ jsish A+B.jsi
1234 123
error: A and B both need to be in range -1000 thru 1000 inclusive
prompt$ jsish A+B.jsi
-1000 +1000
0
prompt$ jsish A+B.jsi
123 -234
-111

Julia

Run from the command line:

input = parse.(Int, split(readline(stdin)))
println(stdout, sum(input))
Output:
>julia AB.jl
1 1
2

In the next solution, an error is returned if the entry is not constituted from exactly two integers. Any number of spaces can follow an integer.

julia> println(parse(Int, readuntil(stdin, ' ')) + parse(Int, readuntil(stdin, '\n')))
1 2  
3

K

  split:{(a@&~&/' y=/: a:(0,&x=y)_ x) _dv\: y}
  ab:{+/0$split[0:`;" "]}
  ab[]
2 3
5

Keg

+.

Try it online!

Or, using flags (-hr):

+

Try it online!

Kite

#!/usr/bin/kite

import "System.file";

in = System.file.stdin;
line = in|readline;
while(not (line is null)) [
    arry = line|split(" ");
    result = (arry[0])|int + (arry[1])|int;
    result|print;

    line = in|readline;
];
Output:
$ kite a_plus_b.kt <<EOF
5 6
EOF
11
$

Klong

  {(1:$(*x?0c )#x)+1:$(1+*|x?0c )_x}@.rl()
2 3
5

Kotlin

// version 1.0.5-2

fun main(args: Array<String>) {
    val r = Regex("""-?\d+[ ]+-?\d+""")
    while(true) {
        print("Enter two integers separated by space(s) or q to quit: ")
        val input: String = readLine()!!.trim()
        if (input == "q" || input == "Q") break
        if (!input.matches(r)) {
            println("Invalid input, try again")
            continue
        }
        val index = input.lastIndexOf(' ')
        val a = input.substring(0, index).trimEnd().toInt()
        val b = input.substring(index + 1).toInt()
        if (Math.abs(a) > 1000 || Math.abs(b) > 1000) {
            println("Both numbers must be in the interval [-1000, 1000] - try again")
        }
        else {
            println("Their sum is ${a + b}\n")
        }
    }       
}
Output:
Enter two integers separated by space(s) or q to quit: 2 2
Their sum is 4

Enter two integers separated by space(s) or q to quit: 3 2
Their sum is 5

Enter two integers separated by space(s) or q to quit: q

KQL

datatable(Input:string)[
    '2 2',
    '3 2'
]
| parse Input with A:int ' ' B:int
| project Input, Output = A + B

L++

(main
  (decl int a)
  (decl int b)
  (>> std::cin a b)
  (prn (+ a b)))

Lambdatalk

Lambdatalk works in a wiki, lambdatank.

1) Open the wiki frame-editor and define a contenteditable box

{def box
 {pre
  {@ contenteditable 
     style="box-shadow:0 0 8px #000; padding:5px;" 
            ondblclick="this.innerHTML=LAMBDATALK.eval_forms(this.innerHTML)"
}}}
-> blockedit

2) create this box

{box}

   and close the wiki frame-editor. The wiki-page displays a shadowed box, 
(here simulated as a space between square brackets)

[                                                                    ]

3) Enter any valid lambdatalk expression, for instance

1+2+3 is equal to {+ 1 2 3}

then double-click. The expression is evaluated and the box displays

[ 1+2+3 is equal to 6                                                ]

Several boxes can be created in the wiki page 
with any valid lambdatalk expressions.

Lang

fn.print(First number:\s)
$a = fn.int(fn.input())

fn.print(Second number:\s)
$b = fn.int(fn.input())

fn.println(Result: parser.op($a + $b))

Lang5

read read + .

read " " split expand drop + .

Lasso

[a + b]

LIL

# A+B, in LIL
# Requires lil shell readline routine
set in [readline]
set A [index $in 0]
set B [index $in 1]
if [expr $A < -1000 || $A > 1000] { print "A out of range: $A"; exit 1 }
if [expr $B < -1000 || $B > 1000] { print "B out of range: $B"; exit 1 }
print [expr $A + $B]
Output:
prompt$ echo '40 2' | lil AB.lil
42

Lisaac

Section Header
 + name := A_PLUS_B

Section Public
 - main <- (    (IO.read_integer; IO.last_integer) +
                (IO.read_integer; IO.last_integer) ).println;

Little

void main() {
    string a, b;
    scan(gets(stdin), "%d %d", &a, &b); 
    puts(((int)a + (int)b));
}

Little Man Computer

Note: Both numbers are entered separately.

This is the "add" example from V1.3 of the implementation of Little Man Computer by Peter Higginson.

Assembly

        INP
        STA 99
        INP
        ADD 99
        OUT
        HLT
// Output the sum of two numbers

Machine code

00 INP
01 STA 99
02 INP
03 ADD 99
04 OUT
05 HLT

LiveCode

Using Livecode Server script

<?lc
if isNumber($0) and isNumber($1) then
    put $0 + $1
else
    put $0 && $1
end if
?>

A graphical version using an input dialog

on mouseUp
    ask "Enter two numbers"
    set itemdelimiter to space
    put it into nums
    if isNumber(item 1 of nums) and isNumber(item 2 of nums) then
        answer item 1 of nums + item 2 of nums
    else
        answer item 1 of nums && item 2 of nums
    end if
end mouseUp

show apply "sum readlist

Lua

a,b = io.read("*number", "*number")
print(a+b)

M2000 Interpreter

Def Range(X%)=Abs(X%)<=1000
Do {
      Input A%, B%
} Until Range(A%) And Range(B%)
Print A%+B%

M4

 define(`sumstr', `eval(patsubst(`$1',` ',`+'))')

sumstr(1 2)
3

Maple

 convert( scanf( "%d %d" ), '`+`' );
23 34
                                   57

Mathematica/Wolfram Language

Interactive in a notebook

Input[] + Input[]

MATLAB / Octave

function sumOfInputs = APlusB()
    inputStream = input('Enter two numbers, separated by a space: ', 's');
    numbers = str2num(inputStream);                         %#ok<ST2NM>
    if any(numbers < -1000 | numbers > 1000)
        warning('APlusB:OutOfRange', 'Some numbers are outside the range');
    end
    sumOfInputs = sum(numbers);    
end

Maude

Built-in

red 3 + 4 .

With restrictions

fmod ADD is

	protecting INT .
	
	op undefined : -> Int .
	op _add_ : Int Int -> Int [assoc comm] .
	
	vars A B : Int .
	
	eq A add B = if (A < -1000 or B < -1000) or (A > 1000 or B > 1000) then undefined else A + B fi .
	
endfm

Maxima

in_stream: openr("/dev/stdin");
unless (line: readline(in_stream), line=false) do (
                 q: map('parse_string, split(line, " ")),
                 print(q[1]+q[2])
      );
close(in_stream);

Mercury

:- module a_plus_b.
:- interface.

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

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

main(!IO) :-
   io.read_line_as_string(Result, !IO),
   ( if
        Result = ok(Line),
        [AStr, BStr] = string.words(Line),
        string.to_int(AStr, A), string.to_int(BStr, B)
     then
        io.format("%d\n", [i(A + B)], !IO)
     else
        true
    ).

min

Works with: min version 0.19.3
gets " " split 'bool filter 'int map sum puts!

MiniScript

The input intrinsic in MiniScript isn't available in all implementations, so we've just hard-coded the input here:

s = "  2    3  "
fields = s.split
for i in range(fields.len-1, 0)
    if fields[i] == "" then fields.remove i
end for
if fields.len < 2 then
    print "Not enough input"
else
    print val(fields[0]) + val(fields[1])
end if
Output:
5

mIRC Scripting Language

alias a+b {
  echo -ag $calc($1 + $2)
}

МК-61/52

С/П + С/П

ML/I

The two numbers are read from 'standard input' or its equivalent.

MCSKIP "WITH" NL
"" A+B
"" assumes macros on input stream 1, terminal on stream 2
MCSKIP MT,<>
MCINS %.
MCDEF SL SPACES NL AS <MCSET T1=%A1.
MCSET T2=%A2.
%T1+T2.
MCSET S10=0
>
MCSKIP SL WITH *
MCSET S1=1
*MCSET S10=2

Modula-2

MODULE  ab;

IMPORT  InOut;

VAR     A, B    : INTEGER;

BEGIN
  InOut.ReadInt (A);
  InOut.ReadInt (B);
  InOut.WriteInt (A + B, 8);
  InOut.WriteLn
END ab.

Modula-3

MODULE Ab EXPORTS Main;

IMPORT IO;

VAR
     A,B:INTEGER;
BEGIN
     TRY
	  A := IO.GetInt();
          B := IO.GetInt();
     EXCEPT
     | IO.Error => IO.Put("Invalid number!\n");
     END;
     IO.PutInt(A+B);
     IO.Put("\n");
END Ab.

MoonScript

a,b = io.read '*number','*number'
print a + b

Mosaic

proc main =
    int a, b

    print "?"
    readln a, b
    println a + b
end

MUMPS

ANB
 NEW A,B,T,S
 READ !,"Input two integers between -1000 and 1000, separated by a space: ",S
 SET A=$PIECE(S," ",1),B=$PIECE(S," ",2)
 SET T=(A>=-1000)&(A<=1000)&(B>=-1000)&(B<=1000)&(A\1=A)&(B\1=B) 
 IF T WRITE !,(A+B)
 IF 'T WRITE !,"Bad input"
 QUIT

Nanoquery

// get a line of input
line = input()
 
// split the line
strings = split(line, " ")
 
// add the two numbers and print the result
println int(strings[0]) + int(strings[1])

Neko

/**
 A+B, Rosetta Code, in Neko
 Tectonics:
   nekoc a+b.neko
   echo '4 5' | neko a+b.n
*/

/* load some primitives */
var regexp_new = $loader.loadprim("regexp@regexp_new", 1)
var regexp_match = $loader.loadprim("regexp@regexp_match", 4)
var regexp_matched = $loader.loadprim("regexp@regexp_matched", 2)

var stdin = $loader.loadprim("std@file_stdin", 0)()
var file_read_char = $loader.loadprim("std@file_read_char", 1)

/* Read a line from file f into string s returning length without any newline */
var NEWLINE = 10
var readline = function(f, s) {
    var len = 0
    var ch
    while true {
        try ch = file_read_char(f) catch a break;
        if ch == NEWLINE break;
        if $sset(s, len, ch) == null break; else len += 1
    }
    return len
}

/* Trim a string of trailing NUL and spaces, returning substring */
var SPACE = 32
var trim = function(s) {
    var len = $ssize(s)
    var ch
    while len > 0 {
        ch = $sget(s, len - 1)
        if ch != 0 && ch != SPACE break; else len -= 1
    }
    return $ssub(s, 0, len)
}

/* The A+B task */
var RECL = 132
try {
    /* whitespace(s), digit(s), whitespace(s), digit(s) */
    var twonums = regexp_new("^\\s*(\\d+)\\s+(\\d+)\\b")
    var s = $smake(RECL)
    var len = readline(stdin, s)
    s = trim(s)

    var valid = regexp_match(twonums, s, 0, $ssize(s))
    if valid {
        var first = regexp_matched(twonums, 1)
        var second = regexp_matched(twonums, 2)

        first = $int(first)
        second = $int(second)

        if first < -1000 || first > 1000 $throw("First value out of range -1000,1000")
        if second < -1000 || second > 1000 $throw("Second value out of range -1000,1000")

        $print($int(first) + $int(second), "\n")

    } else $print("Need two numbers, separated by whitespace\n")

} catch with $print("Exception: ", with, "\n")
Output:
prompt$ nekoc a+b.neko
prompt$ echo '2 2' | neko a+b
4
prompt$ neko a+b
2 3
5

Nemerle

Translation of: C#
using System;
using System.Console;
using System.Linq;

module AplusB
{
    Main() : void
    {
        WriteLine(ReadLine().Split().Select(int.Parse).Sum());
    }    
}

NetRexx

/* NetRexx */

options replace format comments java symbols binary

parse ask a b .
say a '+' b '=' a + b

newLISP

(println (apply + (map int (parse (read-line)))))

Nim

A+B:

# Takes 2 inputs of Floats and adds them (which is not correct for the exercise, will revisit, Thank you

from strutils import parseFloat, formatFloat, ffDecimal

proc aplusb(a,b: float): float =
  return a + b

proc getnumber(): float =
  try:
    parseFloat(readLine(stdin))
  except ValueError:
    echo("Please enter a number: ")
    getnumber()

echo("First number please: ")
let first: float = getnumber()

echo("Second number please: ")
let second: float = getnumber()

echo("Result: " & formatFloat(aplusb(first, second), ffDecimal, 2))

The puzzle requires 1 input, 2 INTS separated by a space, than a+b Needs to be revisited

Nit

Generic non-robust version (source: the Nit’s official repository):

module ab

var words = gets.split(" ")
if words.length != 2 then
	print "Expected two numbers"
	return
end
print words[0].to_i + words[1].to_i

NS-HUBASIC

10 INPUT "ENTER NUMBER A: ",A
20 INPUT "ENTER NUMBER B: ",B
30 PRINT A+B

Nu

input | parse "{a} {b}" | first | values | into int | math sum

Nutt

module main
imports native.io{input.hear,output.say}

vals a=hear(Int),b=hear(Int)
say(a+b)

end

Nyquist

SAL Syntax

;nyquist plug-in
;version 1
;type tool
;name "A+B"
;debugflags trace
 
define variable a = 1
define variable b = 9
 
print a + b
 
return ""

Audacity plug-in (SAL syntax)

;nyquist plug-in
;version 1
;type tool
;name "A+B"
;debugflags trace

define variable a = 1
define variable b = 9

print a + b

return ""

Oberon-2

MODULE  ab;

IMPORT  In, Out;

VAR     A, B    : INTEGER;

BEGIN
  In.Int (A);
  In.Int (B);
  Out.Int (A + B, 8);
  Out.Ln
END ab.

Producing

12 34
      46

Objeck

bundle Default {
   class Vander {
      function : Main(args : String[]) ~ Nil {
         values := IO.Console->ReadString()->Split(" ");
         if(values->Size() = 2) { 
            (values[0]->Trim()->ToInt() + values[1]->Trim()->ToInt())->PrintLine();
         };
      }
   }
}

OCaml

Scanf.scanf "%d %d" (fun a b -> Printf.printf "%d\n" (a + b))

Oforth

Works with any number of integers separated by a space.

import: mapping

System.Console accept words map( #>integer) reduce( #+ ) printcr .

Ol

Note: input data must be separated by newline ([Enter] key press).

; simplest
(+ (read) (read))

; safe
(let ((a (read))
      (b (read)))
   (if (not (number? a))
      (runtime-error "a is not a number! got:" a))
   (if (not (number? b))
      (runtime-error "b is not a number! got:" b))

   (print a " + " b " = " (+ a b)))

Onyx

$Prompt {
  `\nEnter two numbers between -1000 and +1000,\nseparated by a space: ' print flush
} def

$GetNumbers {
  mark stdin readline pop # Reads input as a string. Pop gets rid of false.
  cvx eval # Convert string to integers.
} def

$CheckRange { # (n1 n2 -- bool)
  dup -1000 ge exch 1000 le and
} def

$CheckInput {
  counttomark 2 ne
    {`You have to enter exactly two numbers.\n' print flush quit} if
  2 ndup CheckRange exch CheckRange and not
    {`The numbers have to be between -1000 and +1000.\n' print flush quit} if
} def

$Answer {
  add cvs `The sum is ' exch cat `.\n' cat print flush
} def

Prompt GetNumbers CheckInput Answer

ooRexx

version 1

Translation of: REXX
Numeric digits 1000             /*just in case the user gets ka-razy. */
Say 'enter some numbers to be summed:'
parse pull y
yplus=add_plus(y)
sum=0
Do While y<>''
  Parse Var y n y
  If datatype(n)<>'NUM' Then Do
    Say 'you entered  something that is not recognized to be a number:' n
    Exit
    End
  sum+=n
  End
Say yplus '=' sum/1
Exit
add_plus:
Parse arg list
list=space(list)
return translate(list,'+',' ')
Output:
enter some numbers to be summed:
1e10+7.777+33 = 10000000040.777

version 2

extend for negative numbers

Numeric digits 1000
Say 'enter some numbers to be summed:'
parse pull y
sum=0
yplus=''
Do i=1 By 1 While y<>''
  Parse Var y n y
  If datatype(n)<>'NUM' Then Do
    Say 'you entered  something that is not recognized to be a number:' n
    Exit
    End
  Select
    When i=1 Then
      yplus=n
    When n>0 Then yplus||='+'abs(n)
    Otherwise yplus||=n
    End
  sum+=n
  End
Say yplus '=' sum/1
Exit

OpenEdge/Progress

DEFINE VARIABLE a AS INTEGER NO-UNDO FORMAT "->>>9".
DEFINE VARIABLE b AS INTEGER NO-UNDO FORMAT "->>>9".

IF SESSION:BATCH THEN DO:
   INPUT FROM "input.txt".
   IMPORT a b.
   INPUT CLOSE.
END.
ELSE
   UPDATE a b.

MESSAGE a + b VIEW-AS ALERT-BOX

Openscad

There is no means of run-time input in Openscad

a = 5 + 4;
echo (a);

Order

Since Order is implemented in the C pre-processor, which cannot express arithmetic operations, this program has been built around Order's standard library simulated natural number arithmetic implementation, extended to handle a sign bit.

To run this Order program, you must define the macros A and B to values of the form 8int(SIGN, 8nat(VALUE)), where SIGN is 1/0 to represent signed/unsigned numbers, and VALUES is any comma-separated list of decimal digits. For example, to evaluate the sum of A=-150, B=275, define A to be 8int(1, 8nat(1,5,0)) and B to be 8int(0, 8nat(2,7,5)).

#define ORDER_PP_DEF_1int_is_positive \
    ORDER_PP_FN(8fn(8X, 8is_0(8tuple_at_0(8X))))

#define ORDER_PP_DEF_1int_get_unsigned \
    ORDER_PP_FN(8fn(8X, 8tuple_at_1(8X)))

#define ORDER_PP_DEF_1int_add_impl \
    ORDER_PP_FN(8fn(8A, 8B, 8S, 8int(8S, 8add(8A, 8B))))

#define ORDER_PP_DEF_1int_sub_impl \
    ORDER_PP_FN(8fn(8A, 8B, \
                    8if(8greater(8A, 8B), \
                        8int(0, 8sub(8A, 8B)), \
                        8int(1, 8sub(8B, 8A)))))

#define ORDER_PP_DEF_8int_add \
    ORDER_PP_FN(8fn(8A, 8B, \
                    8cond((8and(1int_is_positive(8A), 1int_is_positive(8B)), \
                                1int_add_impl(1int_get_unsigned(8A), 1int_get_unsigned(8B), 0)) \
                          (8and(1int_is_positive(8A), 8not(1int_is_positive(8B))), \
                                1int_sub_impl(1int_get_unsigned(8A), 1int_get_unsigned(8B))) \
                          (8and(8not(1int_is_positive(8A)), 1int_is_positive(8B)), \
                                1int_sub_impl(1int_get_unsigned(8B), 1int_get_unsigned(8A))) \
                          (8and(8not(1int_is_positive(8A)), 8not(1int_is_positive(8B))), \
                                1int_add_impl(1int_get_unsigned(8A), 1int_get_unsigned(8B), 1)))))

#define ORDER_PP_DEF_8int_to_lit \
    ORDER_PP_FN(8fn(8X, \
                    8if(1int_is_positive(8X), \
                        8to_lit(1int_get_unsigned(8X)), \
                        8adjacent(8(-), 8to_lit(1int_get_unsigned(8X))))))

#define ORDER_PP_DEF_8int \
    ORDER_PP_FN(8fn(8S, 8N, 8pair(8S, 8N)))

ORDER_PP(8int_to_lit(8int_add(A, B)))

Oxygene

// Sum 2 integers read fron standard input
//
// Nigel Galloway - April 16th., 2012
//
namespace aplusb;
 
interface
  uses System.Text.RegularExpressions.*;
 
type
  aplusb = class
  public
    class method Main; 
  end;
 
implementation
 
class method aplusb.Main;
var 
  gc: GroupCollection;
  m : Match;
begin
  m := new Regex('^\s*(?<a>-?[1-9]\d{0,2}|0|-?1000)\s+(?<b>-?[1-9]\d{0,2}|0|-?1000)\s*$').Match(Console.ReadLine());
  if m.Success then
    begin
      gc := m.Groups;
      Console.WriteLine("{0} + {1} = {2}", gc['a'].Value, gc['b'].Value, Integer.Parse(gc['a'].Value) + Integer.Parse(gc['b'].Value));
    end
  else Console.WriteLine("Invalid Input");
end;
 
end.

Produces:

>aplusb
23 -99
23 + -99 = -76

Oz

declare
  class TextFile from Open.file Open.text end

  StdIn = {New TextFile init(name:stdin)}

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

PARI/GP

User input:

input()+input()

File input:

read("file1")+read("file2")

Pascal

var
   a, b: integer;
begin
   readln(a, b);
   writeln(a + b);
end.

Same with input from file input.txt and output from file output.txt.

var
   a, b: integer;
begin
   reset(input, 'input.txt');
   rewrite(output, 'output.txt');
   readln(a, b);
   writeln(a + b);
   close(input);
   close(output);
end.

Version 2. Following the rules

{ Task: A + B
Sum of A + B while A, B >= -1000 and A,B <= 1000
Author: Sinuhe Masan (2019) }
program APlusB;

var
    A, B : integer;

begin
    repeat
        write('Enter two numbers betwen -1000 and 1000 separated by space: ');
        readln(A, B);

    until ((abs(A) < 1000) and (abs(B) < 1000));

    writeln('The sum is: ', A + B);

end.

Perl

my ($a,$b) = split(' ', scalar(<STDIN>));
print "$a $b " . ($a + $b) . "\n";

using the List::Util module

say sum split /\s+/,  scalar <STDIN>;

Phix

-- demo\rosetta\AplusB.exw
string s = prompt_string("Enter two numbers separated by a space : ")
sequence r = scanf(s,"%d %d")
if length(r)=1 then
    integer {a,b} = r[1], c = a+b
    printf(1,"%d + %d = %d\n",{a,b,c})
else
    printf(1,"invalid input\n")
end if
Output:
Enter two numbers separated by a space : 2 3
2 + 3 = 5

GUI version

Library: Phix/pGUI

(The above console version is now just a comment in the distributed file.)

-- demo\rosetta\AplusB.exw
with javascript_semantics
include pGUI.e
Ihandle lab, tab, res, dlg

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

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

Phixmonti

/# Rosetta Code problem: http://rosettacode.org/wiki/A+B
by Galileo, 05/2022 #/

include ..\Utilitys.pmt

def valid
    dup -1000 >= swap 1000 <= and
enddef

true while
    clear cls
    "Enter two numbers (betwen -1000 ... +1000) separated by space: " input split pop pop drop tonum swap tonum
    over valid over valid and not
endwhile

over over + >ps
nl "The sum of " print  print " and " print print " is: " print ps> print
/#
swap over over + >ps >ps >ps
nl ( "The sum of " ps> " and " ps> " is: " ps> ) lprint
#/
Output:
Enter two numbers (betwen -1000 ... +1000) separated by space: 2 3
The sum of 2 and 3 is: 5
=== Press any key to exit ===

PHP

fscanf(STDIN, "%d %d\n", $a, $b); //Reads 2 numbers from STDIN
echo ($a + $b) . "\n";
$in = fopen("input.dat", "r");
fscanf($in, "%d %d\n", $a, $b); //Reads 2 numbers from file $in
fclose($in);

$out = fopen("output.dat", "w");
fwrite($out, ($a + $b) . "\n");
fclose($out);

Picat

go =>
   println("Write two integers (and CR)"),
   println(read_int()+read_int()).
Output:
Picat> go
Write two integers (and CR)
2 5
7

Or directly in the REPL:

Picat> read_int()+read_int()=X
2 5
X = 7

PicoLisp

(+ (read) (read))
3 4               
-> 7

Piet

The code is fairly straightforward. The individual commands are as follows:

in(num)
in(num)
add
out(num)

Pike

string line = Stdio.stdin->gets();
sscanf(line, "%d %d", int a, int b);
write(a+b +"\n");

PL/I

get (a, b);
put (a+b);

Plain English

To run:
Start up.
Read a number from the console.
Read another number from the console.
Output the sum of the number and the other number.
Wait for the escape key.
Shut down.

To output the sum of a number and another number:
If the number is not valid, write "Invalid input" to the console; exit.
If the other number is not valid, write "Invalid input" to the console; exit.
Write the number plus the other number then " is the sum." to the console.

To decide if a number is valid:
If the number is not greater than or equal to -1000, say no.
If the number is not less than or equal to 1000, say no.
Say yes.

Pony

actor Main
    let _env:Env
    new create(env:Env)=>
        _env=env
        env.input(object iso is InputNotify
            let _e:Main=this
            fun ref apply(data:Array[U8] iso)=>
                _e(consume data)
            fun ref dispose()=>
                None
        end,
            512)
    be apply(s:Array[U8] iso)=>
        let c=String.from_iso_array(consume s)
        let parts:Array[String]=c.split(" ",0)
        var sum:I32=0
        try
            for v in parts.values() do
                sum=sum+match v.read_int[I32](0)?
                |(let x:I32,_)=>x
                end
            end
        end
        _env.out.print(sum.string())

PostScript

(%stdin) (r) file  % get stdin
dup
token pop          % read A
exch
token pop          % read B
add
=

Potion

# The numbers are entered, piped, or redirected in via STDIN and the format is proper (i.e., "%d %d").
input = read
i = 0
while (i < input length):
   if (input(i) == " "):
      break
   .
   i++
.
(input slice(0, i) number + input slice(i, nil) number) print

# The numbers are manually inputted, but the format is improper (i.e., "%d\n%d\n").
(read number + read number) print

PowerShell

$a,$b = -split "$input"
[int]$a + [int]$b

This solution does not work interactively, while the following only works interactively:

$a,$b = -split (Read-Host)
[int]$a + [int]$b

I think this works better and doesn't require string input (following the task closer):

filter add { 
    return [int]$args[0] + [int]$args[1]
}

Can be called in one line with

add 2 3

Processing

Rudimentary User Interface

Click on either side to add 1 to its value.

int a = 0;
int b = 0;

void setup() {
  size(200, 200);
}

void draw() {
  fill(255);
  rect(0, 0, width, height);
  fill(0);
  line(width/2, 0, width/2, height * 3 / 4);
  line(0, height * 3 / 4, width, height * 3 / 4);
  text(a, width / 4, height / 4);
  text(b, width * 3 / 4, height / 4);
  text("Sum: " + (a + b), width / 4, height * 7 / 8);
}

void mousePressed() {
  if (mouseX < width/2) {
    a++;
  } else {
    b++;
  }
}

What the GUI looks like.

ProDOS

With the math module:

editvar /newvar /value=a /title=Enter an integer:
editvar /newvar /value=b /title=Enter another integer:
editvar /newvar /value=c 
do add -a-,-b-=-c-
printline -c-

Without the math module:

editvar /newvar /value=a /title=Enter an integer:
editvar /newvar /value=b /title=Enter another integer:
editvar /newvar /value=c=-a-+-b-
printline -c-

Prolog

Works with: SWI-Prolog
plus :-
    read_line_to_codes(user_input,X),
    atom_codes(A, X),
    atomic_list_concat(L, ' ', A),
    maplist(atom_number, L, LN),
    sumlist(LN, N),
    write(N).

output :

?- plus.
|: 4 5
9
true.

Pure

using system;
printf "%d\n" (x+y) when x,y = scanf "%d %d" end;

PureBasic

Console

x$=Input()
a=Val(StringField(x$,1," "))
b=Val(StringField(x$,2," "))
PrintN(str(a+b))

File

If ReadFile(0,"in.txt")
  x$=ReadString(0)
  a=Val(StringField(x$,1," "))
  b=Val(StringField(x$,2," "))
  If OpenFile(1,"out.txt")
    WriteString(1,str(a+b))
    CloseFile(1)
  EndIf
  CloseFile(0)
EndIf

Python

Console

In Python 2, input returns ints, while raw_input returns strings. In Python 3, input returns strings, and raw_input does not exist.

The first two lines allow the program to be run in either Python 2 or 3. In Python 2, raw_input exists, and the lines are effectively skipped. In Python 3, calling raw_input triggers an error, so the except loop activates and assigns "raw_input" the value of Python 3's "input" function. Regardless of version, these two lines make sure that raw_input will return a string.

try: raw_input
except: raw_input = input

print(sum(map(int, raw_input().split())))

File

For Python 2.X and 3.X taking input from stdin stream which can be redirected to be file input under Unix

import sys

for line in sys.stdin:
    print(sum(map(int, line.split())))

Console, Python 3 only

a = int(input("First number: "))
b = int(input("Second number: "))
print("Result:", a+b)

QB64

DIM a AS INTEGER, b AS INTEGER
DIM c AS LONG
INPUT "Enter A: ", a
INPUT "Enter B: ", b
c = a + b
PRINT ""
PRINT "A + B = " + LTRIM$(STR$(c))

Fully implemented version:
CBTJD: 2020/03/13


  • Task description requires:
    • Both integers entered on one line.
    • Integers between -1000 and +1000.
START:
PRINT "Enter two integers between -1000 and +1000 separated by at least one space: "
INPUT "> "; n$ '                   | Enter two numbers with at least one space between.
n$ = _TRIM$(n$) '                  | TRIM any leading or trailing spaces.
bpos = INSTR(n$, " ") '            | Find the first space between the two numbers.
a = VAL(LEFT$(n$, bpos - 1)) '     | Parse the first number from the input string.
b = VAL(_TRIM$(MID$(n$, bpos))) '  | Parse the second number from the input string.
IF (a < -1000 OR a > 1000) OR (b < -1000 OR b > 1000) THEN
  PRINT "A number is outside of limit (-1000 to +1000). Try again.": PRINT
  GOTO START '                     | Check both number are within prescribed limit.
END IF
a$ = LTRIM$(STR$(a)) '             | Clean up both numbers and the sum for better printing.
b$ = LTRIM$(STR$(b)) '             | "
sum$ = LTRIM$(STR$(a + b)) '       | "
PRINT "The sum of the two integers a + b = "; a$; " + "; b$; " = "; sum$

Quackery

As a dialogue in the Quackery shell:

/O> $ "Please enter two numbers separated by a space: " input
... say "Their sum is: " quackery + echo cr
... 
Please enter two numbers separated by a space: 2 3 
Their sum is: 5

Stack empty.

Quite BASIC

10 input "Enter number A: ";a
20 input "Enter number B: ";b
30 print a+b

R

sum(scan("", numeric(0), 2))

Ra

class Sum
	**Adds two given integers**
	
	on start
		
		args := program arguments
		
		if args empty
			print to Console.error made !, "No arguments given"
			exit program with error code
		
		if args.count = 1
			print to Console.error made !, "Only one argument given"
			exit program with error code
		
		try
			print integer.parse(args[0]) + integer.parse(args[1])
		
		catch FormatException
			print to Console.error made !, "Arguments must be integers"
			exit program with error code
		
		catch OverflowException
			print to Console.error made !, "Numbers too large"
			exit program with error code

Racket

#lang racket
(+ (read) (read))

Or, with additional error checking:

#lang racket
(define a (read))
(unless (number? a) (error 'a+b "number" a))
(define b (read))
(unless (number? b) (error 'a+b "number" b))
(displayln (+ a b))

Raku

(formerly Perl 6)

Works with: rakudo version 2015.12

Short version with very little "line noise":

get.words.sum.say;

Reduction operator [+], and say as a function:

say [+] get.words;

Long version:

my ($a, $b) = $*IN.get.split(" ");
say $a + $b;

REBOL

forever [x: load input  print x/1 + x/2]
Output:
1 2
3
2 2
4
3 2
5

Red

x: load input  print x/1 + x/2
Output:
1 2
3
2 2
4
3 2
5

Alternative implementations:

print (first x: load input) + x/2
print head insert load input 'add
print load replace input " " " + "

Relation

set input = "2 2"
set a = regexreplace(input,"^(-?\d+)\s+(-?\d+)+$","$1")
set b = regexreplace(input,"^(-?\d+)\s+(-?\d+)+$","$2")
echo a + b

Retro

:try ("-n) s:get s:to-number s:get s:to-number + n:put ;
try
1
2

REXX

version 1, unnormalized

The numbers can be any valid REXX number (integer, fixed point decimal, floating point (with exponential notation, ···).

/*REXX program obtains two numbers from the input stream (the console), shows their sum.*/
parse pull a b                                   /*obtain two numbers from input stream.*/
say a+b                                          /*display the sum to the terminal.     */
                                                 /*stick a fork in it,  we're all done. */

version 2, normalizied

If the user entered   4.00000   and wanted to add   5   to that, and expects   9,
then the output needs to be normalized before displaying the result.

Normally, REXX will keep the greatest precision in the results;
adding   4.00000   and   5   will normally yield   9.00000

Dividing by one normalizes the number.

/*REXX program obtains two numbers from the input stream (the console), shows their sum.*/
parse pull a b                                   /*obtain two numbers from input stream.*/
say (a+b) / 1                                    /*display normalized sum to terminal.  */
                                                 /*stick a fork in it,  we're all done. */

version 3, extended precision

Using the   numeric digits   statement allows more decimal digits to be used, the default is   9.

/*REXX program obtains two numbers from the input stream (the console), shows their sum.*/
numeric digits 300                               /*the default is  nine  decimal digits.*/
parse pull a b                                   /*obtain two numbers from input stream.*/
z= (a+b) / 1                                     /*add and normalize sum, store it in Z.*/
say z                                            /*display normalized sum Z to terminal.*/
                                                 /*stick a fork in it,  we're all done. */

version 4, multiple numbers

This REXX version adds   all   the numbers entered   (not just two).

/*REXX program obtains some numbers from the input stream (the console), shows their sum*/
numeric digits 1000                              /*just in case the user gets  ka-razy. */
say 'enter some numbers to be summed:'           /*display a prompt message to terminal.*/
parse pull y                                     /*obtain all numbers from input stream.*/
many= words(y)                                   /*obtain the number of numbers entered.*/
$= 0                                             /*initialize the sum to zero.          */
              do j=1  for many                   /*process each of the numbers.         */
              $= $ + word(y, j)                  /*add one number to the sum.           */
              end   /*j*/
                                                 /*stick a fork in it,  we're all done. */
say 'sum of '   many   " numbers = "   $/1       /*display normalized sum $ to terminal.*/

version 5, multiple numbers, tongue in cheek

/*REXX program obtains some numbers from the input stream (the console), shows their sum*/
numeric digits 1000                              /*just in case the user gets  ka-razy. */
say 'enter some numbers to be summed:'           /*display a prompt message to terminal.*/
parse pull y                                     /*obtain all numbers from input stream.*/
y=space(y)
y=translate(y,'+',' ')
Interpret 's='y
say 'sum of '  many  " numbers = " s/1           /*display normalized sum s to terminal.*/

Ring

give Numbers
Numbers = split(Numbers)
sum = 0
for x in Numbers sum += x next
see sum

func Split Str
for x in str if x = " " x = nl ok next
return str2list(str)

Robotic

input string "Input A:"
set "A" to "input"
input string "Input B:"
set "B" to "input"
* "('A' + 'B')"
end

Although the function in the first and third line asks for a string as the input, so long as the variable isn't made to store a string, it will default to an integer instead. Inserting a string to this will return a 0.

Rockstar

Minimized:

Listen to A number
Listen to B
Say A number plus B

Idiomatic:

Listen to my voice
Listen to your thoughts
Shout your thoughts with my voice

RPL

Related task is natively implemented in RPL.

+
2 2 +
2 3 +
Output:
2: 4
1: 5

Ruby

puts gets.split.sum(&:to_i)

Run BASIC

input, x$
print  val(word$(x$,1)) + val(word$(x$,2))

Rust

use std::io;

fn main() {
    let mut line = String::new();
    io::stdin().read_line(&mut line).expect("reading stdin");

    let mut i: i64 = 0;
    for word in line.split_whitespace() {
        i += word.parse::<i64>().expect("trying to interpret your input as numbers");
    }
    println!("{}", i);
}

or

use std::io;

fn main() {
    let mut line = String::new();
    io::stdin().read_line(&mut line).expect("reading stdin");

    let sum: i64 = line.split_whitespace()
                       .map(|x| x.parse::<i64>().expect("Not an integer"))
                       .sum(); 
    println!("{}", sum);
}

S-lang

% A+B from stdin, sans error checking
variable input, a, b;

() = fgets(&input, stdin);
input = strtrim_end(input, "\n");
() = sscanf(input, "%d%d", &a, &b);
print(a + b);
Output:
prompt$ echo "12 34" | slsh A+B.sl
46
% A+B from stdin, basic validity testing
variable input, a, b, rc;

() = fgets(&input, stdin);
input = strtrim_end(input, "\n");
rc = sscanf(input, "%d%d", &a, &b);
if ((rc == 2) && (a >= -1000) && (a <= 1000) && (b >= -1000) && (b <= 1000)) {
   print(a + b);
} else {
   message("input invalid or out of range (-1000,1000): $input"$);
}

Scala

println(readLine().split(" ").map(_.toInt).sum)

This will work if the input is exactly as specified, with no extra whitespace. A slightly more robust version:

val s = new java.util.Scanner(System.in)
val sum = s.nextInt() + s.nextInt()
println(sum)

or

println(readLine().split(" ").filter(_.length>0).map(_.toInt).sum)

Scheme

(display (+ (read) (read)))

Scratch

Scratch is a graphical programming language. Follow the link to see an example solution for A + B
Scratch A + B
Since Scratch is an educational language, I've included comments in the code for new programmers to better understand what the program is doing.

sed

Sed is for string processing and has no facility for manipulating numbers as numeric values. However, being Turing complete, sed can be coerced into performing mathematics.

: Loop
# All done
/^-*00* /s///
/ -*00*$/s///
t

# Negative Check
/^\(-*\)[0-9].* \1[0-9]/!b Negative

# Create magic lookup table
s/\(.[0-9]*\) \(.[0-9]*\)/\1;987654321000009999000999009909 \2;012345678999990000999000990090/
s/ \(-\)*\(9*;\)/ \10\2/
# Decrement 1st number
s/\([^0]\)\(0*\);[^0]*\1\(.\).*\2\(9*\).* \(.*\)/\3\4 \5/
# Increment 2nd
s/\([^9]\)\(9*\);[^9]*\1\(.\).*\2\(0*\).*/\3\4/
t Loop

: Negative
# Create magic lookup table
s/\(.[0-9]*\) \(.[0-9]*\)/\1;987654321000009999000999009909 \2;987654321000009999000999009909/
# Decrement 1st number
s/\([^0]\)\(0*\);[^0]*\1\(.\).*\2\(9*\).* \(.*\)/\3\4 \5/
# Decrement 2nd
s/\([^0]\)\(0*\);[^0]*\1\(.\).*\2\(9*\).*/\3\4/
t Loop

Another method, based off of this StackExchange answer:

#!/bin/sed -f

# Add a marker in front of each digit, for tracking tens, hundreds, etc.
s/[0-9]/<&/g
# Convert numbers to, in essence, tally marks
s/0//g; s/1/|/g; s/2/||/g; s/3/|||/g; s/4/||||/g; s/5/|||||/g
s/6/||||||/g; s/7/|||||||/g; s/8/||||||||/g; s/9/|||||||||/g

# Multiply by ten for each digit from the back they were.
:tens 
s/|</<||||||||||/g
t tens

# We don't want the digit markers any more
s/<//g

# Negative minus negative is the negation of their absolute values.
s/^-\(|*\) *-/-\1/
# Negative plus positive equals positive plus negative, and we want the negative at the back.
s/^-\(|*\) \+\(|*\)$/\2-\1/
# Get rid of any space between the numbers 
s/ //g

# A tally on each side can be canceled.
:minus
s/|-|/-/
t minus
s/-$//

# Convert back to digits
:back
s/||||||||||/</g
s/<\([0-9]*\)$/<0\1/g
s/|||||||||/9/g;
s/|||||||||/9/g; s/||||||||/8/g; s/|||||||/7/g; s/||||||/6/g;
s/|||||/5/g; s/||||/4/g; s/|||/3/g; s/||/2/g; s/|/1/g;
s/</|/g
t back
s/^$/0/

Seed7

$ include "seed7_05.s7i";

const proc: main is func
  local
    var integer: a is 0;
    var integer: b is 0;
  begin
    read(a);
    read(b);
    writeln(a + b);
  end func;

Self

Works with positive and negative integers, and also more than two integers.

((stdin readLine splitOn: ' ') mapBy: [|:e| e asInteger]) sum printLine.

SenseTalk

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

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

put a + b
put file "input.txt" into inputFile
split inputFile by space
put sum of inputFile

SequenceL

import <Utilities/Conversion.sl>;

main(args(2)) := stringToInt(args[1]) + stringToInt(args[2]);
Output:
cmd:> main.exe 3 4
7

cmd:> main.exe -5 7
2

cmd:> main.exe -12 -10
-22

SETL

read(A, B);
print(A + B);

Shiny

if (io.line 'stdin').match ~(\d+)\s+(\d+)~
    say "$a $b %(a+b)d"
end

Sidef

Works with both positive and negative integers.

say STDIN.readline.words.map{.to_i}.sum

More idiomatically:

say read(String).words»to_i()»«+»

Explicit summation:

var (a, b) = read(String).words.map{.to_i}...
say a+b

Simula

BEGIN
    WHILE NOT LASTITEM DO
    BEGIN
        OUTINT(ININT + ININT, 0);
        OUTIMAGE;
    END;
END.

Smalltalk

Most Smalltalk implementations do not have the notion of a standard input stream, since it has always been a GUI based programming environment. I've included test methods to demonstrate one way to create an input stream with two integers can be created. Opening a text file would be another.

'From Squeak3.7 of ''4 September 2004'' [latest update: #5989] on 8 August 2011 at 3:50:55 pm'!
Object subclass: #ABTask
	instanceVariableNames: ''
	classVariableNames: ''
	poolDictionaries: ''
	category: 'rosettacode'!

"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!

ABTask class
	instanceVariableNames: ''!

!ABTask class methodsFor: 'demo'!
parseInteger: inputStream 
	^ Integer readFrom: inputStream skipSeparators! !

!ABTask class methodsFor: 'demo'!
sum: inputStream 
	^ (self parseInteger: inputStream)
		+ (self parseInteger: inputStream)! !

!ABTask class methodsFor: 'demo'!
test2Plus2
	^ self
		sum: (ReadStream on: '2 2')! !

!ABTask class methodsFor: 'demo'!
test3Plus2
	^ self
		sum: (ReadStream on: '3 2')! !

but all have a stream hierarchy, so the task could be restated to pass input and output as stream arguments:

Works with: Smalltalk/X
|task|
task := [:inStream :outStream |
    |processLine|

    processLine := 
        [
            |a b|
            a := Integer readFrom: inStream.
            b := Integer readFrom: inStream.
            "is validation part of the task?"
            self assert:( a between:-1000 and: 1000).
            self assert:( b between:-1000 and: 1000).
            outStream print (a+b); cr.
        ].

    [ inStream atEnd ] whileFalse:processLine.
].

task value: ( 'dataIn.txt' asFilename readStream) value:Transcript.

or:

task value: Stdin value: Stdout.

smart BASIC

INPUT n$
PRINT VAL(LEFT$(n$,(LEN(STR$(VAL(n$))))))+VAL(RIGHT$(n$,(LEN(n$)-LEN(STR$(VAL(n$)))-1)))

NOTE: This is a horribly forced way of doing this. smart BASIC has commands to SPLIT strings. Surely someone can provide better code than what I've written here.  ;@)

And someone did...

A FAR more elegant solution was provided by "Dutchman" on the smart BASIC Support Forum:

INPUT n$
SPLIT n$ TO m$,n WITH " "
PRINT m$(0),m$(1),m$(0)+m$(1)

NOTE: smart BASIC will intelligently interpret the contents of a string as a numeric value if necessary. Other versions of BASIC would require the values stored in a string to be converted to numeric values before calculation.

SmileBASIC

INPUT A
INPUT B
PRINT A+B

SNOBOL4

Simple-minded solution (literally "two somethings separated by space")

	input break(" ") . a " " rem . b 
	output = a + b
end

"Integer aware" solution:

	nums = "0123456789"
	input span(nums) . a break(nums) span(nums) . b
	output = a + b
end

SPAD

Works with: FriCAS
Works with: OpenAxiom
Works with: Axiom

One of several possibilities:

(1) -> integer READ()$Lisp + integer READ()$Lisp
333 444

   (1)  777
                                                        Type: PositiveInteger

Domain:SExpression

SparForte

As a structured script.

#!/usr/local/bin/spar
pragma annotate( summary, "aplusb" )
       @( description, "A+B - in programming contests, classic problem, which is given so" )
       @( description, "contestants can gain familiarity with online judging system being used. " )
       @( description, "A+B is one of few problems on contests, which traditionally lacks fabula." )
       @( description, "Given 2 integer numbers, A and B. One needs to find their sum. " )
       @( category, "tutorials" )
       @( author, "Ken O. Burtch" )
       @( see_also, "http://rosettacode.org/wiki/A%2BB" );
pragma license( unrestricted );

pragma software_model( nonstandard );
pragma restriction( no_external_commands );

procedure aplusb is
  s : string;
  a : integer;
  b : integer;
begin
  s := get_line;
  a := numerics.value( strings.field( s, 1, ' ' ) );
  b := numerics.value( strings.field( s, 2, ' ' ) );
  ? a+b;
end aplusb;

SPARK

-- By Jacob Sparre Andersen
-- Validates with SPARK GPL 2010's Examiner/Simplifier

with SPARK_IO; --# inherit SPARK_IO;

--# main_program;
procedure A_Plus_B
--# global in out SPARK_IO.Inputs, SPARK_IO.Outputs;
--# derives SPARK_IO.Inputs  from SPARK_IO.Inputs &
--#         SPARK_IO.Outputs from SPARK_IO.Inputs, SPARK_IO.Outputs;
is
   subtype Small_Integers is Integer range -1_000 .. +1_000;
   A, B       : Integer;
   A_OK, B_OK : Boolean;
begin
   SPARK_IO.Get_Integer 
     (File  => SPARK_IO.Standard_Input,
      Item  => A,
      Width => 0,
      Read  => A_OK);
   
   A_OK := A_OK and A in Small_Integers;
   
   SPARK_IO.Get_Integer 
     (File  => SPARK_IO.Standard_Input,
      Item  => B,
      Width => 0,
      Read  => B_OK);
   
   B_OK := B_OK and B in Small_Integers;
   
   if A_OK and B_OK then
      SPARK_IO.Put_Integer 
        (File  => SPARK_IO.Standard_Output,
         Item  => A + B,
         Width => 4,
         Base  => 10);
   else
      SPARK_IO.Put_Line 
        (File => SPARK_IO.Standard_Output,
         Item => "Input data does not match specification.",
         Stop => 0);
   end if;
end A_Plus_B;

SPL

n = #.split(#.input("Input two numbers, separated by space:")," ")
#.output(n[1],"+",n[2],"=",#.val(n[1])+#.val(n[2]))
Input:
Input two numbers, separated by space:
2 3
Output:
2+3=5

SQL

select A+B

Example:

select 2+3

This should produce a result set containing the value 5.

Note however that declaration of variables is outside the scope of the ANSI SQL standards, unless by variables you mean tables (which would complicate the example considerably).

SQL PL

Works with: Db2 LUW

With SQL only:

CREATE OR REPLACE FUNCTION splitadd (instring VARCHAR(255))
	RETURNS INTEGER
	NO EXTERNAL ACTION
F1: BEGIN ATOMIC

	declare first INTEGER;
	declare second INTEGER;
	
	set first = REGEXP_SUBSTR(instring, '[0-9]+',1,1);
	set second = REGEXP_SUBSTR(instring, '[0-9]+',1,2);

	return first + second;
END

Output:

VALUES DBA.SPLITADD(VARCHAR('1234    2345'))
 1
 ----
 3579

SSEM

The SSEM has no Add instruction, so we rely on the fact that a + b = -(-a - b).

10100000000000100000000000000000   0. -5 to c     acc = -A
01100000000001010000000000000000   1. Sub. 6      acc -= B
11100000000001100000000000000000   2. c  to 7     X = acc
11100000000000100000000000000000   3. -7 to c     acc = -X
00000000000001110000000000000000   4. Stop
10100100000000000000000000000000   5. 37          A
00111000000000000000000000000000   6. 28          B
00000000000000000000000000000000   7. 0           X

Standard ML

(*
 * val split : string -> string list
 * splits a string at it spaces
 *)
val split = String.tokens Char.isSpace

(*
 * val sum : int list -> int
 * computes the sum of a list of numbers
 *)
val sum = foldl op+ 0

(*
 * val aplusb : unit -> int
 * reads a line and gets the sum of the numbers
 *)
fun aplusb () =
  let
    val input = valOf (TextIO.inputLine TextIO.stdIn)
  in
    (sum o List.mapPartial Int.fromString o split) input
  end
Output:
- aplusb();
123 456
val it = 579 : int

Swift

Works with: Swift version 2

Requires sending EOF.

import Foundation

let input = NSFileHandle.fileHandleWithStandardInput()

let data = input.availableData
let str = NSString(data: data, encoding: NSUTF8StringEncoding)!

let nums = str.componentsSeparatedByString(" ")
let a = (nums[0] as String).toInt()!
let b = (nums[1] as String).toInt()!

print(" \(a + b)")
Works with: Swift version 3

Swift 4 and no requirement to send EOF (press enter/send newline like you normally would)

import Foundation

let input = FileHandle.standardInput

let data = input.availableData
let str = String(data: data, encoding: .utf8)!
let nums = str.split(separator: " ")
    .map { String($0.unicodeScalars
        .filter { CharacterSet.decimalDigits.contains($0) }) }

let a = Int(nums[0])!
let b = Int(nums[1])!

print(" \(a + b)")

Symsyn

 [] $s
 getitem $s x
 getitem $s y
 + x y
 y []

Tailspin

composer nums
  [ (<WS>?) <INT> (<WS>) <INT> (<WS>?) ]
end nums

$IN::lines -> nums -> $(1) + $(2) -> '$;
' -> !OUT::write

Alternatively

composer nums
  (<WS>?) (def a: <INT>;) (<WS>) <INT> -> $a + $ (<WS>?)
end nums

$IN::lines -> nums -> '$;
' -> !OUT::write

Tcl

scan [gets stdin] "%d %d" x y
puts [expr {$x + $y}]

Alternatively:

puts [tcl::mathop::+ {*}[gets stdin]]

To/from a file:

set in [open "input.txt"]
set out [open "output.txt" w]
scan [gets $in] "%d %d" x y
puts $out [expr {$x + $y}]
close $in
close $out

Terraform

#Aamrun, August 15th, 2022

variable "a" {
  type = number
}

variable "b" {
  type = number
}

output "a_plus_b" {
  value = var.a + var.b
}
Output:
$ terraform apply -var="a=136" -var="b=745" -auto-approve

Changes to Outputs:
  + a_plus_b = 881

You can apply this plan to save these new output values to the Terraform state, without changing any real infrastructure.

Apply complete! Resources: 0 added, 0 changed, 0 destroyed.

Outputs:

a_plus_b = 881
$

TI-83 BASIC

:Prompt A,B
:Disp A+B

TI-83 Hex Assembly

Note: Comments (after the semicolons) are just for explanation -- TI-83 hex assembly does not allow comments in program source code.

PROGRAM:APLUSB
:AsmPrgm
:
:EFC541 ; ZeroOP1
:217984 ; ld hl,op1+1
:3641   ; ld (hl),'A'
:EFE34A ; RclVarSym
:CF     ; rst OP1toOP2
:
:EFC541 ; ZeroOP1
:217984 ; ld hl,op1+1
:3642   ; ld (hl),'B'
:EFE34A ; RclVarSym
:
:F7     ; rst FPAdd
:EFBF4A ; StoAns
:C9     ; ret

Store the inputs in the 'A' and 'B' OS variables. Run it with Asm(prgmAPLUSB) and the output will be stored in the Ans OS variable.

TI-89 BASIC

:aplusb(a,b)
:a+b

TorqueScript

Since torque is not compatible with standard input, I will show the closest to that. It's a function that takes a single string input, that will contain the 2 numbers.

Function aPlusB(%input)
{
    return getWord(%input, 0) + getWord(%input, 1);
}

Transd

#lang transd

MainModule : {
	a: Int(),
	b: Int(),
	_start: (lambda (textout (+ (read a) (read b))))
}

TSE SAL

INTEGER PROC FNMathGetSumAPlusBI( INTEGER A, INTEGER B )
 RETURN( A + B )
END
//
PROC Main()
 STRING s1[255] = "3"
 STRING s2[255] = "2"
 IF ( NOT ( Ask( "math: get: sum: a: plus: a (choose a number between -1000 and 1000) = ", s1, _EDIT_HISTORY_ ) ) AND ( Length( s1 ) > 0 ) ) RETURN() ENDIF
 IF ( NOT ( Ask( "math: get: sum: a: plus: b (choose a number between -1000 and 1000) = ", s2, _EDIT_HISTORY_ ) ) AND ( Length( s2 ) > 0 ) ) RETURN() ENDIF
 Message( FNMathGetSumAPlusBI( Val( s1 ), Val( s2 ) ) ) // gives e.g. 5
END
Output:

output 5

TUSCRIPT

$$ MODE TUSCRIPT
SET input="1 2"
SET input=SPLIT(input,": :")
SET input=JOIN (input)
SET output=SUM(input)

TXR

$ txr -p '(+ (read) (read))'
1.2 2.3
3.5

TypeScript

function add(a: number, b: number) {
return a+b;
}

UNIX Shell

Works with: Bourne Shell
#!/bin/sh
read a b || exit
echo `expr "$a" + "$b"`
Works with: bash
Works with: ksh93
Works with: pdksh
Works with: zsh

Script "a+b.sh":

#!/bin/bash
read a b || exit
echo $(( a + b ))
Output:
echo 2 3 | ksh a+b.sh
5

One liner :

a=0;b=0;read a;read b;echo "Sum of $a and $b is "$((a+b))

Sample run :

3
4
Sum of 3 and 4 is 7

C Shell

set line=$<
set input=($line)
@ sum = $input[1] + $input[2]
echo $sum

Ursa

#
# a + b
#

# read a string containing the two ints
decl string input
set input (in string console)

# determine the sum
decl int sum
set sum (int (+ sum (int (split input " ")<0>)))
set sum (int (+ sum (int (split input " ")<1>)))

# output the sum
out sum endl console

Ultimate++

#include <Core/Core.h>
#include <stdio.h>
#include <iostream>

using namespace Upp;

CONSOLE_APP_MAIN
{
	
	int a, b;
	a = 2, b = 3;
	printf("%d + %d = %d\n",a,b,(a + b));
	std::cout << std::endl << a << " + " << b << " = " << (a + b) << std::endl;

	const Vector<String>& cmdline = CommandLine();
	for(int i = 0; i < cmdline.GetCount(); i++) {
	}
}


Ursala

Using standard input and output streams:

#import std
#import int

#executable&

main = %zP+ sum:-0+ %zp*FiNCS+ sep` @L

Overwriting a text file named as a command line parameter:

#import std
#import int

#executable -[parameterized]-

main = ~command.files.&h; <.contents:= %zP+ sum:-0+ %zp*FiNCS+ sep` @L+ ~contents>

Creating a new file named after the input file with suffix .out:

#import std
#import int

#executable -[parameterized]-

main = 

~command.files.&h; ~&iNC+ file$[
   contents: %zP+ sum:-0+ %zp*FiNCS+ sep` @L+ ~contents,
   path: ~path; ^|C\~& ~=`.-~; ^|T/~& '.out'!]

Vala

Read from stdin while program running:

Using GLib;

int main (string[] args) {
    stdout.printf ("Please enter int value for A\n");
    var a = int.parse (stdin.read_line ());
    stdout.printf ("Please enter int value for B\n");
    var b = int.parse (stdin.read_line ());
    stdout.printf ("A + B = %d\n", a + b);
    return 0;
}

VBA

A simple version:

Sub AplusB()
    Dim s As String, t As Variant, a As Integer, b As Integer
    s = InputBox("Enter two numbers separated by a space")
    t = Split(s)
    a = CInt(t(0))
    b = CInt(t(1))
    MsgBox a + b
End Sub

An other version:

Sub Rosetta_AB()
Dim stEval As String
stEval = InputBox("Enter two numbers, separated only by a space", "Rosetta Code", "2 2")
MsgBox "You entered " & stEval & vbCr & vbCr & _
    "VBA converted this input to " & Replace(stEval, " ", "+") & vbCr & vbCr & _
    "And evaluated the result as " & Evaluate(Replace(stEval, " ", "+")), vbInformation + vbOKOnly, "XLSM"
End Sub

VBScript

A simple version:

s=InputBox("Enter two numbers separated by a blank")
t=Split(s)
a=CInt(t(0))
b=CInt(t(1))
c=a+b
MsgBox c

An other version:

Option Explicit
Dim a, b
Select Case WScript.Arguments.Count
	Case 0	'No arguments, prompt for them.
		WScript.Echo "Enter values for a and b"
		a = WScript.Stdin.ReadLine
		if Instr(a, " ") > 0 then	'If two variables were passed
			b = Split(a)(1)
			a = Split(a)(0)
		else
			WScript.Echo "Enter value for b"
			b = WScript.Stdin.ReadLine
		end if
	Case 1	'One argument, assume it's an input file, e.g. "in.txt"
		Dim FSO : Set FSO = CreateObject("Scripting.FileSystemObject")
		With FSO.OpenTextFile(WScript.Arguments(0), 1)
			a = .ReadLine
			b = Split(a)(1)
			a = Split(a)(0)
			.Close
		End With
	Case 2 'Two arguments, assume they are values
		a = WScript.Arguments(0)
		b = WScript.Arguments(1)
End Select
'At this point, a and b are strings as entered, make them numbers
a = CInt(a)
b = CInt(b)

'Write the sum
Wscript.Echo a + b
if 1 = WScript.Arguments.Count then
	With FSO.CreateTextFile("out.txt")
		.WriteLine a + b
		.Close
	End With
end if

Vedit macro language

This version implements the task as specified in the task description.

// Input two values on single line in text format
Get_Input(10, "Enter two integers separated by a space: ")

// Extract two numeric values from the text
Buf_Switch(Buf_Free)
Reg_Ins(10)
BOF
#1 = Num_Eval(ADVANCE)
#2 = Num_Eval()
Buf_Quit(OK)

// Calculate and display the results
Num_Type(#1 + #2)

A simpler version that prompts for the two numbers separately:

#1 = Get_Num("Enter number A: ")
#2 = Get_Num("Enter number B: ")
Num_Type(#1 + #2)

Verilog

module TEST;

  reg signed [11:0] y;

  initial begin
    y= sum(2, 2);
    y= sum(3, 2);
    y= sum(-3, 2);
  end
  
  function signed [11:0] sum;
    input signed [10:0] a, b;
    begin
      sum= a + b;
      $display("%d + %d = %d",a,b,sum);
    end
  endfunction
  
endmodule

VHDL

LIBRARY std;
USE std.TEXTIO.all;


entity test is
end entity test;


architecture beh of test is
begin
  process
    variable line_in, line_out : line;
    variable a,b : integer;
  begin
    readline(INPUT, line_in);
    read(line_in, a);
    read(line_in, b);
    
    write(line_out, a+b);
    writeline(OUTPUT, line_out);
    wait; -- needed to stop the execution
  end process;
end architecture beh;

Visual Basic .NET

Module Module1

  Sub Main()
    Dim s() As String = Nothing

    s = Console.ReadLine().Split(" "c)
    Console.WriteLine(CInt(s(0)) + CInt(s(1)))
  End Sub

End Module

V (Vlang)

import os

fn main() {
    mut a := 0
    mut b := 0
    
    text := os.get_raw_line()
    
    values := text.split(' ')
    
    a = values[0].int()
    b = values[1].int()
    
    println('$a + $b = ${a+b}')
}

Read from stdin

Output:
Input         Output
2 2           2 + 2 = 4
3 2           3 + 2 = 5

Wee Basic

Print 1 "Enter number A:"
input a
Print 1 "Enter number B:"
input b
let c=a+b
print 1 c
end

Whitespace

Wisp

Translation of: Scheme
display : + (read) (read)


314
315
;; displays 629

Wren

import "io" for Stdin, Stdout

while (true) {
    System.write("Enter two integers separated by a space : ")
    Stdout.flush()
    var s = Stdin.readLine().split(" ")
    if (s.count < 2) {
        System.print("Insufficient numbers, try again")
    } else {
        var a = Num.fromString(s[0])
        var b = Num.fromString(s[s.count-1])
        System.print("Their sum is %(a + b)")
        return
    }
}
Output:

Sample input/output:

Enter two integers separated by a space : 12 16
Their sum is 28

X86 Assembly

Works with: NASM version Linux
section .text
	global _start
		
	_print:
		mov ebx, 1
		mov eax, 4
		int 0x80
		ret
			
	_get_input:
		mov edx, 4
		mov ebx, 0
		mov eax, 3
		int 0x80
		ret
		
	_start:
		mov edx, in_val_len
		mov ecx, in_val_msg
		call _print
		mov ecx, a
		call _get_input
		;make 'a' an actual number rather than a char.
		sub dword [a], 0x30
		mov edx, in_val_len
		mov ecx, in_val_msg
		call _print
		mov ecx, b
		call _get_input
		;calc real number for 'b'
		sub dword [b], 0x30
		mov eax, dword [a]
		mov ebx, dword [b]
		add eax, ebx
		;get the character for our sum.
		add eax, 0x30
		mov dword [sum], eax
		mov edx, out_val_len
		mov ecx, out_val_msg
		call _print
		mov [sum+1], dword 0xa
		mov edx, 4
		mov ecx, sum
		call _print
		push 0x1
		mov eax, 1
		push eax
		int 0x80
		ret
		
section .data
in_val_msg	db "Please input an integer:",0
in_val_len	equ $-in_val_msg
out_val_msg db "The sum of a+b is: ",0
out_val_len	equ $-out_val_msg

section .bss
a    			resd 1
b				resd 1
sum			resd 1

This will not work on numbers over 0(from 1 to 0). This is due to the fact, numbers higher than 0(10,11, etc) are in fact strings when taken from the keyboard. A much longer conversion code is required to loop through and treat each number in the string as separate numbers. For example, The number '10' would have to be treated as a 1 and a 0.

XBS

Since XBS is written in Javascript, we have to use the Javascript prompt function to get inputs.

const Amount:number = toint(window.prompt("Input an amount"));
set Stream = [];
<|(*1..Amount)=>Stream.push(window.prompt("Input a number"));
Stream=Stream.join(" ");
const Inputs = <|(*Stream.split(" "))toint(_);
set Result = 0;
<|(*Inputs)Result+=_;
log(Result);
Output:

If we input an amount of "2", then input "1" and "2", the output will be "3".

3

xEec

i# i# ma h#10 r o# p o$ p

XLISP

(DEFUN A-PLUS-B ()
    (DISPLAY "Enter two numbers separated by a space.")
    (NEWLINE)
    (DISPLAY "> ")
    (DEFINE A (READ))
    (DEFINE B (READ))
    (+ A B))
Output:
(A-PLUS-B)
Enter two numbers separated by a space.
> 2 2

4

Xojo

var inp as string
var strVals() as string

print("Enter two numbers separated by a space:")

do
  inp = input
  
  
  strVals = inp.split(" ")
  
  var a, b as integer
  
  a = strVals(0).toInteger
  b = strVals(1).toInteger
  
  if a < -1000 or b > 1000 then
    print("The first number should be greater than or equal to -1000 and the second number should be less " + _
    "than or equal to 1000. Please re-enter:")
    continue
  end
  
  var result as integer = a + b
  print(a.toString + " + " + b.toString + " = " + result.toString)
  exit
loop

XPL0

include c:\cxpl\codes;
int A, B;
[A:= IntIn(0);
 B:= IntIn(0);
 IntOut(0, A+B);
 CrLf(0);
]

XQuery

(: 
  Using the EXPath File Module, which is built into most XQuery processors 
  by default and thus does not need to get imported. Some processors bind the
  namespace automatically, others require explicit declaration.
:)

xquery version "3.1";

declare namespace file = 'http://expath.org/ns/file';

let $in       := 'input.txt'
let $out      := 'output.txt'
let $numbers  := tokenize(file:read-text($in))
let $result   := xs:numeric($numbers[1]) + xs:numeric($numbers[2])
return file:write-text($out, xs:string($result))

Yabasic

repeat
    input "Enter two numbers (betwen -1000 ... +1000): " a, b
until(valid(a) and valid(b))
print "\nThe sum of ", a, " and ", b, " is: ", a + b

sub valid(x)
    return x >= -1000 and x <= 1000
end sub

Yorick

a = b = 0;
read, a, b;
write, a + b;

ZED

Source -> http://ideone.com/WLtEfe Compiled -> http://ideone.com/fMt6ST

(A+B)
comment:
#true
(+) (read) (read)

(+) one two
comment:
#true
(003) "+" one two

(read)
comment:
#true
(001) "read"

zkl

do(2){ask("A B: ").split(" ").filter().sum().println()}
A B: 123    567
690
A B: -4 6
2

This actually works for any number of integers

Zoea

program: a_plus_b
  input: '7 11' 
  output: 18

Zoea Visual

A+B

zonnon

module ABProblem;
var
	a,b: integer;
begin
	read(a,b);
	writeln(a+b)
end ABProblem.
1 2
                   3

ZX Spectrum Basic

10 PRINT "Input two numbers separated by"'"space(s) "
20 INPUT LINE a$
30 GO SUB 90
40 FOR i=1 TO LEN a$
50 IF a$(i)=" " THEN LET a=VAL a$( TO i): LET b=VAL a$(i TO ): PRINT a;" + ";b;" = ";a+b: GO TO 70
60 NEXT i
70 STOP 
80 REM LTrim operation
90 IF a$(1)=" " THEN LET a$=a$(2 TO ): GO TO 90
100 RETURN

Another solution

10 PRINT "Input two numbers separated by"'"space(s) "
20 INPUT LINE a$
30 LET ll=10e10: LET ls=0: LET i=1
40 IF a$(i)=" " THEN LET ls=i: GO TO 60
50 LET ll=i
60 IF ls>ll THEN GO TO 80
70 LET i=i+1: GO TO 40
80 LET a=VAL a$( TO i): LET b=VAL a$(i TO )
90 PRINT a;" + ";b;" = ";a+b
Input two numbers separated by
space(s)
  3.14     2^3
3.14 + 8 = 11.14