A+B: Difference between revisions

88,947 bytes added ,  24 days ago
Zig added
No edit summary
(Zig added)
 
(241 intermediate revisions by more than 100 users not shown)
Line 4:
 
;Task:
Given two integerintegers,   '''A''' and '''B'''.
 
Their sum needs to be calculated.
Line 32:
 
=={{header|0815}}==
<syntaxhighlight lang ="0815">|x|+%</langsyntaxhighlight>
 
=={{header|11l}}==
{{trans|Python}}
<syntaxhighlight lang="11l">print(sum(input().split(‘ ’, group_delimiters' 1B).map(i -> Int(i))))</syntaxhighlight>
 
=={{header|360 Assembly}}==
<langsyntaxhighlight lang="360asm">* A+B 29/08/2015
APLUSB CSECT
USING APLUSB,R12
Line 41 ⟶ 45:
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
Line 56 ⟶ 60:
YREGS
END APLUSB
</syntaxhighlight>
</lang>
{{in}}
<pre>
Line 71 ⟶ 75:
 
=={{header|8th}}==
<langsyntaxhighlight lang="forth">gets dup . space eval n:+ . cr</langsyntaxhighlight>
 
=={{header|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 <code>dad</code> (for "double add"),
which can take four forms:
 
<syntaxhighlight lang="8080asm"> 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)</syntaxhighlight>
 
Merely doing A+B, with 16-bit numbers so that <math>(-1000 \le A,B \le +1000)</math> will fit,
would look like this:
<syntaxhighlight lang="8080asm"> lxi h,123
lxi d,456
dad d
; HL is now 579</syntaxhighlight>
 
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.
 
<syntaxhighlight lang="8080asm">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</syntaxhighlight>
 
{{out}}
 
<pre>A>add 10 10
20
A>add 10 -5
5
A>add -1000 1000
0
A>add -1234 5678
4444</pre>
 
 
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
<syntaxhighlight lang="aarch64 assembly">
/* 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
 
</syntaxhighlight>
 
=={{header|ABAP}}==
<langsyntaxhighlight ABAPlang="abap">report z_sum_a_b.
data: lv_output type i.
selection-screen begin of block input.
Line 88 ⟶ 423:
start-of-selection.
lv_output = p_first + p_second.
write : / lv_output.</langsyntaxhighlight>
 
=={{header|Acornsoft Lisp}}==
{{trans|Common Lisp}}
 
<pre>
Evaluate: (print (plus (read) (read)))
3 2
5
</pre>
 
=={{header|Action!}}==
<syntaxhighlight lang="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</syntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/A+B.png Screenshot from Atari 8-bit computer]
<pre>
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
</pre>
 
=={{header|Ada}}==
<langsyntaxhighlight Adalang="ada">-- Standard I/O Streams
 
with Ada.Integer_Text_Io;
Line 100 ⟶ 521:
Ada.Integer_Text_Io.Get (Item => B);
Ada.Integer_Text_Io.Put (A+B);
end APlusB;</langsyntaxhighlight>
Using appropriate user defined types:
<langsyntaxhighlight Adalang="ada">with Ada.Text_IO;
 
procedure A_Plus_B is
Line 113 ⟶ 534:
IO.Get (B);
IO.Put (A + B, Width => 4, Base => 10);
end A_Plus_B;</langsyntaxhighlight>
 
=={{header|Agena}}==
Tested with Agena 2.9.5 Win32
<langsyntaxhighlight lang="agena">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</langsyntaxhighlight>
 
=={{header|Aime}}==
<langsyntaxhighlight lang="aime">file f;
list l;
 
Line 131 ⟶ 552:
f_list(f, l, 0);
o_integer(atoi(l[0]) + atoi(l[1]));
o_newline();</langsyntaxhighlight>
 
=={{header|ALGOL 60}}==
{{works with|A60}}
<syntaxhighlight lang="algol60">begin
comment A+B;
integer a,b;
ininteger(0,a); ininteger(0,b);
outinteger(1,a+b)
end </syntaxhighlight>
{{in}}
<pre>
1 2
</pre>
{{out}}
<pre>
3
</pre>
 
 
=={{header|ALGOL 68}}==
Line 139 ⟶ 578:
{{wont work with|ELLA ALGOL 68|Any (with appropriate job cards) - missing transput function "read int"}}
===Console===
<langsyntaxhighlight lang="algol68">print((read int + read int))</langsyntaxhighlight>
Input:
<pre>
Line 150 ⟶ 589:
 
===File===
<langsyntaxhighlight lang="algol68">open(stand in, "input.txt", stand in channel);
open(stand out, "output.txt", stand out channel);
print((read int + read int))</langsyntaxhighlight>
Input "input.txt":
<pre>
Line 163 ⟶ 602:
 
=={{header|ALGOL W}}==
<langsyntaxhighlight lang="algolw">begin
integer a, b;
read( a, b );
write( a + b )
end.</langsyntaxhighlight>
 
=={{header|Amazing Hopper}}==
<syntaxhighlight lang="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
</syntaxhighlight>
{{out}}
<pre>
Ingrese dos números, separados por espacio: -200 10
Suma : -190
Press any key to continue...
</pre>
 
Version dos: hopper-BASIC acepta "programación fluída"
 
<syntaxhighlight lang="amazing hopper">
#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
</syntaxhighlight>
{{out}}
<pre>
Ingrese dos números, separados por espacio: -1005 500
Suma : -500
Press any key to continue...
</pre>
 
=={{header|ANTLR}}==
Line 175 ⟶ 669:
 
=={{header|Apex}}==
<syntaxhighlight lang="apex">
<lang Apex>
 
static Integer sumOfTwoNums(Integer A, Integer B) {
Line 192 ⟶ 686:
A = 50 and B = -25: 25
 
</syntaxhighlight>
</lang>
 
=={{header|APL}}==
<syntaxhighlight lang APL="apl"> ⎕+⎕ </langsyntaxhighlight>
 
=={{header|AppleScript}}==
Open the '''AppleScript Editor''' and save this as '''A+B.scpt''' on your Desktop
<langsyntaxhighlight AppleScriptlang="applescript">on run argv
try
return ((first item of argv) as integer) + (second item of argv) as integer
Line 205 ⟶ 699:
return "Usage with -1000 <= a,b <= 1000: " & tab & " A+B.scpt a b"
end try
end run</langsyntaxhighlight>
 
To make this run in Terminal open the '''Terminal.app''' and type
Line 215 ⟶ 709:
 
=={{header|Arc}}==
<syntaxhighlight lang="arc">
<lang Arc>
(prn (+ (read)
(read)))
</syntaxhighlight>
</lang>
 
=={{header|Argile}}==
{{trans|C}}
{{works with|Argile|1.0.0}}
<langsyntaxhighlight Argilelang="argile">(: Standard input-output streams :)
use std, array
Cfunc scanf "%d%d" (&val int a) (&val int b)
printf "%d\n" (a + b)</langsyntaxhighlight>
<langsyntaxhighlight Argilelang="argile">(: Input file : input.txt :)
(: Output file: output.txt :)
use std, array
Line 236 ⟶ 730:
fprintf out "%d\n" (x+y)
fclose in
fclose out</langsyntaxhighlight>
 
=={{header|ARM Assembly}}==
{{works with|gcc|Linux}}
Exploiting C standard library functions (scanf and printf).
Requires arm-linux-gnueabi-gcc and qemu-arm. Compile with:
<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
.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</syntaxhighlight>
 
{{works with|gcc|Linux}}
Todo: -need to print numbers w/o the leading 0's. Replace them with spaces, so alignment is still the same.
Line 257 ⟶ 784:
Save in ab.S
Build with:
<langsyntaxhighlight ARM_Assemblylang="arm_assembly">as -o ab.o ab.S
ld -o a.out ab.o</langsyntaxhighlight>
 
<syntaxhighlight lang="arm_assembly">.data
<lang ARM_Assembly>.data
.align 2
.code 32
Line 773 ⟶ 1,300:
movlt r0, #0
ldmfd sp!, {r7, pc}
</syntaxhighlight>
</lang>
 
=={{header|Arturo}}==
 
<syntaxhighlight lang="rebol">while ø [
x: map split.words input "give me 2 numbers:" 'x -> to :integer x
print add x\0 x\1
]
</syntaxhighlight>
 
{{out}}
 
<pre>give me 2 numbers:3 4
7
give me 2 numbers:2 5
7</pre>
 
=={{header|AsciiDots}}==
<<syntaxhighlight lang="asciidots">
&-#$-\
.-#?-[+]
.-#?--/
</syntaxhighlight>
 
=={{header|ATS}}==
<syntaxhighlight lang="ats">
<lang ATS>
(* ****** ****** *)
//
Line 803 ⟶ 1,352:
 
(* ****** ****** *)
</syntaxhighlight>
</lang>
 
=={{header|AutoHotkey}}==
This handles more than two inputs
<lang AutoHotkey>InputBox, input , A+B, Two integer numbers`, separated by space.
<syntaxhighlight lang="autohotkey">Gui, Add, Edit, vEdit ;Enter your A+B, i.e. 5+3 or 5+3+1+4+6+2
StringSplit, output, input, %A_Space%
Gui, Add, Button, gAdd, Add
msgbox, % output1 . "+" . output2 "=" output1+output2</lang>
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</syntaxhighlight>
 
=={{header|AutoIt}}==
<langsyntaxhighlight AutoItlang="autoit">;AutoIt Version: 3.2.10.0
$num = "45 54"
consolewrite ("Sum of " & $num & " is: " & sum($num))
Line 817 ⟶ 1,377:
$numm = StringSplit($numbers," ")
Return $numm[1]+$numm[$numm[0]]
EndFunc</langsyntaxhighlight>
 
===Example2===
This version can handle any amount of numbers in the input:
<langsyntaxhighlight AutoItlang="autoit">ConsoleWrite("# A+B:" & @CRLF)
 
Func Sum($inp)
Line 842 ⟶ 1,402:
; so the program works correctly even with this input:
Local $inp = "999x y 42 -999", $res = Sum($inp)
ConsoleWrite($inp & " --> " & $res & @CRLF)</langsyntaxhighlight>
{{Out}}
<pre>
Line 851 ⟶ 1,411:
 
=={{header|AWK}}==
<langsyntaxhighlight lang="awk">{print $1 + $2}</langsyntaxhighlight>
 
=={{header|Batch FileBabyCobol}}==
<syntaxhighlight lang="cobol">
Prompts version
* NB: COBOL's ACCEPT does not work with multiple identifiers
<lang dos>::aplusb.cmd
IDENTIFICATION DIVISION.
@echo off
PROGRAM-ID. PLUS.
setlocal
DATA DIVISION.
set /p a="A: "
01 A PICTURE IS S9999.
set /p b="B: "
01 B LIKE A.
set /a c=a+b
PROCEDURE DIVISION.
echo %c%
DISPLAY "Enter two numbers: " WITH NO ADVANCING.
endlocal</lang>
ACCEPT A B.
All on the commandline version
ADD A TO B.
<lang dos>::aplusb.cmd
DISPLAY "A+B =" B.
@echo off
</syntaxhighlight>
setlocal
set a=%1
set b=%2
set /a c=a+b
echo %c%
endlocal</lang>
Formula on the command line version
<lang dos>::aplusb.cmd
@echo off
setlocal
set /a c=%~1
echo %c%
endlocal</lang>
Example of 'Formula on the command line version'
<pre>
>aplusb 123+456
579
>aplusb "1+999"
1000
</pre>
Parse the input stream version (thanks to Tom Lavedas on alt.msdos.batch.nt)
<lang dos>::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</lang>
Example of 'parse the input stream version'
<pre>>aplusb
Input stream: 1234 5678
6912
>aplusb
Input stream: 123 234 345 456 567 678 789 890
4082</pre>
 
=={{header|BASIC}}==
<langsyntaxhighlight lang="qbasic">DEFINT A-Z
 
tryagain:
Line 924 ⟶ 1,444:
ELSE
GOTO tryagain
END IF</langsyntaxhighlight>
 
==={{header|Applesoft BASIC}}===
<langsyntaxhighlight ApplesoftBasiclang="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
40 IF LEN(I$) THEN IF MID$(I$, LEN(I$), 1) = " " THEN I$ = MID$(I$, 1, LEN(I$) - 1) : GOTO 40RTRIM
Line 937 ⟶ 1,457:
100 VTAB BH
110 HTAB LEN(A$) + 2 + S
120 PRINT C%</langsyntaxhighlight>
 
==={{header|BaCon}}===
<langsyntaxhighlight lang="qbasic">' A+B
INPUT d$
PRINT VAL(TOKEN$(d$, 1)) + VAL(TOKEN$(d$, 2))</langsyntaxhighlight>
 
==={{header|BASIC256}}===
<langsyntaxhighlight lang="basic256">dim a(2)
input "Enter two numbers seperatedseparated by a space?", t$
a = explode(t$," ")
print t$ + & " " +& int(a[0]) + int(a[1])</langsyntaxhighlight>
 
==={{header|BBC BASIC}}===
<langsyntaxhighlight lang="bbc"> REPEAT
hereY% = VPOS
INPUT LINE "" q$
Line 964 ⟶ 1,484:
PRINT TAB(hereX%, hereY%) ; a + b
ENDIF
UNTIL FALSE</langsyntaxhighlight>
That seems overly complicated. What's wrong with:
<langsyntaxhighlight lang="bbc"> REPEAT
INPUT LINE "" q$
space% = INSTR(q$," ")
PRINT VAL LEFT$(q$,space%-1) + VAL MID$(q$,space%+1)
UNTIL FALSE</langsyntaxhighlight>
 
==={{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}}===
<langsyntaxhighlight lang="qbasic">10 PRINT "ENTER TWO NUMBERS, SEPARATED BY A SPACE: ";
20 INPUT X$
30 I = 1 : N = LEN(X$)
Line 979 ⟶ 1,516:
50 A = VAL(LEFT$(X$,I))
60 B = VAL(RIGHT$(X$,N-1))
70 PRINT A+B</langsyntaxhighlight>
 
==={{header|FreeBASIC}}===
<langsyntaxhighlight lang="freebasic">' fb 1.05.0 Win64
 
Dim As Integer a, b
Line 998 ⟶ 1,535:
Print
Print "Press any key to quit the program"
Sleep</langsyntaxhighlight>
 
==={{header|GW-BASIC}}===
The [[#Chipmunk_Basic|Chipmunk Basic]] solution works without any changes.
 
==={{header|FUZE BASIC}}===
<syntaxhighlight lang="qbasic">INPUT n$
-- [http://rosettacode.org/wiki/User:Sarossell Scott A. Rossell, 02-27-16]
<lang qbasic>INPUT n$
PRINT VAL(LEFT$(n$,(LEN(STR$(VAL(n$))))))+VAL(RIGHT$(n$,(LEN(n$)-LEN(STR$(VAL(n$)))-1)))
END</langsyntaxhighlight>
 
==={{header|IS-BASIC}}===
<syntaxhighlight lang="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</syntaxhighlight>
 
==={{header|Liberty BASIC}}===
<langsyntaxhighlight lang="lb">input, n$
print eval(word$(n$,1);" + ";word$(n$,2))</langsyntaxhighlight>
 
==={{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}}===
<syntaxhighlight lang="text">
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
</syntaxhighlight>
 
==={{header|Sinclair ZX81 BASIC}}===
<langsyntaxhighlight lang="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 )</langsyntaxhighlight>
 
==={{header|SmallBASIC}}===
<syntaxhighlight lang="SmallBASIC">
input "Enter number A: "; a
input "Enter number B: "; b
print "A + B = "; a + b
</syntaxhighlight>
 
==={{Header|Tiny BASIC}}===
<syntaxhighlight lang="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</syntaxhighlight>
 
==={{header|True BASIC}}===
<syntaxhighlight lang="qbasic">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</syntaxhighlight>
==={{header|uBasic/4tH}}===
<syntaxhighlight lang="text">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@)</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}}==
Prompts version
<syntaxhighlight lang="dos">::aplusb.cmd
@echo off
setlocal
set /p a="A: "
set /p b="B: "
set /a c=a+b
echo %c%
endlocal</syntaxhighlight>
All on the commandline version
<syntaxhighlight lang="dos">::aplusb.cmd
@echo off
setlocal
set a=%1
set b=%2
set /a c=a+b
echo %c%
endlocal</syntaxhighlight>
Formula on the command line version
<syntaxhighlight lang="dos">::aplusb.cmd
@echo off
setlocal
set /a c=%~1
echo %c%
endlocal</syntaxhighlight>
Example of 'Formula on the command line version'
<pre>
>aplusb 123+456
579
>aplusb "1+999"
1000
</pre>
Parse the input stream version (thanks to Tom Lavedas on alt.msdos.batch.nt)
<syntaxhighlight lang="dos">::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</syntaxhighlight>
Example of 'parse the input stream version'
<pre>>aplusb
Input stream: 1234 5678
6912
>aplusb
Input stream: 123 234 345 456 567 678 789 890
4082</pre>
 
=={{header|bc}}==
{{Works with|GNU bc}}
<syntaxhighlight lang ="bc">read() + read()</langsyntaxhighlight>
 
=={{header|Befunge}}==
<syntaxhighlight lang ="befunge">&&+.@</langsyntaxhighlight>
 
=={{header|Bird}}==
<syntaxhighlight lang="bird">use Console Math
 
define Main
$a Console.Read
$b Console.Read
Console.Println Math.Add $a $b
end</syntaxhighlight>
 
=={{header|BlooP}}==
BlooP and FlooP can't actually read from stdin, but here's the procedure it would use, if it could.
<syntaxhighlight lang="bloop">
DEFINE PROCEDURE ''ADD'' [A, B]:
BLOCK 0: BEGIN
OUTPUT <= A + B;
BLOCK 0: END.
</syntaxhighlight>
 
=={{header|bootBASIC}}==
Both numbers are entered separately.
<syntaxhighlight lang="bootbasic">10 print "Number 1";
20 input a
30 print "Number 2";
40 input b
50 print a+b</syntaxhighlight>
 
=={{header|BQN}}==
 
{{works with|https://github.com/dzaima/CBQN CBQN}}
 
<syntaxhighlight lang="bqn">#!/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@</syntaxhighlight>
 
=={{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.
<langsyntaxhighlight lang="bracmat">( out
$ ( put$"Enter two integer numbers between -1000 and 1000:"
& (filter=~/#%:~<-1000:~>1000)
Line 1,034 ⟶ 1,802:
| "Invalid input. Try again"
)
);</langsyntaxhighlight>
 
=={{header|Brainf***}}==
<langsyntaxhighlight lang="brainf***">INPUT AND SUMMATION
TODO if first symbol is a minus sign print Qgo awayQ
+> initialize sum to one
Line 1,060 ⟶ 1,828:
>++++++++++++++++++++++++++++++++++++++++++++++++> convert remainder to ascii digit
]
<[.<<] print ascii digits</langsyntaxhighlight>
 
=={{header|Brat}}==
<langsyntaxhighlight lang="brat">numbers = g.split[0,1].map(:to_i)
p numbers[0] + numbers[1] #Prints the sum of the input</langsyntaxhighlight>
 
=={{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}}==
<syntaxhighlight lang ="burlesque">ps++</langsyntaxhighlight>
 
=={{header|C}}==
<langsyntaxhighlight lang="c">// Standard input-output streams
#include <stdio.h>
int main()
Line 1,078 ⟶ 1,856:
printf("%d\n", a + b);
return 0;
}</langsyntaxhighlight>
<langsyntaxhighlight lang="c">// Input file: input.txt
// Output file: output.txt
#include <stdio.h>
Line 1,090 ⟶ 1,868:
printf("%d\n", a + b);
return 0;
}</langsyntaxhighlight>
<syntaxhighlight lang="c">
<lang c>
#include <stdio.h>
#include <stdlib.h>
Line 1,099 ⟶ 1,877:
return 0;
}
</syntaxhighlight>
</lang>
 
=={{header|C sharp|C#}}==
<langsyntaxhighlight lang="csharp">using System;
using System.Linq;
 
Line 1,111 ⟶ 1,889:
Console.WriteLine(Console.ReadLine().Split().Select(int.Parse).Sum());
}
}</langsyntaxhighlight>
Another way (not recommended since it does not work with more than two numbers):
<langsyntaxhighlight lang="csharp">using System;
 
class Program
Line 1,126 ⟶ 1,904:
Console.WriteLine(sum.ToString());
}
}</langsyntaxhighlight>
 
=={{header|C++}}==
<langsyntaxhighlight lang="cpp">// Standard input-output streams
#include <iostream>
using namespace std;
Line 1,137 ⟶ 1,915:
cin >> a >> b;
cout << a + b << endl;
}</langsyntaxhighlight>
<langsyntaxhighlight lang="cpp">// Input file: input.txt
// Output file: output.txt
#include <fstream>
Line 1,150 ⟶ 1,928:
out << a + b << endl;
return 0;
}</langsyntaxhighlight>
 
=={{header|Ceylon}}==
<langsyntaxhighlight lang="ceylon">shared void run() {
 
print("please enter two numbers for me to add");
Line 1,177 ⟶ 1,955:
}
}
}</langsyntaxhighlight>
 
=={{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}}==
<langsyntaxhighlight lang="clojure">(println (+ (Integer/parseInt (read-line)) (Integer/parseInt (read-line))))
3
4
=>7</langsyntaxhighlight>
<langsyntaxhighlight lang="clojure">(eval (read-string (str "(+ " (read-line) " )") ))
3 3
6</langsyntaxhighlight>
 
Translation of Common Lisp version:
<langsyntaxhighlight lang="clojure">(println (+ (read) (read)))
3 4
7</langsyntaxhighlight>
 
 
Safely and without reader tricks:
<langsyntaxhighlight lang="clojure">(let [ints (map #(Integer/parseInt %) (clojure.string/split (read-line) #"\s") )]
(println (reduce + ints)))
3 4
=>7</langsyntaxhighlight>
 
or same as above, but without "let":
<langsyntaxhighlight lang="clojure">(println (reduce + (map #(Integer/parseInt %) (clojure.string/split (read-line) #"\s") )))
 
3 4
=>7</langsyntaxhighlight>
 
=={{header|COBOL}}==
<langsyntaxhighlight lang="cobol"> IDENTIFICATION DIVISION.
PROGRAM-ID. A-Plus-B.
 
Line 1,226 ⟶ 2,041:
 
GOBACK
.</langsyntaxhighlight>
 
A second version.
 
<syntaxhighlight lang="cobol">
 
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.
 
</syntaxhighlight>
 
=={{header|CoffeeScript}}==
{{trans|JavaScript}}
<langsyntaxhighlight lang="html4strict"><html>
<script type="text/javascript" src="http://jashkenas.github.com/coffee-script/extras/coffee-script.js"></script>
<script type="text/coffeescript">
Line 1,243 ⟶ 2,103:
<div id='output'></div>
</body>
</html></langsyntaxhighlight>
 
{{works with|Node.js}}
<langsyntaxhighlight lang="coffeescript">
{ stdin } = process
sum = ( a, b ) -> a + b
Line 1,277 ⟶ 2,137:
# Start the main loop.
do prompt
</syntaxhighlight>
</lang>
 
=={{header|Common Lisp}}==
<langsyntaxhighlight lang="lisp">(write (+ (read) (read)))</langsyntaxhighlight>
 
=={{header|Component Pascal}}==
BlackBox Component Builder
<langsyntaxhighlight lang="oberon2">
MODULE AB;
IMPORT StdLog, DevCommanders,TextMappers;
Line 1,314 ⟶ 2,174:
END Go;
END AB.
</syntaxhighlight>
</lang>
Execute: <i>AB.Go 12 23 ~ </i><br/>
{{out}}
Line 1,322 ⟶ 2,182:
 
=={{header|Computer/zero Assembly}}==
<langsyntaxhighlight lang="czasm"> STP ; wait for input
a: 0
b: 0
LDA a
ADD b
STP</langsyntaxhighlight>
 
=={{header|Crystal}}==
<langsyntaxhighlight lang="ruby">puts gets.not_nil!.split.map(&.to_i).sum</langsyntaxhighlight>
 
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 1,337 ⟶ 2,197:
To handle the <code>nil</code> case we could do:
 
<langsyntaxhighlight lang="ruby">if line = gets
puts line.split.map(&.to_i).sum
else
puts "No input"
end</langsyntaxhighlight>
 
=={{header|D}}==
===From Console===
<langsyntaxhighlight lang="d">import std.stdio, std.conv, std.string;
 
void main() {
Line 1,355 ⟶ 2,215:
 
writeln(to!int(r[0]) + to!int(r[1]));
}</langsyntaxhighlight>
{{out}}
<pre>30</pre>
===From File===
<langsyntaxhighlight lang="d">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]);
}</langsyntaxhighlight>
 
=={{header|Dart}}==
<langsyntaxhighlight Dartlang="dart">import 'dart:io';
 
// a little helper function that checks if the string only contains
Line 1,394 ⟶ 2,254:
}
}
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,403 ⟶ 2,263:
 
=={{header|dc}}==
<syntaxhighlight lang ="dc">? + psz</langsyntaxhighlight>
 
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}}==
<langsyntaxhighlight DCLlang="dcl">$ read sys$command line
$ a = f$element( 0, " ", line )
$ b = f$element( 1, " ", line )
$ write sys$output a, "+", b, "=", a + b</langsyntaxhighlight>
 
=={{header|Déjà Vu}}==
{{trans|Python}}
===Console===
<lang dejavu>0
for k in split !prompt "" " ":
+ to-num k
!print</lang>
 
=={{header|Delphi}}==
Console version.
<langsyntaxhighlight lang="delphi">program SUM;
 
{$APPTYPE CONSOLE}
Line 1,436 ⟶ 2,289:
Readln(s2);
Writeln(StrToIntDef(s1, 0) + StrToIntDef(s2,0));
end.</langsyntaxhighlight>
 
=={{header|Diego}}==
<syntaxhighlight lang="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[];</syntaxhighlight>
 
=={{header|DMS}}==
<langsyntaxhighlight DMSlang="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" )</langsyntaxhighlight>
 
=={{header|Dragon}}==
<syntaxhighlight lang="dragon">
select "graphic"
select "types"
 
a = int(prompt("Enter A number"))
b = int(prompt("Enter B number"))
 
showln a + b
</syntaxhighlight>
 
=={{header|DWScript}}==
Ghetto GUI version
<langsyntaxhighlight lang="delphi">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));</langsyntaxhighlight>
 
=={{header|Déjà Vu}}==
{{trans|Python}}
===Console===
<syntaxhighlight lang="dejavu">0
for k in split !prompt "" " ":
+ to-num k
!print</syntaxhighlight>
 
=={{header|EasyLang}}==
<syntaxhighlight>
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
</syntaxhighlight>
 
=={{header|EchoLisp}}==
<langsyntaxhighlight lang="scheme">
(+ (read-number 1 "value for A") (read-number 2 "value for B"))
</syntaxhighlight>
</lang>
 
=={{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.
<langsyntaxhighlight lang="edsac">[ A plus B
========
Line 1,488 ⟶ 2,389:
[ When loading is finished: ]
 
EZPF [ Branch to load point ]</langsyntaxhighlight>
{{out}}
<pre>00000000001000001</pre>
 
===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.
<syntaxhighlight lang="edsac">
[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.
</syntaxhighlight>
{{out}}
<pre>
-987
123
-864
</pre>
 
=={{header|EGL}}==
 
<syntaxhighlight lang="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
</syntaxhighlight>
 
=={{header|Eiffel}}==
argument(0) contains the path of the executable - thus we start at argument(1)
<langsyntaxhighlight lang="eiffel">
class
APPLICATION
Line 1,508 ⟶ 2,563:
end
end
</syntaxhighlight>
</lang>
 
Alternatively ...
<langsyntaxhighlight lang="eiffel">
make
-- Run application.
Line 1,532 ⟶ 2,587:
end
end
</syntaxhighlight>
</lang>
 
=={{header|Ela}}==
<langsyntaxhighlight lang="ela">open monad io string list
 
a'b() = do
Line 1,541 ⟶ 2,596:
putStrLn <| show <| sum <| map gread <| string.split " " <| str
 
a'b() ::: IO</langsyntaxhighlight>
 
{{Out}}
Line 1,548 ⟶ 2,603:
 
=={{header|Elena}}==
ELENA 36.20 :
<langsyntaxhighlight lang="elena">import extensions.;
 
public program()
program =
{
[
var A := Integer new.new();
var B := Integer new.new();
console readLine.loadLine(A,B); writeLine.printLine(A + B).
}</syntaxhighlight>
].</lang>
 
Or more generic solution:
<langsyntaxhighlight lang="elena">import system'routines.;
import extensions.;
 
public program()
program =
{
[
console writeLine.printLine(console .readLine;()
.split;()
.selectBy(%"convertorOp.mssgconst toInt<intConvertOp>[01]");
.summarize()).
}</syntaxhighlight>
].</lang>
 
=={{header|Elixir}}==
<langsyntaxhighlight Elixirlang="elixir">IO.gets("Enter two numbers seperated by a space: ")
|> String.split
|> Enum.map(&String.to_integer(&1))
|> Enum.sum
|> IO.puts</langsyntaxhighlight>
 
=={{header|Elm}}==
<syntaxhighlight lang="elm">
<lang Elm>
--To write this function directly run cmd
--Type elm-repl to start
Line 1,591 ⟶ 2,646:
--END
 
</syntaxhighlight>
</lang>
 
=={{header|Emacs Lisp}}==
<syntaxhighlight lang="lisp">(let* ((input (read-from-minibuffer ""))
<lang Emacs Lisp>;; Write this code in a file: a+b.el
(numbers (mapcar #'string-to-number (split-string input)))
;; Put input.txt in the same directory than a+b.el
(a (car numbers))
;; Open a+b.el in emacs and run the program with: M-x eval-buffer
(b (cadr numbers)))
(defun solve (xs) (mapcar (lambda (ys) (apply '+ ys)) xs))
(message "%d" (+ a b)))</syntaxhighlight>
 
=={{header|EMal}}==
(with-temp-buffer
<syntaxhighlight lang="emal">
(insert-file-contents "input.txt")
fun main = int by List args
(setq content (split-string (buffer-string) "\n" t))
text input = when(args.length == 1, args[0], ask(text, "Enter n integers separated by a space: "))
(setq xs (mapcar (lambda (zs) (mapcar #'string-to-number (split-string zs))) content))
int sum, count
(delete-other-windows)
for each text word in input.split(" ")
(find-file-other-window "output.txt")
word = word.trim()
(erase-buffer)
if word.isEmpty() do continue end # ignore empty words
(insert (mapconcat (lambda (x) (format "%d" x)) (solve xs) "\n"))
int nr = int!word # this can raise an exception
(save-buffer))
if abs(nr) > 1000
</lang>
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}}==
<syntaxhighlight lang="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
🍉️</syntaxhighlight>
 
=={{header|Erlang}}==
<langsyntaxhighlight lang="erlang">-module(aplusb).
-export([start/0]).
 
Line 1,620 ⟶ 2,701:
io:format("~w~n",[A+B]),
start()
end.</langsyntaxhighlight>
 
=={{header|ERRE}}==
<syntaxhighlight lang="erre">
<lang ERRE>
PROGRAM SUM2
 
Line 1,636 ⟶ 2,717:
 
END PROGRAM
</syntaxhighlight>
</lang>
 
=={{header|Euler}}==
'''begin'''
'''out''' '''in''' + '''in'''
'''end''' $
 
=={{header|Euler Math Toolbox}}==
 
<syntaxhighlight lang="euler math toolbox">
<lang Euler Math Toolbox>
>s=lineinput("Two numbers seperated by a blank");
Two numbers seperated by a blank? >4 5
Line 1,648 ⟶ 2,734:
>vs[1]()+vs[2]()
9
</syntaxhighlight>
</lang>
 
=={{header|Euphoria}}==
<langsyntaxhighlight lang="euphoria">include get.e
 
function snd(sequence s)
Line 1,662 ⟶ 2,748:
b = snd(get(0))
 
printf(1," %d\n",a+b)</langsyntaxhighlight>
 
=={{header|EGL}}==
 
<lang 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
</lang>
 
=={{header|Excel}}==
Take any 3 columns of any row or rows. Let's say A1,B1 and C1 are taken. In C1 type in :
 
<langsyntaxhighlight lang="excel">
=A1+B1
</syntaxhighlight>
</lang>
 
The value of C1 will change as the values of A1 and B1 are changed
 
<syntaxhighlight lang="text">1 2 3
</syntaxhighlight>
</lang>
 
=={{header|F Sharp|F#}}==
<langsyntaxhighlight lang="fsharp">open System
 
let SumOf(str : string) =
Line 1,708 ⟶ 2,771:
let main argv =
Console.WriteLine(SumOf(Console.ReadLine()))
0</langsyntaxhighlight>
 
=={{header|Factor}}==
<langsyntaxhighlight lang="factor">USING: math.parser splitting ;
: a+b ( -- )
readln " " split1
[ string>number ] bi@ +
number>string print ;</langsyntaxhighlight>
<pre>
( scratchpad ) a+b
Line 1,723 ⟶ 2,786:
 
=={{header|FALSE}}==
<langsyntaxhighlight lang="false">[0[^$$'9>'0@>|~]['0-\10*+]#%]n: {read an integer}
n;!n;!+.</langsyntaxhighlight>
 
=={{header|Fantom}}==
<langsyntaxhighlight lang="fantom">class APlusB
{
public static Void main ()
Line 1,737 ⟶ 2,800:
echo (sum)
}
}</langsyntaxhighlight>
 
=={{header|FBSL}}==
Using stdin and stdout
<langsyntaxhighlight lang="qbasic">#APPTYPE CONSOLE
 
DIM %a, %b
Line 1,747 ⟶ 2,810:
PRINT a, "+", b, "=", a + b
 
PAUSE</langsyntaxhighlight>
 
=={{header|Fennel}}==
{{trans|Lua}}
<syntaxhighlight lang="fennel">
(let [(a b) (io.read :*number :*number)]
(print (+ a b)))
</syntaxhighlight>
 
=={{header|Fhidwfe}}==
<syntaxhighlight lang="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
</syntaxhighlight>
 
=={{header|Fish}}==
<langsyntaxhighlight Fishlang="fish">i:o:"-"=?v1$68*-v
v >~01-0 >
>i:o:" "=?v68*-$a*+
Line 1,756 ⟶ 2,871:
v >~01-0 >
>i:o:d=?v68*-$a*+
>~*+aonao;</langsyntaxhighlight>
 
=={{header|Forth}}==
<langsyntaxhighlight Forthlang="forth">pad dup 80 accept evaluate + .</langsyntaxhighlight>
 
=={{header|Fortran}}==
<langsyntaxhighlight lang="fortran">program a_plus_b
implicit none
integer :: a,b
read (*, *) a, b
write (*, '(i0)') a + b
end program a_plus_b</langsyntaxhighlight>
And in Fortran 77
<syntaxhighlight lang="fortran"> READ (1,100) I,J
100 FORMAT(2I5)
WRITE (2,200) I+J
200 FORMAT(1X,I5)
END</syntaxhighlight>
 
=={{header|Free Pascal}}==
<syntaxhighlight lang="pascal">program SUMA;
uses
SysUtils;
var
s1, s2:integer;
begin
ReadLn(s1);
Readln(s2);
WriteLn(IntToStr(s1 + s2));
end.
</syntaxhighlight>
 
 
=={{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.)
<langsyntaxhighlight lang="frink">
sum[eval[split[%r/\s+/, input[""]]]]
</syntaxhighlight>
</lang>
 
=={{header|FunL}}==
<langsyntaxhighlight lang="funl">println( sum(map(int, readLine().split(' +'))) )</langsyntaxhighlight>
 
=={{header|Furor}}==
<syntaxhighlight lang="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” }
</syntaxhighlight>
{{out}}
<pre>
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
</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}}==
<langsyntaxhighlight lang="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</langsyntaxhighlight>
Output:
<pre>
Line 1,792 ⟶ 3,028:
=={{header|Gastona}}==
Taking A and B from command line arguments
<langsyntaxhighlight lang="gastona">#listix#
 
<main>
"@<p1> + @<p2> = "
=, p1 + p2
</syntaxhighlight>
</lang>
Using Graphical interface
<langsyntaxhighlight lang="gastona">#javaj#
 
<layout of main>
Line 1,814 ⟶ 3,050:
<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}}==
<langsyntaxhighlight lang="gema"><D> <D>=@add{$1;$2}</langsyntaxhighlight>
 
=={{header|Genie}}==
<syntaxhighlight lang="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</syntaxhighlight>
 
{{out}}
<pre>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</pre>
 
=={{header|GML}}==
<langsyntaxhighlight GMLlang="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);</langsyntaxhighlight>
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import "fmt"
Line 1,835 ⟶ 3,133:
fmt.Scan(&a, &b)
fmt.Println(a + b)
}</langsyntaxhighlight>
 
=={{header|Golfscript}}==
<syntaxhighlight lang ="golfscript">~+</langsyntaxhighlight>
 
=={{header|Golo}}==
<syntaxhighlight lang="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")
}
}</syntaxhighlight>
 
=={{header|Gosu}}==
<syntaxhighlight lang="gosu">
<lang Gosu>
uses java.io.InputStreamReader
uses java.util.Scanner
Line 1,851 ⟶ 3,178:
 
print( a + b )
</syntaxhighlight>
</lang>
 
=={{header|Groovy}}==
<langsyntaxhighlight lang="groovy">def abAdder = {
def reader = new Scanner(System.in)
def a = reader.nextInt();
Line 1,861 ⟶ 3,188:
a + b
}
abAdder()</langsyntaxhighlight>
 
=={{header|GUISS}}==
We cannot use variables, but we can find the sum of two numbers.Here we add 3 + 2:
<langsyntaxhighlight lang="guiss">Start,Programs,Accessories,Calculator,Button:3,Button:[plus],
Button:2,Button:[equals]</langsyntaxhighlight>
 
=={{header|Harbour}}==
<syntaxhighlight lang="visualfoxpro">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
</syntaxhighlight>
Screen output:<p>Enter two numbers (range -1000...+1000): ''-56 98''</p>
<p>Sum of given numbers is 42</p>
 
 
=={{header|Haskell}}==
<langsyntaxhighlight lang="haskell">main = print . sum . map read . words =<< getLine</langsyntaxhighlight>
 
=={{header|hexiscript}}==
<syntaxhighlight lang="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</syntaxhighlight>
 
=={{header|HicEst}}==
A and B are input via edit controls with spinners limiting inputs to +-1000.
<langsyntaxhighlight HicEstlang="hicest">DLG(Edit=A, DNum, MIn=-1000, MAx=1000, E=B, DN, MI=-1000, MA=1000)
WRITE(Messagebox, Name) A, B, "Sum = ", A+B</langsyntaxhighlight>
 
=={{header|HyHoon}}==
<syntaxhighlight lang="text">
<lang hy>(print (sum (map int (.split (input)))))</lang>
|= [a=@ud b=@ud] (add a b)
Alternatively, with the "threading tail" macro:
</syntaxhighlight>
<lang hy>(->> (input) (.split) (map int) (sum) (print))</lang>
 
=={{header|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.
<pre>
$ cd lib
$ ../src/hope
>: dec add : num # num -> num;
>: --- add(a,b) <= a + b;
>: add(3,99)
>: ^D
>> 102 : num
</pre>
 
=={{header|Huginn}}==
<langsyntaxhighlight lang="huginn">import Algorithms as algo;
import Text as text;
 
Line 1,897 ⟶ 3,281:
);
);
}</langsyntaxhighlight>
 
=={{header|Hy}}==
<syntaxhighlight lang="hy">(print (sum (map int (.split (input)))))</syntaxhighlight>
Alternatively, with the "threading tail" macro:
<syntaxhighlight lang="hy">(->> (input) (.split) (map int) (sum) (print))</syntaxhighlight>
 
=={{header|i}}==
<syntaxhighlight lang="i">main: print(integer(in(' '))+integer(in('\n'))); ignore</syntaxhighlight>
<lang i>software {
print(number(read(' '))+number(read('\n')))
}</lang>
 
=={{header|Icon}} and {{header|Unicon}}==
<langsyntaxhighlight lang="icon">procedure main()
numChars := '-'++&digits
read() ? {
Line 1,912 ⟶ 3,299:
}
write((\A + \B) | "Bad input")
end</langsyntaxhighlight>
 
=={{header|Idris}}==
<langsyntaxhighlight lang="idris">main : IO()
main = do
line <- getLine
print $ sum $ map cast $ words line</langsyntaxhighlight>
 
=={{header|Insitux}}==
<syntaxhighlight lang="insitux">(+ (to-num (prompt "Enter first number: "))
(to-num (prompt "Enter second number: ")))</syntaxhighlight>
 
=={{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:
<langsyntaxhighlight Jlang="j"> 2+3
5</langsyntaxhighlight>
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
exit ''</langsyntaxhighlight>
3) Here is thean execution of the script:
<langsyntaxhighlight lang="bash">echo 2 3 | ./a+b.ijs
5</langsyntaxhighlight>
 
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}}==
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.*;
<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 {
Line 1,942 ⟶ 3,380:
System.out.println(in.nextInt() + in.nextInt()); // Standard output
}
}</langsyntaxhighlight>
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.
<langsyntaxhighlight lang="java">import java.io.*;
import java.util.*;
 
Line 1,970 ⟶ 3,408:
out.println(nextInt() + nextInt());
}
}</langsyntaxhighlight>
 
The following code uses a StreamTokenizer instead of a Scanner.
 
<langsyntaxhighlight lang="java">import java.io.*;
import java.nio.charset.Charset;
 
Line 1,990 ⟶ 3,428:
}
}
</syntaxhighlight>
</lang>
 
 
<syntaxhighlight lang="text">
grammar aplusb ;
 
Line 2,008 ⟶ 3,446:
NEWLINE : WS* '\r'? '\n'
;
</syntaxhighlight>
</lang>
Produces:
<pre>
Line 2,029 ⟶ 3,467:
Client side:
 
<langsyntaxhighlight lang="html4strict"><html>
<body>
<div id='input'></div>
Line 2,042 ⟶ 3,480:
</script>
</body>
</html></langsyntaxhighlight>
 
Server side (with [http://nodejs.org node.js]):
 
<langsyntaxhighlight lang="javascript">process.openStdin().on (
'data',
function (line) {
Line 2,055 ⟶ 3,493:
process.exit()
}
)</langsyntaxhighlight>
 
$ node io.js
Line 2,066 ⟶ 3,504:
=== ES6 ===
Node.js in a terminal:
<langsyntaxhighlight lang="javascript">process.stdin.on("data", buffer => {
console.log(
(buffer + "").trim().split(" ").map(Number).reduce((a, v) => a + v, 0)
);
});
</syntaxhighlight>
</lang>
 
<pre> $ node io.js
Line 2,079 ⟶ 3,517:
 
=== JScript Windows Script Host Version 5.8 ===
<langsyntaxhighlight lang="javascript">var a = WScript.StdIn.ReadLine();
var b = WScript.StdIn.ReadLine();
WSH.echo(a, " + " , b , " = " , Number(a)+Number(b));
</syntaxhighlight>
</lang>
 
=={{header|Julia}}==
Run from the command line:
<lang julia>
#A+B
function AB()
input = sum(map(int,split(readline(STDIN)," ")))
println(input)
end
AB()</lang>
{{out}}
<pre>>julia AB.jl
1 1
2</pre>
 
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> int(readuntil(STDIN, ' ')) + int(readuntil(STDIN, '\n'))
1 2
3
</lang>
 
=={{header|Joy}}==
===Console===
<syntaxhighlight lang Joy="joy">get get +.</langsyntaxhighlight>
===File===
<langsyntaxhighlight Joylang="joy">"input.txt" include
"output.txt" "w" fopen
get get + fput pop quit.</langsyntaxhighlight>
 
=={{header|jq}}==
Since the given task is simply to add two numbers, the simplest approach in jq is illustrated by the following transcript:
<langsyntaxhighlight lang="jq">$ jq -s add
3 2
5 </langsyntaxhighlight>
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:<langsyntaxhighlight lang="jq">
def addpairs:
if length < 2 then empty
Line 2,123 ⟶ 3,541:
end;
 
addpairs</langsyntaxhighlight>
For example, here is a transcript that assumes the program is in a file named AB.jq:<langsyntaxhighlight lang="jq">
$ jq -s -f AB.jq
1 2 3 4 5 6
3
7
11</langsyntaxhighlight>
 
=={{header|Jsish}}==
<syntaxhighlight lang="javascript">/* 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");
}</syntaxhighlight>
 
{{out}}
<pre>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</pre>
 
=={{header|Julia}}==
Run from the command line:
<syntaxhighlight lang="julia">input = parse.(Int, split(readline(stdin)))
println(stdout, sum(input))</syntaxhighlight>
 
{{out}}
<pre>>julia AB.jl
1 1
2</pre>
 
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.
<syntaxhighlight lang="julia">julia> println(parse(Int, readuntil(stdin, ' ')) + parse(Int, readuntil(stdin, '\n')))
1 2
3</syntaxhighlight>
 
=={{header|K}}==
<syntaxhighlight lang="k">
<lang K>
split:{(a@&~&/' y=/: a:(0,&x=y)_ x) _dv\: y}
ab:{+/0$split[0:`;" "]}
Line 2,138 ⟶ 3,601:
2 3
5
</syntaxhighlight>
</lang>
 
=={{header|Keg}}==
<syntaxhighlight lang="keg">+.</syntaxhighlight>
[https://tio.run/##y05N//9fW@//f1MDLjMDAA Try it online!]
 
Or, using flags (<code>-hr</code>):
<syntaxhighlight lang="keg">+</syntaxhighlight>
[https://tio.run/##y05N//9f@/9/UwMuM4P/uhlFAA Try it online!]
 
=={{header|Kite}}==
<syntaxhighlight lang="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;
];</syntaxhighlight>
{{Out}}
<pre>
$ kite a_plus_b.kt <<EOF
5 6
EOF
11
$</pre>
 
=={{header|Klong}}==
<syntaxhighlight lang="k">
<lang K>
{(1:$(*x?0c )#x)+1:$(1+*|x?0c )_x}@.rl()
2 3
5
</syntaxhighlight>
</lang>
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">// version 1.0.5-2
 
fun main(args: Array<String>) {
Line 2,170 ⟶ 3,663:
}
}
}</langsyntaxhighlight>
 
{{out}}
Line 2,182 ⟶ 3,675:
Enter two integers separated by space(s) or q to quit: q
</pre>
 
=={{header|KQL}}==
<syntaxhighlight lang="kql">datatable(Input:string)[
'2 2',
'3 2'
]
| parse Input with A:int ' ' B:int
| project Input, Output = A + B</syntaxhighlight>
 
=={{header|L++}}==
<langsyntaxhighlight lang="lisp">(main
(decl int a)
(decl int b)
(>> std::cin a b)
(prn (+ a b)))</langsyntaxhighlight>
 
=={{header|LassoLambdatalk}}==
<syntaxhighlight lang="scheme">
<lang lb>[a + b]</lang>
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.
</syntaxhighlight>
 
=={{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}}==
<langsyntaxhighlight lang="lang5">read read + .
 
read " " split expand drop + .</langsyntaxhighlight>
 
=={{header|Lasso}}==
<syntaxhighlight lang="lb">[a + b]</syntaxhighlight>
 
=={{header|LIL}}==
<syntaxhighlight lang="tcl"># 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]</syntaxhighlight>
 
{{out}}
<pre>prompt$ echo '40 2' | lil AB.lil
42</pre>
 
=={{header|Lisaac}}==
<langsyntaxhighlight lang="lisaac">Section Header
+ name := A_PLUS_B
 
Section Public
- main <- ( (IO.read_integer; IO.last_integer) +
(IO.read_integer; IO.last_integer) ).println;</langsyntaxhighlight>
 
=={{header|Little}}==
<langsyntaxhighlight lang="c">void main() {
string a, b;
scan(gets(stdin), "%d %d", &a, &b);
puts(((int)a + (int)b));
}</langsyntaxhighlight>
 
=={{header|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'''
<syntaxhighlight lang="little man computer"> INP
STA 99
INP
ADD 99
OUT
HLT
// Output the sum of two numbers</syntaxhighlight>
 
'''Machine code'''
<syntaxhighlight lang="little man computer">00 INP
01 STA 99
02 INP
03 ADD 99
04 OUT
05 HLT</syntaxhighlight>
 
=={{header|LiveCode}}==
Using Livecode Server script
<syntaxhighlight lang="livecode"><?lc
<lang LiveCode><?lc
if isNumber($0) and isNumber($1) then
put $0 + $1
Line 2,221 ⟶ 3,804:
put $0 && $1
end if
?></langsyntaxhighlight>
 
A graphical version using an input dialog
<langsyntaxhighlight LiveCodelang="livecode">on mouseUp
ask "Enter two numbers"
set itemdelimiter to space
Line 2,233 ⟶ 3,816:
answer item 1 of nums && item 2 of nums
end if
end mouseUp</langsyntaxhighlight>
 
=={{header|Logo}}==
<langsyntaxhighlight lang="logo">show apply "sum readlist</langsyntaxhighlight>
 
=={{header|Lua}}==
<langsyntaxhighlight Lualang="lua">a,b = io.read("*number", "*number")
print(a+b)</langsyntaxhighlight>
 
=={{header|KiteM2000 Interpreter}}==
<syntaxhighlight lang="text">Def Range(X%)=Abs(X%)<=1000
<lang Kite>#!/usr/bin/kite
Do {
 
Input A%, B%
import "System.file";
} Until Range(A%) And Range(B%)
 
Print A%+B%</syntaxhighlight>
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;
];</lang>
{{Out}}
<pre>
$ kite a_plus_b.kt <<EOF
5 6
EOF
11
$</pre>
 
=={{header|M4}}==
<langsyntaxhighlight M4lang="m4"> define(`sumstr', `eval(patsubst(`$1',` ',`+'))')
 
sumstr(1 2)
3</langsyntaxhighlight>
 
=={{header|Maple}}==
<langsyntaxhighlight lang="maple"> convert( scanf( "%d %d" ), '`+`' );
23 34
57</langsyntaxhighlight>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
Interactive in a notebook
<syntaxhighlight lang Mathematica="mathematica">Input[] + Input[]</langsyntaxhighlight>
 
=={{header|MATLAB}} / {{header|Octave}}==
<langsyntaxhighlight MATLABlang="matlab">function sumOfInputs = APlusB()
inputStream = input('Enter two numbers, separated by a space: ', 's');
numbers = str2num(inputStream); %#ok<ST2NM>
Line 2,287 ⟶ 3,855:
end
sumOfInputs = sum(numbers);
end</langsyntaxhighlight>
 
=={{header|Maude}}==
===Built-in===
<syntaxhighlight lang="maude">
<lang Maude>
red 3 + 4 .
</syntaxhighlight>
</lang>
===With restrictions===
<syntaxhighlight lang="maude">
<lang Maude>
fmod ADD is
 
Line 2,308 ⟶ 3,876:
endfm
</syntaxhighlight>
</lang>
 
=={{header|Maxima}}==
<syntaxhighlight lang="text">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);
</syntaxhighlight>
 
=={{header|Mercury}}==
<syntaxhighlight lang="text">:- module a_plus_b.
:- interface.
 
Line 2,330 ⟶ 3,907:
else
true
).</langsyntaxhighlight>
 
=={{header|Maximamin}}==
{{works with|min|0.19.3}}
<lang>in_stream: openr("/dev/stdin");
<syntaxhighlight lang="min">gets " " split 'bool filter 'int map sum puts!</syntaxhighlight>
unless (line: readline(in_stream), line=false) do (
 
q: map('parse_string, split(line, " ")),
=={{header|MiniScript}}==
print(q[1]+q[2])
The <code>input</code> intrinsic in MiniScript isn't available in all implementations, so we've just hard-coded the input here:
);
<syntaxhighlight lang="miniscript">s = " 2 3 "
close(in_stream);
fields = s.split
</lang>
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</syntaxhighlight>
 
{{out}}
<pre>5</pre>
 
=={{header|mIRC Scripting Language}}==
<langsyntaxhighlight lang="mirc">alias a+b {
echo -ag $calc($1 + $2)
}</langsyntaxhighlight>
 
=={{header|МК-61/52}}==
Line 2,353 ⟶ 3,941:
=={{header|ML/I}}==
The two numbers are read from 'standard input' or its equivalent.
<langsyntaxhighlight MLlang="ml/Ii">MCSKIP "WITH" NL
"" A+B
"" assumes macros on input stream 1, terminal on stream 2
Line 2,365 ⟶ 3,953:
MCSKIP SL WITH *
MCSET S1=1
*MCSET S10=2</langsyntaxhighlight>
 
=={{header|Modula-2}}==
<langsyntaxhighlight lang="modula2">MODULE ab;
 
IMPORT InOut;
Line 2,379 ⟶ 3,967:
InOut.WriteInt (A + B, 8);
InOut.WriteLn
END ab.</langsyntaxhighlight>
 
=={{header|Modula-3}}==
<syntaxhighlight lang="modula3">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.</syntaxhighlight>
 
=={{header|MoonScript}}==
<langsyntaxhighlight lang="moonscript">a,b = io.read '*number','*number'
print a + b</langsyntaxhighlight>
 
=={{header|Mosaic}}==
<syntaxhighlight lang="mosaic">
proc main =
int a, b
 
print "?"
readln a, b
println a + b
end
</syntaxhighlight>
 
=={{header|MUMPS}}==
<syntaxhighlight lang="mumps">ANB
<lang MUMPS>ANB
NEW A,B,T,S
READ !,"Input two integers between -1000 and 1000, separated by a space: ",S
Line 2,393 ⟶ 4,010:
IF T WRITE !,(A+B)
IF 'T WRITE !,"Bad input"
QUIT</langsyntaxhighlight>
 
=={{header|Nanoquery}}==
<syntaxhighlight lang="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])</syntaxhighlight>
 
=={{header|Neko}}==
<syntaxhighlight lang="actionscript">/**
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")</syntaxhighlight>
 
{{out}}
<pre>prompt$ nekoc a+b.neko
prompt$ echo '2 2' | neko a+b
4
prompt$ neko a+b
2 3
5</pre>
 
=={{header|Nemerle}}==
{{trans|C#}}
<langsyntaxhighlight Nemerlelang="nemerle">using System;
using System.Console;
using System.Linq;
Line 2,407 ⟶ 4,109:
WriteLine(ReadLine().Split().Select(int.Parse).Sum());
}
}</langsyntaxhighlight>
 
=={{header|NetRexx}}==
<langsyntaxhighlight NetRexxlang="netrexx">/* NetRexx */
 
options replace format comments java symbols binary
 
parse ask a b .
say a '+' b '=' a + b</langsyntaxhighlight>
 
=={{header|newLISP}}==
<langsyntaxhighlight newLISPlang="newlisp">(println (apply + (map int (parse (read-line)))))</langsyntaxhighlight>
 
=={{header|Nim}}==
A+B:
<syntaxhighlight lang="nim">
<lang nim>import strutils, os
# 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
echo parseInt(paramStr(1)) + parseInt(paramStr(2))</lang>
Arbitrary number of arguments:
<lang nim>import strutils, os
var sum = 0
for i in countup(1, paramCount()):
sum = sum + parseInt(paramStr(i))
echo sum</lang>
 
another:
 
<lang nim>from strutils import parseFloat, formatFloat, ffDecimal
 
proc aplusb(a,b: float): float =
Line 2,452 ⟶ 4,145:
let second: float = getnumber()
 
echo("Result: " & formatFloat(aplusb(first, second), ffDecimal, 2))</langsyntaxhighlight>
 
The puzzle requires 1 input, 2 INTS separated by a space, than a+b
Needs to be revisited
 
=={{header|Nit}}==
Generic non-robust version (source: [https://github.com/nitlang/nit/blob/master/examples/rosettacode/ab.nit the Nit’s official repository]):
<langsyntaxhighlight lang="nit">module ab
 
var words = gets.split(" ")
Line 2,463 ⟶ 4,159:
return
end
print words[0].to_i + words[1].to_i</langsyntaxhighlight>
 
=={{header|ObjeckNS-HUBASIC}}==
<syntaxhighlight lang="ns-hubasic">10 INPUT "ENTER NUMBER A: ",A
<lang objeck>bundle Default {
20 INPUT "ENTER NUMBER B: ",B
class Vander {
30 PRINT A+B</syntaxhighlight>
function : Main(args : String[]) ~ Nil {
 
values := IO.Console->ReadString()->Split(" ");
=={{header|Nu}}==
if(values->Size() = 2) {
<syntaxhighlight lang="nu">
(values[0]->Trim()->ToInt() + values[1]->Trim()->ToInt())->PrintLine();
input | parse "{a} {b}" | first | values | into int | math sum
};
</syntaxhighlight>
}
 
}
=={{header|Nutt}}==
}</lang>
<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}}==
===SAL Syntax===
<syntaxhighlight lang="nyquist">;nyquist plug-in
;version 1
;type tool
;name "A+B"
;debugflags trace
define variable a = 1
define variable b = 9
print a + b
return ""</syntaxhighlight>
 
===Audacity plug-in (SAL syntax)===
<syntaxhighlight lang="nyquist">;nyquist plug-in
;version 1
;type tool
;name "A+B"
;debugflags trace
 
define variable a = 1
define variable b = 9
 
print a + b
 
return ""</syntaxhighlight>
 
=={{header|Oberon-2}}==
<langsyntaxhighlight lang="oberon2">MODULE ab;
 
IMPORT In, Out;
Line 2,489 ⟶ 4,223:
Out.Int (A + B, 8);
Out.Ln
END ab.</langsyntaxhighlight>
Producing
<pre>
Line 2,495 ⟶ 4,229:
46
</pre>
 
=={{header|Objeck}}==
<syntaxhighlight lang="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();
};
}
}
}</syntaxhighlight>
 
=={{header|OCaml}}==
<langsyntaxhighlight lang="ocaml">Scanf.scanf "%d %d" (fun a b -> Printf.printf "%d\n" (a + b))</langsyntaxhighlight>
 
=={{header|Oforth}}==
Line 2,503 ⟶ 4,249:
Works with any number of integers separated by a space.
 
<langsyntaxhighlight Oforthlang="oforth">import: mapping
 
System.Console accept words map( #>integer) reduce( #+ ) printcr .</langsyntaxhighlight>
 
=={{header|Ol}}==
{{works with|Ol 1.2}}
Note: input data must be separated by newline ([Enter] key press).
 
<langsyntaxhighlight lang="ol">; simplest
(+ (read) (read))
 
Line 2,523 ⟶ 4,268:
 
(print a " + " b " = " (+ a b)))
</syntaxhighlight>
</lang>
 
=={{header|Onyx}}==
 
<langsyntaxhighlight lang="onyx">$Prompt {
`\nEnter two numbers between -1000 and +1000,\nseparated by a space: ' print flush
} def
Line 2,551 ⟶ 4,296:
} def
 
Prompt GetNumbers CheckInput Answer</langsyntaxhighlight>
 
=={{header|ooRexx}}==
===version 1===
{{trans|REXX}}
<langsyntaxhighlight lang="oorexx">Numeric digits 1000 /*just in case the user gets ka-razy. */
Say 'enter some numbers to be summed:'
parse pull y
Line 2,574 ⟶ 4,319:
Parse arg list
list=space(list)
return translate(list,'+',' ')</langsyntaxhighlight>
{{out}}
<pre>enter some numbers to be summed:
Line 2,580 ⟶ 4,325:
===version 2===
extend for negative numbers
<langsyntaxhighlight lang="oorexx">Numeric digits 1000
Say 'enter some numbers to be summed:'
parse pull y
Line 2,600 ⟶ 4,345:
End
Say yplus '=' sum/1
Exit</langsyntaxhighlight>
 
=={{header|OpenEdge/Progress}}==
<langsyntaxhighlight lang="progress">DEFINE VARIABLE a AS INTEGER NO-UNDO FORMAT "->>>9".
DEFINE VARIABLE b AS INTEGER NO-UNDO FORMAT "->>>9".
 
Line 2,614 ⟶ 4,359:
UPDATE a b.
 
MESSAGE a + b VIEW-AS ALERT-BOX</langsyntaxhighlight>
 
=={{header|Openscad}}==
There is no means of run-time input in Openscad
<langsyntaxhighlight lang="openscad">
a = 5 + 4;
echo (a);
</syntaxhighlight>
</lang>
 
=={{header|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))'''.
<syntaxhighlight lang="order">
#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)))
</syntaxhighlight>
 
=={{header|Oxygene}}==
<langsyntaxhighlight lang="oxygene">
// Sum 2 integers read fron standard input
//
Line 2,657 ⟶ 4,445:
end.
</syntaxhighlight>
</lang>
Produces:
<pre>
Line 2,666 ⟶ 4,454:
 
=={{header|Oz}}==
<langsyntaxhighlight lang="oz">declare
class TextFile from Open.file Open.text end
 
Line 2,675 ⟶ 4,463:
end
in
{Show {ReadInt}+{ReadInt}}</langsyntaxhighlight>
 
=={{header|PARI/GP}}==
User input:
<syntaxhighlight lang ="parigp">input()+input()</langsyntaxhighlight>
File input:
<langsyntaxhighlight lang="parigp">read("file1")+read("file2")</langsyntaxhighlight>
 
=={{header|PascalABC.NET}}==
<syntaxhighlight lang="pascal">
##
var (a,b) := ReadInteger2;
Writeln(a + b);
</syntaxhighlight>
 
 
=={{header|Pascal}}==
<langsyntaxhighlight lang="pascal">var
a, b: integer;
begin
readln(a, b);
writeln(a + b);
end.</langsyntaxhighlight>
Same with input from file <tt>input.txt</tt> and output from file <tt>output.txt</tt>.
<langsyntaxhighlight lang="pascal">var
a, b: integer;
begin
Line 2,700 ⟶ 4,496:
close(input);
close(output);
end.</langsyntaxhighlight>
===Version 2. Following the rules===
<syntaxhighlight lang="pascal">{ Task: A + B
Sum of A + B while A, B >= -1000 and A,B <= 1000
Author: Sinuhe Masan (2019) }
program APlusB;
 
var
=={{header|Perl}}==
A, B : integer;
<lang Perl>my ($a,$b) = split(' ', scalar(<STDIN>));
print "$a $b " . ($a + $b) . "\n";</lang>
 
begin
=== using the List::Util module ===
repeat
<lang Perl>say sum split /\s+/, scalar <STDIN>;</lang>
write('Enter two numbers betwen -1000 and 1000 separated by space: ');
readln(A, B);
 
until ((abs(A) < 1000) and (abs(B) < 1000));
=={{header|Perl 6}}==
{{works with|rakudo|2015.12}}
 
writeln('The sum is: ', A + B);
Short version with very little "line noise":
 
<lang perl6>get.words.sum.say;</lang>
end.</syntaxhighlight>
Reduction operator <code>[+]</code>, and <code>say</code> as a function:
 
<lang perl6>say [+] get.words;</lang>
=={{header|Perl}}==
Long version:
<langsyntaxhighlight perl6lang="perl">my ($a, $b) = $*IN.get.split("' "', scalar(<STDIN>));
sayprint "$a $b " . ($a + $b) . "\n";</langsyntaxhighlight>
 
=== using the List::Util module ===
<syntaxhighlight lang="perl">say sum split /\s+/, scalar <STDIN>;</syntaxhighlight>
 
=={{header|Phix}}==
<!--<syntaxhighlight lang="phix">-->
When presented with a problem this simple, I start inventing difficulty
<span style="color: #000080;font-style:italic;">-- demo\rosetta\AplusB.exw</span>
in the simple act of accepting input (especially 2 numbers on one line)...
<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>
so I ended up with three different solutions, this being the longest.
<span style="color: #004080;">sequence</span> <span style="color: #000000;">r</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">scanf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%d %d"</span><span style="color: #0000FF;">)</span>
The much shorter Euphoria version above also works fine.
<span style="color: #008080;">if</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">r</span><span style="color: #0000FF;">)=</span><span style="color: #000000;">1</span> <span style="color: #008080;">then</span>
<lang Phix>-- longhand version, input is echoed, full error handling
<span style="color: #004080;">integer</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">a</span><span style="color: #0000FF;">,</span><span style="color: #000000;">b</span><span style="color: #0000FF;">}</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">r</span><span style="color: #0000FF;">[</span><span style="color: #000000;">1</span><span style="color: #0000FF;">],</span> <span style="color: #000000;">c</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">a</span><span style="color: #0000FF;">+</span><span style="color: #000000;">b</span>
string text
<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;">"%d + %d = %d\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">a</span><span style="color: #0000FF;">,</span><span style="color: #000000;">b</span><span style="color: #0000FF;">,</span><span style="color: #000000;">c</span><span style="color: #0000FF;">})</span>
integer idx = 0
<span style="color: #008080;">else</span>
integer ch
<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>
<!--</syntaxhighlight>-->
{{out}}
<pre>
Enter two numbers separated by a space : 2 3
2 + 3 = 5
</pre>
=== GUI version ===
{{libheader|Phix/pGUI}}
<small>(The above console version is now just a comment in the distributed file.)</small>
<!--<syntaxhighlight lang="phix">(phixonline)-->
<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;">include</span> <span style="color: #000000;">pGUI</span><span style="color: #0000FF;">.</span><span style="color: #000000;">e</span>
<span style="color: #004080;">Ihandle</span> <span style="color: #000000;">lab</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">tab</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">res</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">dlg</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">valuechanged_cb</span><span style="color: #0000FF;">(</span><span style="color: #004080;">Ihandle</span> <span style="color: #000000;">tab</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;">IupGetAttribute</span><span style="color: #0000FF;">(</span><span style="color: #000000;">tab</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"VALUE"</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">r</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">scanf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%d %d"</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">if</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">r</span><span style="color: #0000FF;">)=</span><span style="color: #000000;">1</span> <span style="color: #008080;">then</span>
<span style="color: #004080;">integer</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">a</span><span style="color: #0000FF;">,</span><span style="color: #000000;">b</span><span style="color: #0000FF;">}</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">r</span><span style="color: #0000FF;">[</span><span style="color: #000000;">1</span><span style="color: #0000FF;">]</span>
<span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">sprintf</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"%d + %d = %d"</span><span style="color: #0000FF;">,</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">a</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">b</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">a</span><span style="color: #0000FF;">+</span><span style="color: #000000;">b</span><span style="color: #0000FF;">})</span>
<span style="color: #7060A8;">IupSetStrAttribute</span><span style="color: #0000FF;">(</span><span style="color: #000000;">res</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"TITLE"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">IupRefresh</span><span style="color: #0000FF;">(</span><span style="color: #000000;">res</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">return</span> <span style="color: #004600;">IUP_DEFAULT</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #008080;">procedure</span> <span style="color: #000000;">main</span><span style="color: #0000FF;">()</span>
<span style="color: #7060A8;">IupOpen</span><span style="color: #0000FF;">()</span>
<span style="color: #000000;">lab</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">IupLabel</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: #000000;">tab</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">IupText</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"VALUECHANGED_CB"</span><span style="color: #0000FF;">,</span> <span style="color: #7060A8;">Icallback</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"valuechanged_cb"</span><span style="color: #0000FF;">),</span><span style="color: #008000;">"EXPAND=HORIZONTAL"</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">IupLabel</span><span style="color: #0000FF;">(</span><span style="color: #008000;">""</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">dlg</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">IupDialog</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">IupVbox</span><span style="color: #0000FF;">({</span><span style="color: #7060A8;">IupHbox</span><span style="color: #0000FF;">({</span><span style="color: #000000;">lab</span><span style="color: #0000FF;">,</span><span style="color: #000000;">tab</span><span style="color: #0000FF;">},</span><span style="color: #008000;">"GAP=10,NORMALIZESIZE=VERTICAL"</span><span style="color: #0000FF;">),</span>
<span style="color: #7060A8;">IupHbox</span><span style="color: #0000FF;">({</span><span style="color: #000000;">res</span><span style="color: #0000FF;">})},</span><span style="color: #008000;">"MARGIN=5x5"</span><span style="color: #0000FF;">),</span><span style="color: #008000;">`TITLE="A plus B"`</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">IupShow</span><span style="color: #0000FF;">(</span><span style="color: #000000;">dlg</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">if</span> <span style="color: #7060A8;">platform</span><span style="color: #0000FF;">()!=</span><span style="color: #004600;">JS</span> <span style="color: #008080;">then</span>
<span style="color: #7060A8;">IupMainLoop</span><span style="color: #0000FF;">()</span>
<span style="color: #7060A8;">IupClose</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;">procedure</span>
<span style="color: #000000;">main</span><span style="color: #0000FF;">()</span>
<!--</syntaxhighlight>-->
 
=={{header|Phixmonti}}==
procedure nextch()
<syntaxhighlight lang="phixmonti">/# Rosetta Code problem: http://rosettacode.org/wiki/A+B
idx += 1
by Galileo, 05/2022 #/
if idx>length(text) then
idx = 0
ch = 0
else
ch = text[idx]
end if
end procedure
 
include ..\Utilitys.pmt
function getNumber()
integer sign = 0
integer res = 0
while find(ch," \t\r\n") do
nextch()
end while
if idx=0 then
puts(1,"\nenter another number\n")
text = gets(0)
idx = 0
nextch()
end if
if ch='-' then
sign = 1
nextch()
end if
if idx=0 or ch<'0' or ch>'9' then
idx = 0
else
while 1 do
res = res*10+ch-'0'
nextch()
if idx=0 or ch<'0' or ch>'9' then exit end if
end while
if sign then
res = -res
end if
end if
return res
end function
 
def valid
procedure twoNumbers()
dup -1000 >= swap 1000 <= and
integer a, b
enddef
text = gets(0)
idx = 0
nextch()
if idx!=0 then
a = getNumber()
if idx!=0 and a>=-1000 and a<=1000 then
b = getNumber()
if idx!=0 and b>=-1000 and b<=1000 then
printf(1," %d\n",{a+b})
return
end if
end if
end if
puts(1," some error\n")
end procedure
 
true while
twoNumbers()</lang>
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
#/</syntaxhighlight>
{{out}}
<pre>Enter two numbers (betwen -1000 ... +1000) separated by space: 2 3
The sum of 2 and 3 is: 5
=== Press any key to exit ===</pre>
 
=={{header|PHP}}==
<langsyntaxhighlight lang="php">fscanf(STDIN, "%d %d\n", $a, $b); //Reads 2 numbers from STDIN
echo ($a + $b) . "\n";</langsyntaxhighlight>
<langsyntaxhighlight lang="php">$in = fopen("input.dat", "r");
fscanf($in, "%d %d\n", $a, $b); //Reads 2 numbers from file $in
fclose($in);
Line 2,800 ⟶ 4,615:
$out = fopen("output.dat", "w");
fwrite($out, ($a + $b) . "\n");
fclose($out);</langsyntaxhighlight>
 
=={{header|Picat}}==
<syntaxhighlight lang="picat">
go =>
println("Write two integers (and CR)"),
println(read_int()+read_int()).
</syntaxhighlight>
 
{{out}}
<pre>Picat> go
Write two integers (and CR)
2 5
7
</pre>
 
Or directly in the REPL:
<pre>
Picat> read_int()+read_int()=X
2 5
X = 7
</pre>
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(+ (read) (read))
3 4
-> 7</langsyntaxhighlight>
 
=={{header|Piet}}==
[[File:Piet A+B.png]]
The code is fairly straightforward. The individual commands are as follows:
<langsyntaxhighlight lang="text">in(num)
in(num)
add
out(num)</langsyntaxhighlight>
 
=={{header|Pike}}==
<langsyntaxhighlight Pikelang="pike">string line = Stdio.stdin->gets();
sscanf(line, "%d %d", int a, int b);
write(a+b +"\n");</langsyntaxhighlight>
 
=={{header|PL/I}}==
<langsyntaxhighlight lang="pli">get (a, b);
put (a+b);</langsyntaxhighlight>
 
=={{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}}==
<syntaxhighlight lang="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())
 
</syntaxhighlight>
 
=={{header|PostScript}}==
<langsyntaxhighlight lang="postscript">(%stdin) (r) file % get stdin
dup
token pop % read A
Line 2,831 ⟶ 4,717:
token pop % read B
add
=</langsyntaxhighlight>
 
=={{header|Potion}}==
<langsyntaxhighlight lang="potion"># The numbers are entered, piped, or redirected in via STDIN and the format is proper (i.e., "%d %d").
input = read
i = 0
Line 2,846 ⟶ 4,732:
 
# The numbers are manually inputted, but the format is improper (i.e., "%d\n%d\n").
(read number + read number) print</langsyntaxhighlight>
 
=={{header|PowerShell}}==
<langsyntaxhighlight lang="powershell">$a,$b = -split "$input"
[int]$a + [int]$b</langsyntaxhighlight>
This solution does not work interactively, while the following ''only'' works interactively:
<langsyntaxhighlight lang="powershell">$a,$b = -split (Read-Host)
[int]$a + [int]$b</langsyntaxhighlight>
 
I think this works better and doesn't require string input (following the task closer):
<langsyntaxhighlight lang="powershell">filter add {
return [int]$args[0] + [int]$args[1]
}</langsyntaxhighlight>
 
Can be called in one line with
<syntaxhighlight lang ="powershell">add 2 3</langsyntaxhighlight>
 
=={{header|Processing}}==
===Rudimentary User Interface===
Click on either side to add 1 to its value.
<langsyntaxhighlight Processinglang="processing">int a = 0;
int b = 0;
 
Line 2,890 ⟶ 4,776:
b++;
}
}</langsyntaxhighlight>
 
[https://i.imgur.com/QEHtMyA.jpg What the GUI looks like.]
Line 2,896 ⟶ 4,782:
=={{header|ProDOS}}==
With the math module:
<langsyntaxhighlight ProDOSlang="prodos">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- </langsyntaxhighlight>
Without the math module:
<langsyntaxhighlight ProDOSlang="prodos">editvar /newvar /value=a /title=Enter an integer:
editvar /newvar /value=b /title=Enter another integer:
editvar /newvar /value=c=-a-+-b-
printline -c- </langsyntaxhighlight>
 
=={{header|Prolog}}==
{{Works with|SWI-Prolog}}
<langsyntaxhighlight Prologlang="prolog">plus :-
read_line_to_codes(user_input,X),
atom_codes(A, X),
Line 2,915 ⟶ 4,801:
maplist(atom_number, L, LN),
sumlist(LN, N),
write(N).</langsyntaxhighlight>
output :
<langsyntaxhighlight Prologlang="prolog">?- plus.
|: 4 5
9
true.</langsyntaxhighlight>
 
=={{header|Pure}}==
<langsyntaxhighlight lang="pure">using system;
printf "%d\n" (x+y) when x,y = scanf "%d %d" end;</langsyntaxhighlight>
 
=={{header|PureBasic}}==
===Console===
<langsyntaxhighlight PureBasiclang="purebasic">x$=Input()
a=Val(StringField(x$,1," "))
b=Val(StringField(x$,2," "))
PrintN(str(a+b))</langsyntaxhighlight>
===File===
<langsyntaxhighlight PureBasiclang="purebasic">If ReadFile(0,"in.txt")
x$=ReadString(0)
a=Val(StringField(x$,1," "))
Line 2,942 ⟶ 4,828:
EndIf
CloseFile(0)
EndIf </langsyntaxhighlight>
 
=={{header|Python}}==
Line 2,951 ⟶ 4,837:
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.
 
<langsyntaxhighlight lang="python">try: raw_input
except: raw_input = input
 
print(sum(map(int, raw_input().split())))</langsyntaxhighlight>
 
===File===
For Python 2.X and 3.X taking input from stdin stream which can be redirected to be file input under Unix
<langsyntaxhighlight lang="python">import sys
 
for line in sys.stdin:
print(sum(map(int, line.split())))</langsyntaxhighlight>
 
===Console, Python 3 only===
<syntaxhighlight lang="python">a = int(input("First number: "))
b = int(input("Second number: "))
print("Result:", a+b)</syntaxhighlight>
 
=={{header|QB64}}==
<syntaxhighlight lang="qb64">DIM a AS INTEGER, b AS INTEGER
<lang QB64>
DIM a AS INTEGER, b AS INTEGER
DIM c AS LONG
INPUT "Enter A: ", a
Line 2,971 ⟶ 4,861:
c = a + b
PRINT ""
PRINT "A + B = " + LTRIM$(STR$(c)) </syntaxhighlight>
 
</lang>
'''Fully implemented version:'''
<br>
''CBTJD'': 2020/03/13
----
* Task description requires:
** Both integers entered on one line.
** Integers between -1000 and +1000.
<syntaxhighlight lang="qbasic">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$</syntaxhighlight>
 
=={{header|Quackery}}==
'''As a dialogue in the Quackery shell:'''
<pre>/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.</pre>
 
=={{header|Quite BASIC}}==
<syntaxhighlight lang="quite basic">10 input "Enter number A: ";a
20 input "Enter number B: ";b
30 print a+b</syntaxhighlight>
 
=={{header|R}}==
<langsyntaxhighlight lang="r">sum(scan("", numeric(0), 2))</langsyntaxhighlight>
 
=={{header|Ra}}==
<syntaxhighlight lang="ra">
<lang Ra>
class Sum
**Adds two given integers**
Line 3,004 ⟶ 4,932:
print to Console.error made !, "Numbers too large"
exit program with error code
</syntaxhighlight>
</lang>
 
=={{header|Racket}}==
 
<langsyntaxhighlight lang="racket">
#lang racket
(+ (read) (read))
</syntaxhighlight>
</lang>
 
Or, with additional error checking:
<langsyntaxhighlight lang="racket">
#lang racket
(define a (read))
Line 3,021 ⟶ 4,949:
(unless (number? b) (error 'a+b "number" b))
(displayln (+ a b))
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
(formerly Perl 6)
{{works with|rakudo|2015.12}}
 
Short version with very little "line noise":
<syntaxhighlight lang="raku" line>get.words.sum.say;</syntaxhighlight>
Reduction operator <code>[+]</code>, and <code>say</code> as a function:
<syntaxhighlight lang="raku" line>say [+] get.words;</syntaxhighlight>
Long version:
<syntaxhighlight lang="raku" line>my ($a, $b) = $*IN.get.split(" ");
say $a + $b;</syntaxhighlight>
 
=={{header|REBOL}}==
<langsyntaxhighlight lang="rebol">forever [x: load input print x/1 + x/2]</langsyntaxhighlight>
{{Out}}
<pre>1 2
Line 3,034 ⟶ 4,974:
 
=={{header|Red}}==
<langsyntaxhighlight Redlang="red">x: load input print x/1 + x/2</langsyntaxhighlight>
{{Out}}
<pre>1 2
Line 3,044 ⟶ 4,984:
 
Alternative implementations:
<langsyntaxhighlight Redlang="red">print (first x: load input) + x/2</langsyntaxhighlight>
<langsyntaxhighlight Redlang="red">print head insert load input 'add</langsyntaxhighlight>
<langsyntaxhighlight Redlang="red">print load replace input " " " + "</langsyntaxhighlight>
 
=={{header|Relation}}==
<syntaxhighlight lang="relation">
set input = "2 2"
set a = regexreplace(input,"^(-?\d+)\s+(-?\d+)+$","$1")
set b = regexreplace(input,"^(-?\d+)\s+(-?\d+)+$","$2")
echo a + b
</syntaxhighlight>
 
=={{header|Retro}}==
<langsyntaxhighlight Retrolang="retro">: try ( "-n ) getTokens:get toNumbers:to-number getTokens:get toNumbers:to-number + putnn:put ;</langsyntaxhighlight>
<syntaxhighlight lang Retro="retro">try 1 2</lang>
1
2</syntaxhighlight>
 
=={{header|REXX}}==
===version 1, unnormalized===
The numbers can be any valid REXX number (integer, fixed point decimal, floating point (with exponential notation, ···).
<langsyntaxhighlight 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.*/
say a+b /*display the sum to the terminal. */
/*stick a fork in it, we're all done. */</langsyntaxhighlight>
===version 2, normalizied===
If the user entered &nbsp; '''4.00000''' &nbsp; and wanted to add &nbsp; '''5''' &nbsp; to that, and expects &nbsp; '''9''',
Line 3,067 ⟶ 5,017:
 
Dividing by one normalizes the number.
<langsyntaxhighlight 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.*/
say (a+b) / 1 /*display normalized sum to terminal. */
/*stick a fork in it, we're all done. */</langsyntaxhighlight>
 
===version 3, extended precision===
Using the &nbsp; '''numeric digits''' &nbsp; statement allows more decimal digits to be used, the default is &nbsp; '''9'''.
<langsyntaxhighlight 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.*/
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. */</syntaxhighlight>
 
</lang>
===version 4, multiple numbers===
This REXX program version adds &nbsp; ''all'' &nbsp; the numbers entered &nbsp; (not just two).
<langsyntaxhighlight 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. */
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 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.*/</syntaxhighlight>
 
===version 5, multiple numbers, tongue in cheek===
say 'sum of ' many " numbers = " $/1 /*display normalized sum $ to terminal.*/
<syntaxhighlight lang="rexx">/*REXX program obtains some numbers from the input stream (the console), shows their sum*/
/*stick a fork in it, we're all done. */</lang>
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.*/</syntaxhighlight>
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">give Numbers
Numbers = split(Numbers)
sum = 0
Line 3,105 ⟶ 5,064:
func Split Str
for x in str if x = " " x = nl ok next
return str2list(str)</langsyntaxhighlight>
 
=={{header|RubyRobotic}}==
<syntaxhighlight lang="robotic">
<lang ruby>puts gets.split.map(&:to_i).inject(:+)</lang>
input string "Input A:"
set "A" to "input"
input string "Input B:"
set "B" to "input"
* "('A' + 'B')"
end
</syntaxhighlight>
 
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.
=={{header|Run BASIC}}==
<lang runbasic>input, x$
print val(word$(x$,1)) + val(word$(x$,2))</lang>
 
=={{header|Rockstar}}==
Minimized:
<syntaxhighlight lang="rockstar">
Listen to A number
Listen to B
Say A number plus B
</syntaxhighlight>
Idiomatic:
<syntaxhighlight lang="rockstar">
Listen to my voice
Listen to your thoughts
Shout your thoughts with my voice
</syntaxhighlight>
 
=={{header|RPL}}==
Related task is natively implemented in RPL.
+
 
2 2 +
2 3 +
{{out}}
<pre>
2: 4
1: 5
</pre>
 
=={{header|Ruby}}==
<syntaxhighlight lang="ruby">puts gets.split.sum(&:to_i)</syntaxhighlight>
 
=={{header|Run BASIC}}==
<syntaxhighlight lang="runbasic">input, x$
print val(word$(x$,1)) + val(word$(x$,2))</syntaxhighlight>
 
=={{header|Rust}}==
<langsyntaxhighlight lang="rust">use std::io;
 
fn main() {
Line 3,128 ⟶ 5,123:
}
println!("{}", i);
}</langsyntaxhighlight>
 
or
 
<langsyntaxhighlight lang="rust">use std::io;
 
fn main() {
Line 3,142 ⟶ 5,137:
.sum();
println!("{}", sum);
}</langsyntaxhighlight>
 
=={{header|S-lang}}==
<syntaxhighlight lang="c">% 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);</syntaxhighlight>
 
{{out}}
<pre>prompt$ echo "12 34" | slsh A+B.sl
46</pre>
 
<syntaxhighlight lang="c">% 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"$);
}</syntaxhighlight>
 
=={{header|Scala}}==
<langsyntaxhighlight lang="scala">println(readLine().split(" ").map(_.toInt).sum)</langsyntaxhighlight>
 
This will work if the input is exactly as specified, with no extra whitespace. A slightly more robust version:
 
<langsyntaxhighlight lang="scala">val s = new java.util.Scanner(System.in)
val sum = s.nextInt() + s.nextInt()
println(sum)</langsyntaxhighlight>
 
or
 
<langsyntaxhighlight lang="scala">println(readLine().split(" ").filter(_.length>0).map(_.toInt).sum)</langsyntaxhighlight>
 
=={{header|Scheme}}==
<langsyntaxhighlight lang="scheme">(display (+ (read) (read)))</langsyntaxhighlight>
 
=={{header|Scratch}}==
Scratch is a graphical programming language. Follow the link to see an example solution for A + B<br>
[https://scratch.mit.edu/projects/327678813/ '''Scratch A + B''']<br>
Since Scratch is an educational language, I've included comments in the code for new programmers to better understand what the program is doing.
 
=={{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.
<langsyntaxhighlight lang="sed">: Loop
# All done
/^-*00* /s///
Line 3,187 ⟶ 5,212:
# Decrement 2nd
s/\([^0]\)\(0*\);[^0]*\1\(.\).*\2\(9*\).*/\3\4/
t Loop</langsyntaxhighlight>
 
Another method, based off of [http://unix.stackexchange.com/a/36959/11750 this StackExchange answer]:
<langsyntaxhighlight lang="sed">#!/bin/sed -f
 
# Add a marker in front of each digit, for tracking tens, hundreds, etc.
Line 3,228 ⟶ 5,253:
s/</|/g
t back
s/^$/0/</langsyntaxhighlight>
 
=={{header|Seed7}}==
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
 
const proc: main is func
Line 3,241 ⟶ 5,266:
read(b);
writeln(a + b);
end func;</langsyntaxhighlight>
 
=={{header|Self}}==
Works with positive and negative integers, and also more than two integers.
 
<syntaxhighlight lang="self">((stdin readLine splitOn: ' ') mapBy: [|:e| e asInteger]) sum printLine.</syntaxhighlight>
 
=={{header|SenseTalk}}==
<syntaxhighlight lang="sensetalk">ask "Enter the first number:"
put it into a
 
ask "Enter the second number:"
put it into b
 
put a + b</syntaxhighlight>
<syntaxhighlight lang="sensetalk">put file "input.txt" into inputFile
split inputFile by space
put sum of inputFile</syntaxhighlight>
 
=={{header|SequenceL}}==
<langsyntaxhighlight lang="sequencel">import <Utilities/Conversion.sl>;
 
main(args(2)) := stringToInt(args[1]) + stringToInt(args[2]);</langsyntaxhighlight>
 
{{Out}}
Line 3,259 ⟶ 5,301:
 
=={{header|SETL}}==
<langsyntaxhighlight lang="setl">read(A, B);
print(A + B);</langsyntaxhighlight>
 
=={{header|Self}}==
Works with positive and negative integers, and also more than two integers.
 
<lang self>((stdin readLine splitOn: ' ') mapBy: [|:e| e asInteger]) sum printLine.</lang>
 
=={{header|Shiny}}==
<langsyntaxhighlight lang="shiny">if (io.line 'stdin').match ~(\d+)\s+(\d+)~
say "$a $b %(a+b)d"
end</langsyntaxhighlight>
 
=={{header|Sidef}}==
Works with both positive and negative integers.
<langsyntaxhighlight lang="ruby">say STDIN.readline.words.map{.to_i}.sum</langsyntaxhighlight>
 
More idiomatically:
<langsyntaxhighlight lang="ruby">say read(String).words»to_i»()»«+»</langsyntaxhighlight>
 
Explicit summation:
<langsyntaxhighlight lang="ruby">var (a, b) = read(String).words.map{.to_i}...
say a+b</langsyntaxhighlight>
 
=={{header|Simula}}==
<langsyntaxhighlight lang="simula">BEGIN
WHILE NOT LASTITEM DO
BEGIN
Line 3,290 ⟶ 5,328:
END;
END.
</syntaxhighlight>
</lang>
 
=={{header|SmileBASIC}}==
<lang smilebasic>INPUT A
INPUT B
PRINT A+B
</lang>
 
=={{header|SNOBOL4}}==
Simple-minded solution (literally "two somethings separated by space")
<lang snobol> input break(" ") . a " " rem . b
output = a + b
end</lang>
"Integer aware" solution:
<lang snobol> nums = "0123456789"
input span(nums) . a break(nums) span(nums) . b
output = a + b
end</lang>
 
=={{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.
<langsyntaxhighlight lang="smalltalk">'From Squeak3.7 of ''4 September 2004'' [latest update: #5989] on 8 August 2011 at 3:50:55 pm'!
Object subclass: #ABTask
instanceVariableNames: ''
Line 3,340 ⟶ 5,361:
test3Plus2
^ self
sum: (ReadStream on: '3 2')! !</langsyntaxhighlight>
 
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|VisualWorks Smalltalk}}
<langsyntaxhighlight lang="smalltalk">|task|
task := [:inStream :outStream |
|processLine|
Line 3,363 ⟶ 5,384:
].
 
task value: ( 'dataIn.txt' asFilename readStream) value:Transcript.</langsyntaxhighlight>
or:
<langsyntaxhighlight lang="smalltalk">task value: Stdin value: Stdout.</langsyntaxhighlight>
 
=={{header|smart BASIC}}==
<syntaxhighlight lang="qbasic">INPUT n$
-- [http://rosettacode.org/wiki/User:Sarossell Scott A. Rossell, 12-16-16]
PRINT VAL(LEFT$(n$,(LEN(STR$(VAL(n$))))))+VAL(RIGHT$(n$,(LEN(n$)-LEN(STR$(VAL(n$)))-1)))</syntaxhighlight>
<lang qbasic>INPUT n$
PRINT VAL(LEFT$(n$,(LEN(STR$(VAL(n$))))))+VAL(RIGHT$(n$,(LEN(n$)-LEN(STR$(VAL(n$)))-1)))</lang>
 
<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 3,378 ⟶ 5,398:
A FAR more elegant solution was provided by "Dutchman" on the smart [http://kibernetik.pro/forum/viewforum.php?f=2 BASIC Support Forum]:
 
<langsyntaxhighlight lang="qbasic">INPUT n$
SPLIT n$ TO m$,n WITH " "
PRINT m$(0),m$(1),m$(0)+m$(1)</langsyntaxhighlight>
 
<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}}==
<syntaxhighlight lang="smilebasic">INPUT A
INPUT B
PRINT A+B
</syntaxhighlight>
 
=={{header|SNOBOL4}}==
Simple-minded solution (literally "two somethings separated by space")
<syntaxhighlight lang="snobol"> input break(" ") . a " " rem . b
output = a + b
end</syntaxhighlight>
"Integer aware" solution:
<syntaxhighlight lang="snobol"> nums = "0123456789"
input span(nums) . a break(nums) span(nums) . b
output = a + b
end</syntaxhighlight>
 
=={{header|SPAD}}==
Line 3,389 ⟶ 5,426:
{{works with|Axiom}}
One of several possibilities:
<langsyntaxhighlight SPADlang="spad">(1) -> integer READ()$Lisp + integer READ()$Lisp
333 444
 
(1) 777
Type: PositiveInteger</langsyntaxhighlight>
 
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}}==
<langsyntaxhighlight Adalang="ada">-- By Jacob Sparre Andersen
-- Validates with SPARK GPL 2010's Examiner/Simplifier
 
Line 3,441 ⟶ 5,505:
Stop => 0);
end if;
end A_Plus_B;</langsyntaxhighlight>
 
=={{header|SPL}}==
<langsyntaxhighlight lang="spl">n = #.split(#.input("Input two numbers, separated by space:")," ")
#.output(n[1],"+",n[2],"=",#.val(n[1])+#.val(n[2]))</langsyntaxhighlight>
{{in}}
<pre>
Line 3,457 ⟶ 5,521:
 
=={{header|SQL}}==
<syntaxhighlight lang ="sql">select A+B</langsyntaxhighlight>
Example:
<syntaxhighlight lang ="sql">select 2+3</langsyntaxhighlight>
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).
 
=={{header|SQL PL}}==
{{works with|Db2 LUW}}
With SQL only:
<syntaxhighlight lang="sql pl">
 
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
</syntaxhighlight>
Output:
<pre>
VALUES DBA.SPLITADD(VARCHAR('1234 2345'))
1
----
3579
</pre>
 
=={{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>).
<langsyntaxhighlight lang="ssem">10100000000000100000000000000000 0. -5 to c acc = -A
01100000000001010000000000000000 1. Sub. 6 acc -= B
11100000000001100000000000000000 2. c to 7 X = acc
Line 3,473 ⟶ 5,564:
10100100000000000000000000000000 5. 37 A
00111000000000000000000000000000 6. 28 B
00000000000000000000000000000000 7. 0 X</langsyntaxhighlight>
 
=={{header|Standard ML}}==
<langsyntaxhighlight lang="sml">(*
* val split : string -> string list
* splits a string at it spaces
*)
val split = String.fieldstokens (fn #" " => true | _ => false)Char.isSpace
 
(*
* val removeNlsum : stringint list -> stringint
* removescomputes the occurencesum of "\n"a inlist aof stringnumbers
*)
val sum = foldl op+ 0
val removeNl = String.translate (fn #"\n" => "" | c => implode [c])
 
(*
Line 3,493 ⟶ 5,584:
*)
fun aplusb () =
let
val input = removeNl (valOf (TextIO.inputLine TextIO.stdIn))
in
foldl op+ 0 (mapsum (fno sList.mapPartial => valOf (Int.fromString s))o (split) input))
end</langsyntaxhighlight>
{{out}}
<pre>
Line 3,506 ⟶ 5,597:
 
=={{header|Swift}}==
{{works with|Swift|2}}
Requires sending EOF.
<langsyntaxhighlight Swiftlang="swift">import Foundation
 
let input = NSFileHandle.fileHandleWithStandardInput()
Line 3,518 ⟶ 5,610:
let b = (nums[1] as String).toInt()!
 
print(" \(a + b)")</langsyntaxhighlight>
 
{{works with|Swift|3}}
 
Swift 4 and no requirement to send EOF (press enter/send newline like you normally would)
 
<syntaxhighlight lang="swift">
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)")
</syntaxhighlight>
 
=={{header|Symsyn}}==
<syntaxhighlight lang="symsyn">
 
[] $s
getitem $s x
getitem $s y
+ x y
y []
 
</syntaxhighlight>
 
=={{header|Tailspin}}==
<syntaxhighlight lang="tailspin">
composer nums
[ (<WS>?) <INT> (<WS>) <INT> (<WS>?) ]
end nums
 
$IN::lines -> nums -> $(1) + $(2) -> '$;
' -> !OUT::write
</syntaxhighlight>
 
Alternatively
<syntaxhighlight lang="tailspin">
composer nums
(<WS>?) (def a: <INT>;) (<WS>) <INT> -> $a + $ (<WS>?)
end nums
 
$IN::lines -> nums -> '$;
' -> !OUT::write
</syntaxhighlight>
 
=={{header|Tcl}}==
<langsyntaxhighlight lang="tcl">scan [gets stdin] "%d %d" x y
puts [expr {$x + $y}]</langsyntaxhighlight>
Alternatively:
<langsyntaxhighlight lang="tcl">puts [tcl::mathop::+ {*}[gets stdin]]</langsyntaxhighlight>
To/from a file:
<langsyntaxhighlight lang="tcl">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</langsyntaxhighlight>
 
=={{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}}==
<langsyntaxhighlight lang="ti83b">:Prompt A,B
:Disp A+B</langsyntaxhighlight>
 
=={{header|TI-83 Hex Assembly}}==
Line 3,541 ⟶ 5,718:
Note: Comments (after the semicolons) are just for explanation -- TI-83 hex assembly does not allow comments in program source code.
 
<langsyntaxhighlight lang="ti83b">PROGRAM:APLUSB
:AsmPrgm
:
Line 3,557 ⟶ 5,734:
:F7 ; rst FPAdd
:EFBF4A ; StoAns
:C9 ; ret</langsyntaxhighlight>
 
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}}==
<langsyntaxhighlight lang="ti89b">:aplusb(a,b)
:a+b</langsyntaxhighlight>
 
=={{header|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.
<langsyntaxhighlight Torquelang="torque">Function aPlusB(%input)
{
return getWord(%input, 0) + getWord(%input, 1);
}</langsyntaxhighlight>
 
=={{header|Transd}}==
<syntaxhighlight lang="scheme">#lang transd
 
MainModule : {
a: Int(),
b: Int(),
_start: (lambda (textout (+ (read a) (read b))))
}</syntaxhighlight>
 
=={{header|TSE SAL}}==
<syntaxhighlight lang="tsesal">
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
</syntaxhighlight>
{{out}} <pre>
output
5
</pre>
 
=={{header|TUSCRIPT}}==
<langsyntaxhighlight lang="tuscript">$$ MODE TUSCRIPT
SET input="1 2"
SET input=SPLIT(input,": :")
SET input=JOIN (input)
SET output=SUM(input)</langsyntaxhighlight>
 
=={{header|TXR}}==
Line 3,595 ⟶ 5,800:
=={{header|UNIX Shell}}==
{{works with|Bourne Shell}}
<langsyntaxhighlight lang="sh">#!/bin/sh
read a b || exit
echo `expr "$a" + "$b"`</langsyntaxhighlight>
 
{{works with|bash}}
Line 3,604 ⟶ 5,809:
{{works with|zsh}}
Script "a+b.sh":
<langsyntaxhighlight lang="bash">#!/bin/bash
read a b || exit
echo $(( a + b ))</langsyntaxhighlight>
{{Out}}
<langsyntaxhighlight lang="bash">echo 2 3 | ksh a+b.sh
5</langsyntaxhighlight>
 
One liner :
 
<syntaxhighlight lang="bash">
a=0;b=0;read a;read b;echo "Sum of $a and $b is "$((a+b))
</syntaxhighlight>
Sample run :
<pre>
3
4
Sum of 3 and 4 is 7
</pre>
 
==={{header|C Shell}}===
<langsyntaxhighlight lang="csh">set line=$<
set input=($line)
@ sum = $input[1] + $input[2]
echo $sum</langsyntaxhighlight>
 
=={{header|Ursa}}==
<syntaxhighlight lang="text">#
# a + b
#
Line 3,632 ⟶ 5,849:
 
# output the sum
out sum endl console</langsyntaxhighlight>
 
=={{header|Ultimate++}}==
 
<syntaxhighlight lang="cpp">
#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++) {
}
}
 
 
</syntaxhighlight>
 
 
=={{header|Ursala}}==
Using standard input and output streams:
<langsyntaxhighlight Ursalalang="ursala">#import std
#import int
 
#executable&
 
main = %zP+ sum:-0+ %zp*FiNCS+ sep` @L</langsyntaxhighlight>
Overwriting a text file named as a command line parameter:
<langsyntaxhighlight Ursalalang="ursala">#import std
#import int
 
#executable -[parameterized]-
 
main = ~command.files.&h; <.contents:= %zP+ sum:-0+ %zp*FiNCS+ sep` @L+ ~contents></langsyntaxhighlight>
Creating a new file named after the input file with suffix <code>.out</code>:
<langsyntaxhighlight Ursalalang="ursala">#import std
#import int
 
Line 3,659 ⟶ 5,902:
~command.files.&h; ~&iNC+ file$[
contents: %zP+ sum:-0+ %zp*FiNCS+ sep` @L+ ~contents,
path: ~path; ^|C\~& ~=`.-~; ^|T/~& '.out'!]</langsyntaxhighlight>
 
=={{header|Vala}}==
Read from stdin while program running:
<langsyntaxhighlight lang="vala">Using GLib;
 
int main (string[] args) {
Line 3,673 ⟶ 5,916:
return 0;
}
</syntaxhighlight>
</lang>
 
=={{header|VBA}}==
A simple version:
 
<langsyntaxhighlight VBAlang="vba">Sub Rosetta_ABAplusB()
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</syntaxhighlight>
An other version:
<syntaxhighlight lang="vba">Sub Rosetta_AB()
Dim stEval As String
stEval = InputBox("Enter two numbers, separated only by a space", "Rosetta Code", "2 2")
Line 3,683 ⟶ 5,935:
"VBA converted this input to " & Replace(stEval, " ", "+") & vbCr & vbCr & _
"And evaluated the result as " & Evaluate(Replace(stEval, " ", "+")), vbInformation + vbOKOnly, "XLSM"
End Sub</langsyntaxhighlight>
 
=={{header|VBScript}}==
A simple version:
<lang vb>Option Explicit
<syntaxhighlight lang="vb">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 </syntaxhighlight>
An other version:
<syntaxhighlight lang="vb">Option Explicit
Dim a, b
Select Case WScript.Arguments.Count
Line 3,722 ⟶ 5,982:
.Close
End With
end if</langsyntaxhighlight>
 
=={{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}}==
<langsyntaxhighlight Veriloglang="verilog">module TEST;
 
reg signed [11:0] y;
Line 3,743 ⟶ 6,024:
endfunction
endmodule</langsyntaxhighlight>
 
=={{header|VHDL}}==
<langsyntaxhighlight VHDLlang="vhdl">LIBRARY std;
USE std.TEXTIO.all;
 
Line 3,768 ⟶ 6,049:
wait; -- needed to stop the execution
end process;
end architecture beh;</langsyntaxhighlight>
 
=={{header|Visual Basic .NET}}==
<langsyntaxhighlight lang="vbnet">Module Module1
 
Sub Main()
Line 3,780 ⟶ 6,061:
End Sub
 
End Module</langsyntaxhighlight>
 
=={{header|V (Vlang)}}==
<syntaxhighlight lang="go">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}')
}</syntaxhighlight>
Read from stdin
{{out}}
<pre>
Input Output
2 2 2 + 2 = 4
3 2 3 + 2 = 5
</pre>
 
=={{header|Wee Basic}}==
<syntaxhighlight lang="wee basic">Print 1 "Enter number A:"
input a
Print 1 "Enter number B:"
input b
let c=a+b
print 1 c
end</syntaxhighlight>
 
=={{header|Whitespace}}==
<langsyntaxhighlight lang="whitespace">
Line 3,795 ⟶ 6,109:
 
 
</syntaxhighlight>
</lang>
 
=={{header|Wisp}}==
{{trans|Scheme}}
<syntaxhighlight lang="scheme">
display : + (read) (read)
 
 
314
315
;; displays 629
</syntaxhighlight>
 
=={{header|Wren}}==
<langsyntaxhighlight lang="wren">import "io" for Stdin, Stdout
 
var a = Num.fromString(Stdin.readLine())
while (true) {
var b = Num.fromString(Stdin.readLine())
System.write("Enter two integers separated by a space : ")
System.print(a + b)
Stdout.flush()
</lang>
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
}
}</syntaxhighlight>
 
{{out}}
Sample input/output:
<pre>
Enter two integers separated by a space : 12 16
Their sum is 28
</pre>
 
=={{header|X86 Assembly}}==
{{works with|NASM|Linux}}
<langsyntaxhighlight lang="asm">section .text
global _start
Line 3,865 ⟶ 6,207:
a resd 1
b resd 1
sum resd 1</langsyntaxhighlight>
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}}==
Since XBS is written in Javascript, we have to use the Javascript prompt function to get inputs.
<syntaxhighlight lang="xbs">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);</syntaxhighlight>
{{out}}
If we input an amount of "2", then input "1" and "2", the output will be "3".
<pre>
3
</pre>
 
=={{header|xEec}}==
<langsyntaxhighlight xEeclang="xeec">i# i# ma h#10 r o# p o$ p</langsyntaxhighlight>
 
=={{header|XLISP}}==
<langsyntaxhighlight lang="xlisp">(DEFUN A-PLUS-B ()
(DISPLAY "Enter two numbers separated by a space.")
(NEWLINE)
Line 3,878 ⟶ 6,236:
(DEFINE A (READ))
(DEFINE B (READ))
(+ A B))</langsyntaxhighlight>
{{out}}
<pre>(A-PLUS-B)
Line 3,885 ⟶ 6,243:
 
4</pre>
 
=={{header|Xojo}}==
<syntaxhighlight lang="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
</syntaxhighlight>
 
=={{header|XPL0}}==
<langsyntaxhighlight XPL0lang="xpl0">include c:\cxpl\codes;
int A, B;
[A:= IntIn(0);
Line 3,893 ⟶ 6,280:
IntOut(0, A+B);
CrLf(0);
]</langsyntaxhighlight>
 
=={{header|XQuery}}==
<syntaxhighlight lang="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))
</syntaxhighlight>
 
=={{header|Yabasic}}==
<syntaxhighlight lang="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</syntaxhighlight>
 
=={{header|Yorick}}==
<langsyntaxhighlight lang="yorick">a = b = 0;
read, a, b;
write, a + b;</langsyntaxhighlight>
 
=={{header|ZED}}==
Source -> http://ideone.com/WLtEfe
Compiled -> http://ideone.com/fMt6ST
<langsyntaxhighlight lang="zed">(A+B)
comment:
#true
Line 3,916 ⟶ 6,332:
comment:
#true
(001) "read"</langsyntaxhighlight>
 
=={{header|Zig}}==
<syntaxhighlight lang="zig">
const std = @import("std");
const stdout = std.io.getStdOut().writer();
 
const Input = enum { a, b };
 
pub fn main() !void {
var buf: [1024]u8 = undefined;
const reader = std.io.getStdIn().reader();
const input = try reader.readUntilDelimiter(&buf, '\n');
const values = std.mem.trim(u8, input, "\x20");
 
var count: usize = 0;
var split: usize = 0;
for (values, 0..) |c, i| {
if (!std.ascii.isDigit(c)) {
count += 1;
if (count == 1) split = i;
}
}
 
const a = try std.fmt.parseInt(u64, values[0..split], 10);
const b = try std.fmt.parseInt(u64, values[split + count ..], 10);
 
try stdout.print("{d}\n", .{a + b});
}
</syntaxhighlight>
{{out}}
<pre>
1 2
3
 
3 6
9
</pre>
 
=={{header|zkl}}==
<langsyntaxhighlight lang="zkl">do(2){ask("A B: ").split(" ").filter().sum().println()}</langsyntaxhighlight>
<pre>
A B: 123 567
Line 3,927 ⟶ 6,380:
</pre>
This actually works for any number of integers
 
=={{header|Zoea}}==
<syntaxhighlight lang="zoea">program: a_plus_b
input: '7 11'
output: 18
</syntaxhighlight>
 
=={{header|Zoea Visual}}==
[http://zoea.co.uk/examples/zv-rc/A_plus_b.png A+B]
 
=={{header|zonnon}}==
<syntaxhighlight lang="zonnon">
module ABProblem;
var
a,b: integer;
begin
read(a,b);
writeln(a+b)
end ABProblem.
</syntaxhighlight>
<pre>
1 2
3
</pre>
 
=={{header|ZX Spectrum Basic}}==
<langsyntaxhighlight lang="zxbasic">10 PRINT "Input two numbers separated by"'"space(s) "
20 INPUT LINE a$
30 GO SUB 90
Line 3,938 ⟶ 6,415:
80 REM LTrim operation
90 IF a$(1)=" " THEN LET a$=a$(2 TO ): GO TO 90
100 RETURN</langsyntaxhighlight>
 
Another solution
 
<syntaxhighlight lang="zxbasic">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</syntaxhighlight>
 
<pre>
Line 3,945 ⟶ 6,434:
3.14 2^3
3.14 + 8 = 11.14
</pre>
 
=={{header|zonnon}}==
<lang zonnon>
module ABProblem;
var
a,b: integer;
begin
read(a,b);
writeln(a+b)
end ABProblem.
</lang>
<pre>
1 2
3
</pre>
22

edits