A+B

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

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


Task

Given two integer,   A and B.

Their sum needs to be calculated.


Input data

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


Output data

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


Example
Input Output
2 2 4
3 2 5



Contents

0815[edit]

|x|+%

360 Assembly[edit]

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

8th[edit]

parseln eval n:+ . cr

ABAP[edit]

report z_sum_a_b.
data: lv_output type i.
selection-screen begin of block input.
parameters:
p_first type i,
p_second type i.
selection-screen end of block input.
 
at selection-screen output.
%_p_first_%_app_%-text = 'First Number: '.
%_p_second_%_app_%-text = 'Second Number: '.
 
start-of-selection.
lv_output = p_first + p_second.
write : / lv_output.

Ada[edit]

-- Standard I/O Streams
 
with Ada.Integer_Text_Io;
procedure APlusB is
A, B : Integer;
begin
Ada.Integer_Text_Io.Get (Item => A);
Ada.Integer_Text_Io.Get (Item => B);
Ada.Integer_Text_Io.Put (A+B);
end APlusB;

Using appropriate user defined types:

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

Aime[edit]

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

ALGOL 68[edit]

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

Console[edit]

print((read int + read int))

Input:

1 2
Output:
         +3

File[edit]

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

Input "input.txt":

3 4

Output "output.txt":

         +7

ALGOL W[edit]

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

ANTLR[edit]

aplusb
aplusb


Apex[edit]

 
 
static Integer sumOfTwoNums(Integer A, Integer B) {
return A + B;
}
 
System.debug('A = 50 and B = 25: ' + sumOfTwoNums(50, 25));
System.debug('A = -50 and B = 25: ' +sumOfTwoNums(-50, 25));
System.debug('A = -50 and B = -25: ' +sumOfTwoNums(-50, -25));
System.debug('A = 50 and B = -25: ' +sumOfTwoNums(50, -25));
 
'''Output'''
A = 50 and B = 25: 75
A = -50 and B = 25: -25
A = -50 and B = -25: -75
A = 50 and B = -25: 25
 
 

AppleScript[edit]

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

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

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

Result: 75

Arc[edit]

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

Argile[edit]

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

ARM Assembly[edit]

Works with: gcc version Linux

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

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

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

as -o ab.o ab.S
ld -o a.out ab.o
.data
.align 2
.code 32
 
.section .rodata
.align 2
.code 32
 
overflow_msg: .ascii "Invalid number. Overflow.\n"
overflow_msglen = . - overflow_msg
bad_input_msg: .ascii "Invalid input. NaN.\n"
bad_input_msglen = . - bad_input_msg
range_err_msg: .ascii "Value out of range.\n"
range_err_msglen = . - range_err_msg
io_error_msg: .ascii "I/O error.\n"
io_error_msglen = . - range_err_msg
 
sys_exit = 1
sys_read = 3
sys_write = 4
max_rd_buf = 14
lf = 10
m10_9 = 0x3b9aca00
maxval = 1000
minval = -1000
 
.text
 
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@ void main()
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
.align 2
.code 32
.type _start STT_FUNC
.global _start
_start:
stmfd sp!, {r4,r5,lr}
 
.read_lhs:
ldr r0, =max_rd_buf
bl readint
mov r4, r0
bl printint
mov r0, r4
bl range_check
 
.read_rhs:
ldr r0, =max_rd_buf
bl readint
mov r5, r0
bl printint
mov r0, r5
bl range_check
 
.sum_and_print:
adds r0, r4, r5
bvs overflow
bl printint
 
.main_exit:
mov r0, #0
bl exit
ldmfd sp!, {r4,r5,pc}
 
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@ Read from stdin until we encounter a non-digit, or we have read bytes2rd digits.
@@ Ignore leading spaces.
@@ Return value to the caller converted to a signed int.
@@ We read positive values, but if we read a leading '-' sign, we convert the
@@ return value to two's complement.
@@ The argument is max number of bytes to read from stdin.
@@ int readint(int bytes2rd)
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
.align 2
.code 32
.type readint STT_FUNC
.global readint
readint:
stmfd sp!, {r4,r5,r6,r7,lr}
@@@@@@@@@@@@@@@
@@ r0 : #0 for stdin arg to read.
@@ r1 : ptr to current pos in local buffer.
@@ r2 : #1 to read one byte at a time.
@@ r3,r7 : tmp.
@@ r4 : number of bytes read.
@@ r5 : value of current byte.
@@ r6 : 0 while we are reading leading spaces.
@@@@@@@@@@@@@@@
sub sp, sp, r0
mov r1, sp
mov r3, #0
push {r3} @ sp,#4: local var @isnegative. return in r1. Default value is 0/false. Positive number.
push {r0} @ sp,#0: local var @maxbytes. const.
mov r2, #1
mov r4, #0
 
mov r6, #0
b .rd
@ we get here if r6 is 0.
@ if space, goto .rd.
@ else set r6 to 1 and goto .noleading.
.leadchk:
mov r0, r5
bl isspace
cmp r0, #1
beq .rd
 
.sign_chk:
mov r0, r5
push {r1}
bl issign
cmp r0, #1
streq r0, [sp,#8] @ sp,#4 + 4 for the pushed r1.
movhi r1, #0
strhi r1, [sp,#8] @ sp,#4 + 4 for the pushed r1.
pop {r1}
bhs .rd
 
mov r6, #1
b .noleading
 
.rd:
mov r0, #0
bl read
cmp r0, #1
bne .sum_digits_eof @ eof
mov r5, #0
ldrb r5, [r1]
cmp r6, #0
beq .leadchk
 
.noleading:
mov r0, r5
bl isdigit
cmp r0, #1
bne .sum_digits_nan @ r5 is non-digit
 
add r4, r4, #1
add r1, r1, #1
@ max chars to read is received in arg[0], stored in local var at sp.
@ Only 10 can be valid, so the default of 12 leaves space for separator.
ldr r3, [sp]
cmp r4, r3
beq .sum_digits_maxrd @ max bytes read.
b .rd
 
 
@@@@@@@@@@@@@@@
@ We have read r4 (0..arg[0](default 12)) digits when we get here. Go through them
@ and add/mul them together to calculate a number.
@ We multiply and add the digits in reverse order to simplify the multiplication.
@@@@@@@@@@@@@@@
@ r0: return value.
@ r1: local variable for read buffer.
@ r2: tmp for conversion.
@ r3,r6,r7: tmp
@ r4: number of chars we have read.
@ r5: multiplier 1,10,100.
@@@@@@@@@@@@@@@
.sum_digits_nan:
mov r0, r5
bl isspace
cmp r0, #1
bne bad_input
.sum_digits_maxrd:
.sum_digits_eof:
mov r0, #0
mov r5, #1
.count:
cmp r4, #0
beq .readint_ret
sub r4, r4, #1
sub r1, #1
ldrb r2, [r1]
sub r2, r2, #48
mov r3, r2
 
@ multiply r3 (char value of digit) with r5 (multiplier).
@ possible overflow.
@ MI means negative.
@ smulls multiples two signed 32 bit vals and returns a 64 bit result.
@ If we get anything in r7, the value has overflowed.
@ having r2[31] set is overflow too.
smulls r2, r7, r3, r5
cmp r7, #0
bne overflow
cmp r2, #0
bmi overflow
 
@@ possible overflow.
adds r0, r0, r2
bvs overflow
bmi overflow
 
@@ end of array check.
@@ check is needed here too, for large numbers, since 10 billion is not a valid 32 bit val.
cmp r4, #0
beq .readint_ret
 
@@ multiple multiplier by 10.
@@ possible overflow.
@@ too many digits is input. happens if input is more than 10 digits.
mov r3, #10
mov r6, r5
smulls r5, r7, r3, r6
cmp r7, #0
bne overflow
cmp r5, #0
bmi overflow
b .count
 
.readint_ret:
ldr r1, [sp,#4] @ read isnegative value.
cmp r1, #0
rsbne r0, r0, #0
pop {r2}
add sp, sp, #4
add sp, sp, r2
ldmfd sp!, {r4,r5,r6,r7,pc}
 
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@ int isdigit(int)
@@ #48..#57 ascii range for '0'..'9'.
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
.align 2
.code 32
.type isdigit STT_FUNC
.global isdigit
isdigit:
stmfd sp!, {r1,lr}
cmp r0, #48
blo .o_range
cmp r0, #57
bhi .o_range
mov r0, #1
ldmfd sp!, {r1,pc}
.o_range:
mov r0, #0
ldmfd sp!, {r1,pc}
 
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@ int isspace(int)
@@ ascii space = 32, tab = 9, newline 10, cr = 13.
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
.align 2
.code 32
.type isspace STT_FUNC
.global isspace
isspace:
stmfd sp!, {lr}
cmp r0, #32
cmpne r0, #9
cmpne r0, #10
cmpne r0, #13
beq .is_space
mov r0, #0
ldmfd sp!, {pc}
.is_space:
mov r0, #1
ldmfd sp!, {pc}
 
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@ Return value is 1 for '-' 2 for '+'.
@@ int isspace(int)
@@ '+' = 43 and '-' = 45.
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
.align 2
.code 32
.type issign STT_FUNC
.global issign
issign:
stmfd sp!, {lr}
cmp r0, #43
beq .plus_sign
cmp r0, #45
beq .minus_sign
mov r0, #0
ldmfd sp!, {pc}
.plus_sign:
mov r0, #2
ldmfd sp!, {pc}
.minus_sign:
mov r0, #1
ldmfd sp!, {pc}
 
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@ ARGS:
@@ r0 : in out arg (current int value)
@@ r1 : in out arg (ptr to current pos in buffer)
@@ r2 : in arg (const increment. 1000_000_000, 100_000_000, 10_000_000, 1000_000, 100_000, 10_000, 1000, 100, 10, 1.)
@@
@@ r4 : tmp local. Outer scope must init to #10 and count down to #0.
@@ Special case is INTMAX. Must init to 5 if r4 >= 1000_000_000 (0x3b9aca00 = m10_9).
@@ r5: tmp
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
.align 2
.code 32
.type get_digit STT_FUNC
.global get_digit
get_digit:
stmfd sp!, {r2,r4,r5,lr}
ldr r5, =m10_9
cmp r2, r5
movlo r4, #10
movhs r4, #5
.get_digit_loop:
sub r4, #1
mul r5, r4, r2
cmp r0, r5
blo .get_digit_loop
sub r0, r5
add r4, r4, #48
strb r4, [r1], #1
ldmfd sp!, {r2,r4,r5,pc}
 
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@ A quick way to divide (numbers evenly divisible by 10) by 10.
@@ Most ARM cpus don't have a divide instruction,
@@ so this will always work.
@@ A generic div function is long and not needed here.
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
.align 2
.div_r2_10:
stmfd sp!, {r0,r1,r3,lr}
mov r0, #1
mov r1, #10
.find_x:
mul r3, r0, r1;
cmp r3, r2
movlo r0, r3
blo .find_x
mov r2, r0
ldmfd sp!, {r0,r1,r3,pc}
 
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
.align 2
.print_neg_sign:
stmfd sp!, {r0,r1,r2,lr}
@ 45 = '-'
mov r1, #45
push {r1}
mov r2, #1
@ r1 is ptr to our local variable (holding '-').
mov r1, sp
mov r0, #1
bl write
cmp r0, #0
blne io_error
pop {r1}
ldmfd sp!, {r0,r1,r2,pc}
 
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@ void printint(int val)
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
.align 2
.code 32
.type printint STT_FUNC
.global printint
printint:
stmfd sp!, {r4,r5,r6,lr}
mov r1, #1
ands r1, r1, r0, LSR #31
rsbne r0, r0, #0
blne .print_neg_sign
sub sp, sp, #20
mov r1, sp
mov r3, sp
 
ldr r2, =m10_9
.getc_loop:
bl get_digit
cmp r2, #1
beq .exit_getc_loop
bl .div_r2_10
b .getc_loop
.exit_getc_loop:
ldr r0, =lf
strb r0, [r1], #1
 
sub r2, r1, r3
mov r1, r3
mov r0, #1
bl write
cmp r0, #0
blne io_error
add sp, sp, #20
ldmfd sp!, {r4,r5,r6,pc}
 
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
.align 2
range_check:
stmfd sp!, {r4,r5,lr}
ldr r4, =minval
ldr r5, =maxval
cmp r4, #0
cmpeq r5, #0
beq .skip_range_check
cmp r0, r4
bllt range_err
cmp r0, r5
blgt range_err
.skip_range_check:
ldmfd sp!, {r4,r5,pc}
 
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@ void range_err()
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
.align 2
range_err:
stmfd sp!, {lr}
ldr r2, =range_err_msglen
ldr r1, =range_err_msg
mov r0, #2
bl write
mov r0, #-1
bl exit
ldmfd sp!, {pc}
 
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@ void overflow()
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
.align 2
overflow:
stmfd sp!, {lr}
ldr r2, =overflow_msglen
ldr r1, =overflow_msg
mov r0, #2
bl write
mov r0, #-1
bl exit
ldmfd sp!, { pc}
 
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@ void bad_input()
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
.align 2
bad_input:
stmfd sp!, {lr}
ldr r2, =bad_input_msglen
ldr r1, =bad_input_msg
mov r0, #2
bl write
mov r0, #-1
bl exit
ldmfd sp!, {pc}
 
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@ void io_error()
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
.align 2
io_error:
stmfd sp!, {lr}
ldr r2, =io_error_msglen
ldr r1, =io_error_msg
mov r0, #2
bl write
mov r0, #-1
bl exit
ldmfd sp!, {pc}
 
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@ void exit(int)
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
.align 2
.code 32
.type _start STT_FUNC
.global exit
exit:
stmfd sp!, {r7, lr}
ldr r7, =sys_exit
svc #0
ldmfd sp!, {r7, pc}
 
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@ int write(int fd,char*buf,int len)
@ Return 0 if we successfully write all bytes. Otherwise return the error code.
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
.align 2
.code 32
.type _start STT_FUNC
.global write
write:
stmfd sp!, {r4,r7, lr}
mov r4, r2
.wr_loop:
ldr r7, =sys_write
svc #0
@ If r0 is negative, it is more than r4 with LO (unsigned <).
cmp r0, r4
sublo r4, r0
blo .wr_loop
moveq r0, #0
ldmfd sp!, {r4,r7, pc}
 
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@ int read(int fd,char*buf,int len)
@ Return number of bytes successfully read. Ignore errors.
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
.align 2
.code 32
.type _start STT_FUNC
.global read
read:
stmfd sp!, {r7, lr}
ldr r7, =sys_read
svc #0
cmp r0, #0
movlt r0, #0
ldmfd sp!, {r7, pc}
 

ATS[edit]

 
(* ****** ****** *)
//
#include
"share/atspre_staload.hats"
//
staload UN = $UNSAFE
//
(* ****** ****** *)
 
staload "libc/SATS/stdio.sats"
 
(* ****** ****** *)
 
implement
main0() = let
var A: int
var B: int
val () =
$extfcall
(void, "scanf", "%d%d", [email protected], [email protected])
// end of [val]
in
println! ($UN.cast2int(A) + $UN.cast2int(B))
end // end of [main0]
 
(* ****** ****** *)
 

AutoHotkey[edit]

InputBox, input , A+B, Two integer numbers`, separated by space.
StringSplit, output, input, %A_Space%
msgbox, % output1 . "+" . output2 "=" output1+output2

AutoIt[edit]

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

AWK[edit]

{print $1 + $2}

Batch File[edit]

Prompts version

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

All on the commandline version

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

Formula on the command line version

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

Example of 'Formula on the command line version'

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

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

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

Example of 'parse the input stream version'

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

BASIC[edit]

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

Applesoft BASIC[edit]

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

BASIC256[edit]

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

BBC BASIC[edit]

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

That seems overly complicated. What's wrong with:

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

bc[edit]

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

Befunge[edit]

&&+.@

Bracmat[edit]

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

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

Brainf***[edit]

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

Brat[edit]

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

Burlesque[edit]

ps++

C[edit]

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

C#[edit]

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

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

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

C++[edit]

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

Ceylon[edit]

shared void run() {
while(true) {
print("please enter two numbers for me to add");
value input = process.readLine();
if(exists input) {
value tokens = input.split();
value numbers = tokens.map(parseInteger);
if(numbers.any((Integer? element) => element is Null)) {
print("numbers only, please");
} else if(numbers.size != 2) {
print("two numbers, please");
} else if(!numbers.coalesced.every((Integer element) => -1k <= element <= 1k)) {
print("only numbers between -1000 and 1000, please");
} else if(exists a = numbers.first, exists b = numbers.last) {
print(a + b);
} else {
print("something went wrong");
}
} else {
break;
}
}
}

Clojure[edit]

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

Translation of Common Lisp version:

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


Safely and without reader tricks:

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

or same as above, but without "let":

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

COBOL[edit]

       IDENTIFICATION DIVISION.
PROGRAM-ID. A-Plus-B.
 
DATA DIVISION.
WORKING-STORAGE SECTION.
01 A PIC S9(5).
01 B PIC S9(5).
 
01 A-B-Sum PIC S9(5).
 
PROCEDURE DIVISION.
ACCEPT A
ACCEPT B
 
ADD A TO B GIVING A-B-Sum
 
DISPLAY A-B-Sum
 
GOBACK
.

CoffeeScript[edit]

Translation of: JavaScript
<html>
<script type="text/javascript" src="http://jashkenas.github.com/coffee-script/extras/coffee-script.js"></script>
<script type="text/coffeescript">
a = window.prompt 'enter A number', ''
b = window.prompt 'enter B number', ''
document.getElementById('input').innerHTML = a + ' ' + b
sum = parseInt(a) + parseInt(b)
document.getElementById('output').innerHTML = sum
</script>
<body>
<div id='input'></div>
<div id='output'></div>
</body>
</html>
Works with: Node.js
 
{ stdin } = process
sum = ( a, b ) -> a + b
 
display = ( messages... ) -> console.log messages...
 
parse = ( input ) ->
parseInt x for x in ( x.trim() for x in input.split ' ' ) when x?.length
 
check = ( numbers... ) ->
return no for x in numbers when isNaN x
return no for x in numbers when not ( -1000 < x < 1000 )
yes
 
prompt = ->
display 'Please enter two integers between -1000 and 1000, separated by a space:'
stdin.once 'data', ( data ) ->
[ a, b ] = parse data
if check a, b
display "#{ a } + #{ b } = #{ sum a, b }"
else
display "Invalid input: #{ a }, #{ b }"
do prompt
return
 
# Resume input and set the incoming encoding.
stdin.resume()
stdin.setEncoding 'utf8'
 
# Start the main loop.
do prompt
 

Common Lisp[edit]

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

Component Pascal[edit]

BlackBox Component Builder

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

Execute: AB.Go 12 23 ~

Output:
12 23 35

Crystal[edit]

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

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

To handle the nil case we could do:

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

D[edit]

From Console[edit]

import std.stdio, std.conv, std.string;
 
void main() {
string[] r;
try
r = readln().split();
catch (StdioException e)
r = ["10", "20"];
 
writeln(to!int(r[0]) + to!int(r[1]));
}
Output:
30

From File[edit]

void main() {
import std.stdio, std.file;
 
immutable ab = "sum_input.txt".slurp!(int, int)("%d %d")[0];
"sum_output.txt".File("w").writeln(ab[0] + ab[1]);
}

Dart[edit]

import 'dart:io';
 
// a little helper function that checks if the string only contains
// digits and an optional minus sign at the front
bool isAnInteger(String str) => str.contains(new RegExp(r'^-?\d+$'));
 
void main() {
while(true) {
String input = stdin.readLineSync();
var chunks = input.split(new RegExp(r'[ ]+')); // split on 1 or more spaces
if(!chunks.every(isAnInteger)) {
print("not an integer!");
} else if(chunks.length > 2) {
print("too many numbers!");
} else if(chunks.length < 2) {
print('not enough numbers!');
} else {
// parse the strings into integers
var nums = chunks.map((String s) => int.parse(s));
if(nums.any((num) => num < -1000 || num > 1000)) {
print("between -1000 and 1000 please!");
} else {
print(nums.reduce((a, b) => a + b));
}
}
}
}
 
Output:
1 2
3
3 4
7

dc[edit]

? + psz

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

DCL[edit]

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

Déjà Vu[edit]

Translation of: Python

Console[edit]

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

Delphi[edit]

Console version.

program SUM;
 
{$APPTYPE CONSOLE}
 
uses
SysUtils;
 
procedure
var
s1, s2:string;
begin
ReadLn(s1);
Readln(s2);
Writeln(StrToIntDef(s1, 0) + StrToIntDef(s2,0));
end.

DMS[edit]

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" )

DWScript[edit]

Ghetto GUI version

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

EchoLisp[edit]

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

Eiffel[edit]

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

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

Alternatively ...

 
make
-- Run application.
note
synopsis: "[
The specification implies command line input stream and also
implies a range for both `A' and `B' (e.g. (-1000 <= A,B <= +1000)).
To test in Eiffel Studio workbench, one can set Execution Parameters
of "
2 2", where the expected output is 4. One may also create other
test Execution Parameters where the inputs are out-of-bounds and
confirm the failure.
]"

do
if attached {INTEGER} argument (1).to_integer as a and then
attached {INTEGER} argument (2).to_integer as b and then
(a >= -1000 and b >= -1000 and a <= 1000 and b <= 1000) then
print (a + b)
else
print ("Either argument 1 or 2 is out-of-bounds. Ensure: (-1000 <= A,B <= +1000)")
end
end
 

Ela[edit]

open monad io string list
 
a'b() = do
str <- readStr
putStrLn <| show <| sum <| map gread <| string.split " " <| str
 
a'b() ::: IO
Output:
1 2 3 4 5 6
21

Elena[edit]

#import system.
#import extensions.
 
#symbol program =
[
#var A := Integer new.
#var B := Integer new.
 
console readLine:A:B writeLine:(A + B).
].
 

Elixir[edit]

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

Erlang[edit]

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

ERRE[edit]

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

Euler Math Toolbox[edit]

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

Euphoria[edit]

include get.e
 
function snd(sequence s)
return s[2]
end function
 
integer a,b
 
a = snd(get(0))
b = snd(get(0))
 
printf(1," %d\n",a+b)

EGL[edit]

 
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
 

Excel[edit]

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

 
=A1+B1
 

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

1	2	3
 

F#[edit]

open System
let plus = (fun (a:string) (b:string) -> Console.WriteLine(int(a)+int(b))) (Console.ReadLine()) (Console.ReadLine());;

Factor[edit]

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

FALSE[edit]

[0[^$$'9>'0@>|~]['0-\10*+]#%]n:  {read an integer}
n;!n;!+.

Fantom[edit]

class APlusB
{
public static Void main ()
{
echo ("Enter two numbers: ")
Str input := Env.cur.in.readLine
Int sum := 0
input.split.each |n| { sum += n.toInt }
echo (sum)
}
}

FBSL[edit]

Using stdin and stdout

#APPTYPE CONSOLE
 
DIM %a, %b
SCANF("%d%d", @a, @b)
PRINT a, "+", b, "=", a + b
 
PAUSE

Fish[edit]

i:o:"-"=?v1$68*-v
v >~01-0 >
>i:o:" "=?v68*-$a*+
>~*i:o:"-"=?v1$68*-v
v >~01-0 >
>i:o:d=?v68*-$a*+
>~*+aonao;

Forth[edit]

pad dup 80 accept evaluate + .

Fortran[edit]

program a_plus_b
implicit none
integer :: a,b
read (*, *) a, b
write (*, '(i0)') a + b
end program a_plus_b

Frink[edit]

This program handles arbitrarily-large integers, or even floating-point or rational numbers or complex numbers (as long as they're not internally separated with spaces, of course, which are the delimiters for this task.) It can even handle units of measure (with no embedded spaces) such as "3.3meter 2feet" and does the right thing when summing those units. It can handle any number of arbitrary whitespace characters separating the numbers. It also works whether the input is user-interactive, or input comes from stdin or a pipe. (It will bring up a user dialog for input when run in a graphical environment.)

 
sum[eval[split[%r/\s+/, input[""]]]]
 

FunL[edit]

println( sum(map(int, readLine().split(' +'))) )

FUZE BASIC[edit]

-- Scott A. Rossell, 02-27-16

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

Gema[edit]

<D> <D>[email protected]{$1;$2}

GML[edit]

var add, a, b;
add = argument0; // get the string with the numbers to add
a = real(string_copy(add, 1, string_pos(" ", add)));
b = real(string_copy(add, string_pos(" ", add) + 1, string_length(add) - string_pos(" ", add)));
return(a + b);

Go[edit]

package main
 
import "fmt"
 
func main() {
var a, b int
fmt.Scan(&a, &b)
fmt.Println(a + b)
}

Golfscript[edit]

~+

Gosu[edit]

 
uses java.io.InputStreamReader
uses java.util.Scanner
uses java.lang.System
 
var scanner = new Scanner( new InputStreamReader( System.in ) )
var a = scanner.nextInt()
var b = scanner.nextInt()
 
print( a + b )
 

Groovy[edit]

def abAdder = {
def reader = new Scanner(System.in)
def a = reader.nextInt();
def b = reader.nextInt();
assert (-1000..1000).containsAll([a,b]) : "both numbers must be between -1000 and 1000 (inclusive)"
a + b
}
abAdder()

GUISS[edit]

We cannot use variables, but we can find the sum of two numbers.Here we add 3 + 2:

Start,Programs,Accessories,Calculator,Button:3,Button:[plus],
Button:2,Button:[equals]

Haskell[edit]

main =  print . sum . map read . words =<< getLine

HicEst[edit]

A and B are input via edit controls with spinners limiting inputs to +-1000.

DLG(Edit=A, DNum, MIn=-1000, MAx=1000, E=B, DN, MI=-1000, MA=1000)
WRITE(Messagebox, Name) A, B, "Sum = ", A+B

Icon and Unicon[edit]

procedure main()
numChars := '-'++&digits
read() ? {
A := (tab(upto(numChars)), integer(tab(many(numChars))))
B := (tab(upto(numChars)), integer(tab(many(numChars))))
}
write((\A + \B) | "Bad input")
end

Idris[edit]

main : IO()
main = do
line <- getLine
print $ sum $ map cast $ words line

J[edit]

Typically, in J, you would find the sum of two numbers (let us say 2 and 3) by entering both of them on a line with a + sign between them:

   2+3
5

In the following expression, 1!:1(3) reads a line from STDIN; -.LF drops the line ending character; ". converts the remaining text to a sequence of numbers which are then summed using +/.

+/". (1!:1(3))-.LF

Here's a little script, called "a+b.ijs":

#!/Applications/j602/bin/jconsole
echo +/". (1!:1(3))-.LF
exit ''

Here is the execution of the script:

echo 2 3 | ./a+b.ijs
5

Java[edit]

import java.util.*;
 
public class Sum2 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in); // Standard input
System.out.println(in.nextInt() + in.nextInt()); // Standard output
}
}

Object of class Scanner works slow enough, because of that contestants prefer to avoid its use. Often, longer solution works faster and easily scales to problems.

import java.io.*;
import java.util.*;
 
public class SumDif {
StreamTokenizer in;
PrintWriter out;
 
public static void main(String[] args) throws IOException {
new SumDif().run();
}
 
private int nextInt() throws IOException {
in.nextToken();
return (int)in.nval;
}
 
public void run() throws IOException {
in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in))); // Standard input
out = new PrintWriter(new OutputStreamWriter(System.out)); // Standard output
solve();
out.flush();
}
 
private void solve() throws IOException {
out.println(nextInt() + nextInt());
}
}
import java.io.*; 
 
public class AplusB {
public static void main(String[] args) {
try {
StreamTokenizer in = new StreamTokenizer(new FileReader("input.txt"));
in.nextToken();
int a = (int) in.nval;
in.nextToken();
int b = (int) in.nval;
FileWriter outFile = new FileWriter("output.txt");
outFile.write(Integer.toString(a + b));
outFile.close();
}
catch (IOException e) {
System.out.println("IO error");
}
}
}


 
grammar aplusb ;
 
options {
language = Java;
}
 
aplusb : (WS* e1=Num WS+ e2=Num NEWLINE {System.out.println($e1.text + " + " + $e2.text + " = " + (Integer.parseInt($e1.text) + Integer.parseInt($e2.text)));})+
;
Num : '-'?('0'..'9')+
;
WS : (' ' | '\t')
;
NEWLINE : WS* '\r'? '\n'
 ;
 

Produces:

>java Test
1 2
23 89
13 567
-75 6
-75 -29
^Z
1 + 2 = 3
23 + 89 = 112
13 + 567 = 580
-75 + 6 = -69
-75 + -29 = -104

JavaScript[edit]

ES5[edit]

Client side:

<html>
<body>
<div id='input'></div>
<div id='output'></div>
<script type='text/javascript'>
var a = window.prompt('enter A number', '');
var b = window.prompt('enter B number', '');
document.getElementById('input').innerHTML = a + ' ' + b;
 
var sum = Number(a) + Number(b);
document.getElementById('output').innerHTML = sum;
</script>
</body>
</html>

Server side (with node.js):

process.openStdin().on (
'data',
function (line) {
var xs = String(line).match(/^\s*(\d+)\s+(\d+)\s*/)
console.log (
xs ? Number(xs[1]) + Number(xs[2]) : 'usage: <number> <number>'
)
process.exit()
}
)
$ node io.js
2 3
5
$ node io.js
x 3
usage: <integer> <integer>

ES6[edit]

Node.js in a terminal:

process.stdin.on("data", buffer => {
console.log(
(buffer + "").trim().split(" ").map(Number).reduce((a, v) => a + v, 0)
);
});
 
 $ node io.js
 2 3
 5

Julia[edit]

Run from the command line:

 
#A+B
function AB()
input = sum(map(int,split(readline(STDIN)," ")))
println(input)
end
AB()
Output:
>julia AB.jl
1 1
2

In the next solution, an error is returned if the entry is not constituted from exactly two integers. Any number of spaces can follow an integer.

julia> int(readuntil(STDIN, ' ')) + int(readuntil(STDIN, '\n'))
1 2
3
 

Joy[edit]

Console[edit]

get get +.

File[edit]

"input.txt" include
"output.txt" "w" fopen
get get + fput pop quit.

jq[edit]

Since the given task is simply to add two numbers, the simplest approach in jq is illustrated by the following transcript:

$ jq -s add
3 2
5
This will work provided the numbers are neither too small nor too large. However, the above program will add **all** the numbers presented on the stream (assuming only numbers are presented). If the task were to add consecutive pairs of numbers, then the approach illustrated in the following transcript can be used, in conjunction with the jq "-s" option:
 
def addpairs:
if length < 2 then empty
else (.[0] + .[1]), (.[2:] | addpairs)
end;
 
addpairs
For example, here is a transcript that assumes the program is in a file named AB.jq:
 
$ jq -s -f AB.jq
1 2 3 4 5 6
3
7
11

L++[edit]

(main
(decl int a)
(decl int b)
(>> std::cin a b)
(prn (+ a b)))

Lasso[edit]

[a + b]

Lang5[edit]

read read + .
 
read " " split expand drop + .

Liberty BASIC[edit]

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

Lisaac[edit]

Section Header
+ name := A_PLUS_B
 
Section Public
- main <- ( (IO.read_integer; IO.last_integer) +
(IO.read_integer; IO.last_integer) ).println;

Little[edit]

void main() {
string a, b;
scan(gets(stdin), "%d %d", &a, &b);
puts(((int)a + (int)b));
}

LiveCode[edit]

Using Livecode Server script

<?lc
if isNumber($0) and isNumber($1) then
put $0 + $1
else
put $0 && $1
end if
?>

A graphical version using an input dialog

on mouseUp
ask "Enter two numbers"
set itemdelimiter to space
put it into nums
if isNumber(item 1 of nums) and isNumber(item 2 of nums) then
answer item 1 of nums + item 2 of nums
else
answer item 1 of nums && item 2 of nums
end if
end mouseUp

[edit]

show apply "sum readlist

Lua[edit]

a,b = io.read("*number", "*number")
print(a+b)

Kite[edit]

#!/usr/bin/kite
 
import "System.file";
 
in = System.file.stdin;
line = in|readline;
while(not (line is null)) [
arry = line|split(" ");
result = (arry[0])|int + (arry[1])|int;
result|print;
 
line = in|readline;
];
Output:
$ kite a_plus_b.kt <<EOF
5 6
EOF
11
$

M4[edit]

 define(`sumstr', `eval(patsubst(`$1',` ',`+'))')
 
sumstr(1 2)
3

Maple[edit]

 convert( scanf( "%d %d" ), '`+`' );
23 34
57

Mathematica[edit]

Interactive in a notebook

Input[] + Input[]

MATLAB / Octave[edit]

function sumOfInputs = APlusB()
inputStream = input('Enter two numbers, separated by a space: ', 's');
numbers = str2num(inputStream); %#ok<ST2NM>
if any(numbers < -1000 | numbers > 1000)
warning('APlusB:OutOfRange', 'Some numbers are outside the range');
end
sumOfInputs = sum(numbers);
end

Maude[edit]

Built-in[edit]

 
red 3 + 4 .
 

With restrictions[edit]

 
fmod ADD is
 
protecting INT .
 
op undefined : -> Int .
op _add_ : Int Int -> Int [assoc comm] .
 
vars A B : Int .
 
eq A add B = if (A < -1000 or B < -1000) or (A > 1000 or B > 1000) then undefined else A + B fi .
 
endfm
 

Mercury[edit]

:- module a_plus_b.
:- interface.
 
:- import_module io.
:- pred main(io::di, io::uo) is det.
 
:- implementation.
:- import_module int, list, string.
 
main(!IO) :-
io.read_line_as_string(Result, !IO),
( if
Result = ok(Line),
[AStr, BStr] = string.words(Line),
string.to_int(AStr, A), string.to_int(BStr, B)
then
io.format("%d\n", [i(A + B)], !IO)
else
true
).

Maxima[edit]

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

mIRC Scripting Language[edit]

alias a+b {
echo -ag $calc($1 + $2)
}

МК-61/52[edit]

С/П + С/П

ML/I[edit]

The two numbers are read from 'standard input' or its equivalent.

MCSKIP "WITH" NL
"" A+B
"" assumes macros on input stream 1, terminal on stream 2
MCSKIP MT,<>
MCINS %.
MCDEF SL SPACES NL AS <MCSET T1=%A1.
MCSET T2=%A2.
%T1+T2.
MCSET S10=0
>
MCSKIP SL WITH *
MCSET S1=1
*MCSET S10=2

Modula-2[edit]

MODULE  ab;
 
IMPORT InOut;
 
VAR A, B : INTEGER;
 
BEGIN
InOut.ReadInt (A);
InOut.ReadInt (B);
InOut.WriteInt (A + B, 8);
InOut.WriteLn
END ab.

MoonScript[edit]

a,b = io.read '*number','*number'
print a + b

MUMPS[edit]

ANB
NEW A,B,T,S
READ !,"Input two integers between -1000 and 1000, separated by a space: ",S
SET A=$PIECE(S," ",1),B=$PIECE(S," ",2)
SET T=(A>=-1000)&(A<=1000)&(B>=-1000)&(B<=1000)&(A\1=A)&(B\1=B)
IF T WRITE !,(A+B)
IF 'T WRITE !,"Bad input"
QUIT

Nemerle[edit]

Translation of: C#
using System;
using System.Console;
using System.Linq;
 
module AplusB
{
Main() : void
{
WriteLine(ReadLine().Split().Select(int.Parse).Sum());
}
}

NetRexx[edit]

/* NetRexx */
 
options replace format comments java symbols binary
 
parse ask a b .
say a '+' b '=' a + b

newLISP[edit]

(println (apply + (map int (parse (read-line)))))

Nim[edit]

A+B:

import strutils, os
 
echo parseInt(paramStr(1)) + parseInt(paramStr(2))

Arbitrary number of arguments:

import strutils, os
var sum = 0
for i in countup(1, paramCount()):
sum = sum + parseInt(paramStr(i))
echo sum

another:

from strutils import parseFloat, formatFloat, ffDecimal
 
proc aplusb(a,b: float): float =
return a + b
 
proc getnumber(): float =
try:
parseFloat(readLine(stdin))
except EInvalidValue:
echo("Please enter a number: ")
getnumber()
 
echo("First number please: ")
let first: float = getnumber()
 
echo("Second number please: ")
let second: float = getnumber()
 
echo("Result: " & formatFloat(aplusb(first, second), ffDecimal, 2))

Nit[edit]

Generic non-robust version:

module ab
 
var words = gets.split(" ")
print words[0].to_i + words[1].to_i

Objeck[edit]

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();
};
}
}
}

Oberon-2[edit]

MODULE  ab;
 
IMPORT In, Out;
 
VAR A, B : INTEGER;
 
BEGIN
In.Int (A);
In.Int (B);
Out.Int (A + B, 8);
Out.Ln
END ab.

Producing

12 34
      46

OCaml[edit]

Scanf.scanf "%d %d" (fun a b -> Printf.printf "%d\n" (a + b))

Oforth[edit]

Works with any number of integers separated by a space.

System.Console askln words map(#asInteger) sum .

Onyx[edit]

$Prompt {
`\nEnter two numbers between -1000 and +1000,\nseparated by a space: ' print flush
} def
 
$GetNumbers {
mark stdin readline pop # Reads input as a string. Pop gets rid of false.
cvx eval # Convert string to integers.
} def
 
$CheckRange { # (n1 n2 -- bool)
dup -1000 ge exch 1000 le and
} def
 
$CheckInput {
counttomark 2 ne
{`You have to enter exactly two numbers.\n' print flush quit} if
2 ndup CheckRange exch CheckRange and not
{`The numbers have to be between -1000 and +1000.\n' print flush quit} if
} def
 
$Answer {
add cvs `The sum is ' exch cat `.\n' cat print flush
} def
 
Prompt GetNumbers CheckInput Answer

ooRexx[edit]

version 1[edit]

Translation of: REXX
Numeric digits 1000             /*just in case the user gets ka-razy. */
Say 'enter some numbers to be summed:'
parse pull y
yplus=add_plus(y)
sum=0
Do While y<>''
Parse Var y n y
If datatype(n)<>'NUM' Then Do
Say 'you entered something that is not recognized to be a number:' n
Exit
End
sum+=n
End
Say yplus '=' sum/1
Exit
add_plus:
Parse arg list
list=space(list)
return translate(list,'+',' ')
Output:
enter some numbers to be summed:
1e10+7.777+33 = 10000000040.777

version 2[edit]

extend for negative numbers

Numeric digits 1000
Say 'enter some numbers to be summed:'
parse pull y
sum=0
yplus=''
Do i=1 By 1 While y<>''
Parse Var y n y
If datatype(n)<>'NUM' Then Do
Say 'you entered something that is not recognized to be a number:' n
Exit
End
Select
When i=1 Then
yplus=n
When n>0 Then yplus||='+'abs(n)
Otherwise yplus||=n
End
sum+=n
End
Say yplus '=' sum/1
Exit

OpenEdge/Progress[edit]

DEFINE VARIABLE a AS INTEGER NO-UNDO FORMAT "->>>9".
DEFINE VARIABLE b AS INTEGER NO-UNDO FORMAT "->>>9".
 
IF SESSION:BATCH THEN DO:
INPUT FROM "input.txt".
IMPORT a b.
INPUT CLOSE.
END.
ELSE
UPDATE a b.
 
MESSAGE a + b VIEW-AS ALERT-BOX

Openscad[edit]

There is no means of run-time input in Openscad

 
a = 5 + 4;
echo (a);
 

Oxygene[edit]

 
// Sum 2 integers read fron standard input
//
// Nigel Galloway - April 16th., 2012
//
namespace aplusb;
 
interface
uses System.Text.RegularExpressions.*;
 
type
aplusb = class
public
class method Main;
end;
 
implementation
 
class method aplusb.Main;
var
gc: GroupCollection;
m : Match;
begin
m := new Regex('^\s*(?<a>-?[1-9]\d{0,2}|0|-?1000)\s+(?<b>-?[1-9]\d{0,2}|0|-?1000)\s*$').Match(Console.ReadLine());
if m.Success then
begin
gc := m.Groups;
Console.WriteLine("{0} + {1} = {2}", gc['a'].Value, gc['b'].Value, Integer.Parse(gc['a'].Value) + Integer.Parse(gc['b'].Value));
end
else Console.WriteLine("Invalid Input");
end;
 
end.
 

Produces:

>aplusb
23 -99
23 + -99 = -76

Oz[edit]

declare
class TextFile from Open.file Open.text end
 
StdIn = {New TextFile init(name:stdin)}
 
fun {ReadInt}
{String.toInt {StdIn getS($)}}
end
in
{Show {ReadInt}+{ReadInt}}

PARI/GP[edit]

User input:

input()+input()

File input:

read("file1")+read("file2")

Pascal[edit]

var
a, b: integer;
begin
readln(a, b);
writeln(a + b);
end.

Same with input from file input.txt and output from file output.txt.

var
a, b: integer;
begin
reset(input, 'input.txt');
rewrite(output, 'output.txt');
readln(a, b);
writeln(a + b);
close(input);
close(output);
end.

Perl[edit]

my ($a,$b) = split(' ', scalar(<STDIN>));
print "$a $b " . ($a + $b) . "\n";

Perl 6[edit]

Works with: rakudo version 2015.12

Short version with very little "line noise":

get.words.sum.say;

Reduction operator [+], and say as a function:

say [+] get.words;

Long version:

my ($a, $b) = $*IN.get.split(" ");
say $a + $b;

Phix[edit]

When presented with a problem this simple, I start inventing difficulty in the simple act of accepting input (especially 2 numbers on one line)... so I ended up with three different solutions, this being the longest. The much shorter Euphoria version above also works fine.

-- longhand version, input is echoed, full error handling  
string text
integer idx = 0
integer ch
 
procedure nextch()
idx += 1
if idx>length(text) then
idx = 0
ch = 0
else
ch = text[idx]
end if
end procedure
 
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
 
procedure twoNumbers()
integer a, b
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
 
twoNumbers()

PHP[edit]

fscanf(STDIN, "%d %d\n", $a, $b); //Reads 2 numbers from STDIN
echo ($a + $b) . "\n";
$in = fopen("input.dat", "r");
fscanf($in, "%d %d\n", $a, $b); //Reads 2 numbers from file $in
fclose($in);
 
$out = fopen("output.dat", "w");
fwrite($out, ($a + $b) . "\n");
fclose($out);

PicoLisp[edit]

(+ (read) (read))
3 4
-> 7

Piet[edit]

Piet A+B.png The code is fairly straightforward. The individual commands are as follows:

in(num)
in(num)
add
out(num)

Pike[edit]

string line = Stdio.stdin->gets();
sscanf(line, "%d %d", int a, int b);
write(a+b +"\n");

PL/I[edit]

get (a, b);
put (a+b);

PostScript[edit]

(%stdin) (r) file  % get stdin
dup
token pop  % read A
exch
token pop  % read B
add
=

Potion[edit]

# The numbers are entered, piped, or redirected in via STDIN and the format is proper (i.e., "%d %d").
input = read
i = 0
while (i < input length):
if (input(i) == " "):
break
.
i++
.
(input slice(0, i) number + input slice(i, nil) number) print
 
# The numbers are manually inputted, but the format is improper (i.e., "%d\n%d\n").
(read number + read number) print

PowerShell[edit]

$a,$b = -split "$input"
[int]$a + [int]$b

This solution does not work interactively, while the following only works interactively:

$a,$b = -split (Read-Host)
[int]$a + [int]$b

Processing[edit]

Rudimentary User Interface[edit]

Click on either side to add 1 to its value.

int a = 0;
int b = 0;
 
void setup() {
size(200, 200);
}
 
void draw() {
fill(255);
rect(0, 0, width, height);
fill(0);
line(width/2, 0, width/2, height * 3 / 4);
line(0, height * 3 / 4, width, height * 3 / 4);
text(a, width / 4, height / 4);
text(b, width * 3 / 4, height / 4);
text("Sum: " + (a + b), width / 4, height * 7 / 8);
}
 
void mousePressed() {
if (mouseX < width/2) {
a++;
} else {
b++;
}
}

What the GUI looks like.

ProDOS[edit]

With the math module:

editvar /newvar /value=a /title=Enter an integer:
editvar /newvar /value=b /title=Enter another integer:
editvar /newvar /value=c
do add -a-,-b-=-c-
printline -c-

Without the math module:

editvar /newvar /value=a /title=Enter an integer:
editvar /newvar /value=b /title=Enter another integer:
editvar /newvar /value=c=-a-+-b-
printline -c-

Prolog[edit]

Works with: SWI-Prolog
plus :-
read_line_to_codes(user_input,X),
atom_codes(A, X),
atomic_list_concat(L, ' ', A),
maplist(atom_number, L, LN),
sumlist(LN, N),
write(N).

output :

?- plus.
|: 4 5
9
true.

Pure[edit]

using system;
printf "%d\n" (x+y) when x,y = scanf "%d %d" end;

PureBasic[edit]

Console[edit]

x$=Input()
a=Val(StringField(x$,1," "))
b=Val(StringField(x$,2," "))
PrintN(str(a+b))

File[edit]

If ReadFile(0,"in.txt")
x$=ReadString(0)
a=Val(StringField(x$,1," "))
b=Val(StringField(x$,2," "))
If OpenFile(1,"out.txt")
WriteString(1,str(a+b))
CloseFile(1)
EndIf
CloseFile(0)
EndIf

Python[edit]

Console[edit]

In Python 2, input returns ints, while raw_input returns strings. In Python 3, input returns strings, and raw_input does not exist.

The first two lines allow the program to be run in either Python 2 or 3. In Python 2, raw_input exists, and the lines are effectively skipped. In Python 3, calling raw_input triggers an error, so the except loop activates and assigns "raw_input" the value of Python 3's "input" function. Regardless of version, these two lines make sure that raw_input will return a string.

try: raw_input
except: raw_input = input
 
print(sum(map(int, raw_input().split())))

File[edit]

For Python 2.X and 3.X taking input from stdin stream which can be redirected to be file input under Unix

import sys
 
for line in sys.stdin:
print(sum(map(int, line.split())))

R[edit]

sum(scan("", numeric(0), 2))

Ra[edit]

 
class Sum
**Adds two given integers**
 
on start
 
args := program arguments
 
if args empty
print to Console.error made !, "No arguments given"
exit program with error code
 
if args.count = 1
print to Console.error made !, "Only one argument given"
exit program with error code
 
try
print integer.parse(args[0]) + integer.parse(args[1])
 
catch FormatException
print to Console.error made !, "Arguments must be integers"
exit program with error code
 
catch OverflowException
print to Console.error made !, "Numbers too large"
exit program with error code
 

Racket[edit]

 
#lang racket
(+ (read) (read))
 

Or, with additional error checking:

 
#lang racket
(define a (read))
(unless (number? a) (error 'a+b "number" a))
(define b (read))
(unless (number? b) (error 'a+b "number" b))
(displayln (+ a b))
 

REBOL[edit]

forever [x: load input  print x/1 + x/2]
Output:
1 2
3
2 2
4
3 2
5

Retro[edit]

: try ( "-n ) getToken toNumber getToken toNumber + putn ;
try 1 2

REXX[edit]

version 1, unnormalized[edit]

The numbers can be any valid REXX number (integer, fixed point decimal, floating point (with exponential notation, ···).

/*REXX program obtains two numbers from the input stream (the console), shows their sum.*/
parse pull a b /*obtain two numbers from input stream.*/
say a+b /*display the sum to the terminal. */
/*stick a fork in it, we're all done. */

version 2, normalizied[edit]

If the user entered   4.00000   and wanted to add   5   to that, and expects   9,
then the output needs to be normalized before displaying the result.

Normally, REXX will keep the greatest precision in the results;
adding   4.00000   and   5   will normally yield   9.00000

Dividing by one normalizes the number.

/*REXX program obtains two numbers from the input stream (the console), shows their sum.*/
parse pull a b /*obtain two numbers from input stream.*/
say (a+b) / 1 /*display normalized sum to terminal. */
/*stick a fork in it, we're all done. */

version 3, extended precision[edit]

Using the   numeric digits   statement allows more decimal digits to be used, the default is   9.

/*REXX program obtains two numbers from the input stream (the console), shows their sum.*/
numeric digits 300 /*the default is nine decimal digits.*/
parse pull a b /*obtain two numbers from input stream.*/
z= (a+b) / 1 /*add and normalize sum, store it in Z.*/
say z /*display normalized sum Z to terminal.*/
/*stick a fork in it, we're all done. */
 

version 4, multiple numbers[edit]

This REXX program version adds   all   the numbers entered   (not just two).

/*REXX program obtains some numbers from the input stream (the console), shows their sum*/
numeric digits 1000 /*just in case the user gets ka-razy. */
say 'enter some numbers to be summed:' /*display a prompt message to terminal.*/
parse pull y /*obtain all numbers from input stream.*/
many=words(y) /*obtain the number of numbers entered.*/
$=0 /*initialize the sum to zero. */
do j=1 for many /*process each of the numbers. */
$=$ + word(y, j) /*add one number to the sum. */
end /*j*/
 
say 'sum of ' many " numbers = " $/1 /*display normalized sum $ to terminal.*/
/*stick a fork in it, we're all done. */

Ring[edit]

give Numbers
Numbers = split(Numbers)
sum = 0
for x in Numbers sum += x next
see sum
 
func Split Str
for x in str if x = " " x = nl ok next
return str2list(str)

Ruby[edit]

puts gets.split.map(&:to_i).inject(:+)

Run BASIC[edit]

input, x$
print val(word$(x$,1)) + val(word$(x$,2))


Rust[edit]

use std::io;
 
fn main() {
let mut line = String::new();
io::stdin().read_line(&mut line).expect("reading stdin");
 
let mut i: i64 = 0;
for word in line.split_whitespace() {
i += word.parse::<i64>().expect("trying to interpret your input as numbers");
}
println!("{}", i);
}

or

#![feature(iter_arith)]
use std::io;
 
fn main() {
let mut a = String::new();
io::stdin().read_line(&mut a).expect("reading stdin");
println!("{}",
a.split_whitespace()
.map(|x| x.parse::<i32>().expect("these better be numbers"))
.sum::<i32>());
}
 

Scala[edit]

println(readLine().split(" ").map(_.toInt).sum)

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

val s = new java.util.Scanner(System.in)
val sum = s.nextInt() + s.nextInt()
println(sum)

or

println(readLine().split(" ").filter(_.length>0).map(_.toInt).sum)

Scheme[edit]

(display (+ (read) (read)))

sed[edit]

Sed is for string processing and has no facility for manipulating numbers as numeric values. However, being Turing complete, sed can be coerced into performing mathematics.

: Loop
# All done
/^-*00* /s///
/ -*00*$/s///
t
 
# Negative Check
/^\(-*\)[0-9].* \1[0-9]/!b Negative
 
# Create magic lookup table
s/\(.[0-9]*\) \(.[0-9]*\)/\1;987654321000009999000999009909 \2;012345678999990000999000990090/
s/ \(-\)*\(9*;\)/ \10\2/
# Decrement 1st number
s/\([^0]\)\(0*\);[^0]*\1\(.\).*\2\(9*\).* \(.*\)/\3\4 \5/
# Increment 2nd
s/\([^9]\)\(9*\);[^9]*\1\(.\).*\2\(0*\).*/\3\4/
t Loop
 
: Negative
# Create magic lookup table
s/\(.[0-9]*\) \(.[0-9]*\)/\1;987654321000009999000999009909 \2;987654321000009999000999009909/
# Decrement 1st number
s/\([^0]\)\(0*\);[^0]*\1\(.\).*\2\(9*\).* \(.*\)/\3\4 \5/
# Decrement 2nd
s/\([^0]\)\(0*\);[^0]*\1\(.\).*\2\(9*\).*/\3\4/
t Loop

Another method, based off of this StackExchange answer:

#!/bin/sed -f
 
# Add a marker in front of each digit, for tracking tens, hundreds, etc.
s/[0-9]/<&/g
# Convert numbers to, in essence, tally marks
s/0//g; s/1/|/g; s/2/||/g; s/3/|||/g; s/4/||||/g; s/5/|||||/g
s/6/||||||/g; s/7/|||||||/g; s/8/||||||||/g; s/9/|||||||||/g
 
# Multiply by ten for each digit from the back they were.
:tens
s/|</<||||||||||/g
t tens
 
# We don't want the digit markers any more
s/<//g
 
# Negative minus negative is the negation of their absolute values.
s/^-\(|*\) *-/-\1/
# Negative plus positive equals positive plus negative, and we want the negative at the back.
s/^-\(|*\) \+\(|*\)$/\2-\1/
# Get rid of any space between the numbers
s/ //g
 
# A tally on each side can be canceled.
:minus
s/|-|/-/
t minus
s/-$//
 
# Convert back to digits
:back
s/||||||||||/</g
s/<\([0-9]*\)$/<0\1/g
s/|||||||||/9/g;
s/|||||||||/9/g; s/||||||||/8/g; s/|||||||/7/g; s/||||||/6/g;
s/|||||/5/g; s/||||/4/g; s/|||/3/g; s/||/2/g; s/|/1/g;
s/</|/g
t back
s/^$/0/

Seed7[edit]

$ include "seed7_05.s7i";
 
const proc: main is func
local
var integer: a is 0;
var integer: b is 0;
begin
read(a);
read(b);
writeln(a + b);
end func;

SequenceL[edit]

import <Utilities/Conversion.sl>;
 
main(args(2)) := stringToInt(args[1]) + stringToInt(args[2]);
Output:
cmd:> main.exe 3 4
7

cmd:> main.exe -5 7
2

cmd:> main.exe -12 -10
-22

SETL[edit]

read(A, B);
print(A + B);

Self[edit]

Works with positive and negative integers, and also more than two integers.

((stdin readLine splitOn: ' ') mapBy: [|:e| e asInteger]) sum printLine.

Shiny[edit]

if (io.line 'stdin').match ~(\d+)\s+(\d+)~
say "$a $b %(a+b)d"
end

Sidef[edit]

Works with both positive and negative integers.

say STDIN.readline.words.map{.to_i}.sum

More idiomatically:

say read(String).words»to_i»()«+»

Explicit summation:

var (a, b) = read(String).words.map{.to_i}...
say a+b

SmileBASIC[edit]

INPUT A
INPUT B
PRINT A+B
 

SNOBOL4[edit]

Simple-minded solution (literally "two somethings separated by space")

	input break(" ") . a " " rem . b 
output = a + b
end

"Integer aware" solution:

	nums = "0123456789"
input span(nums) . a break(nums) span(nums) . b
output = a + b
end

Smalltalk[edit]

Most Smalltalk implementations do not have the notion of a standard input stream, since it has always been a GUI based programming environment. I've included test methods to demonstrate one way to create an input stream with two integers can be created. Opening a text file would be another.

'From Squeak3.7 of ''4 September 2004'' [latest update: #5989] on 8 August 2011 at 3:50:55 pm'!
Object subclass: #ABTask
instanceVariableNames: ''
classVariableNames: ''
poolDictionaries: ''
category: 'rosettacode'!
 
"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!
 
ABTask class
instanceVariableNames: ''!
 
!ABTask class methodsFor: 'demo'!
parseInteger: inputStream
^ Integer readFrom: inputStream skipSeparators! !
 
!ABTask class methodsFor: 'demo'!
sum: inputStream
^ (self parseInteger: inputStream)
+ (self parseInteger: inputStream)! !
 
!ABTask class methodsFor: 'demo'!
test2Plus2
^ self
sum: (ReadStream on: '2 2')! !
 
!ABTask class methodsFor: 'demo'!
test3Plus2
^ self
sum: (ReadStream on: '3 2')! !

but all have a stream hierarchy, so the task could be restated to pass input and output as stream arguments:

Works with: Smalltalk/X
|task|
task := [:inStream :outStream |
|processLine|
 
processLine :=
[
|a b|
a := Integer readFrom: inStream.
b := Integer readFrom: inStream.
"is validation part of the task?"
self assert:( a between:-1000 and: 1000).
self assert:( b between:-1000 and: 1000).
outStream print (a+b); cr.
].
 
[ inStream atEnd ] whileFalse:processLine.
].
 
task value: ( 'dataIn.txt' asFilename readStream) value:Transcript.

or:

task value: Stdin value: Stdout.

SPAD[edit]

Works with: FriCAS
Works with: OpenAxiom
Works with: Axiom

One of several possibilities:

(1) -> integer READ()$Lisp + integer READ()$Lisp
333 444
 
(1) 777
Type: PositiveInteger

Domain:SExpression

SPARK[edit]

-- By Jacob Sparre Andersen
-- Validates with SPARK GPL 2010's Examiner/Simplifier
 
with SPARK_IO; --# inherit SPARK_IO;
 
--# main_program;
procedure A_Plus_B
--# global in out SPARK_IO.Inputs, SPARK_IO.Outputs;
--# derives SPARK_IO.Inputs from SPARK_IO.Inputs &
--# SPARK_IO.Outputs from SPARK_IO.Inputs, SPARK_IO.Outputs;
is
subtype Small_Integers is Integer range -1_000 .. +1_000;
A, B  : Integer;
A_OK, B_OK : Boolean;
begin
SPARK_IO.Get_Integer
(File => SPARK_IO.Standard_Input,
Item => A,
Width => 0,
Read => A_OK);
 
A_OK := A_OK and A in Small_Integers;
 
SPARK_IO.Get_Integer
(File => SPARK_IO.Standard_Input,
Item => B,
Width => 0,
Read => B_OK);
 
B_OK := B_OK and B in Small_Integers;
 
if A_OK and B_OK then
SPARK_IO.Put_Integer
(File => SPARK_IO.Standard_Output,
Item => A + B,
Width => 4,
Base => 10);
else
SPARK_IO.Put_Line
(File => SPARK_IO.Standard_Output,
Item => "Input data does not match specification.",
Stop => 0);
end if;
end A_Plus_B;

SQL[edit]

SELECT A+B

Example:

SELECT 2+3

This should produce a result set containing the value 5.

Note however that declaration of variables is outside the scope of the ANSI SQL standards, unless by variables you mean tables (which would complicate the example considerably).

Standard ML[edit]

(*
* val split : string -> string list
* splits a string at it spaces
*)
val split = String.fields (fn #" " => true | _ => false)
 
(*
* val removeNl : string -> string
* removes the occurence of "\n" in a string
*)
val removeNl = String.translate (fn #"\n" => "" | c => implode [c])
 
(*
* val aplusb : unit -> int
* reads a line and gets the sum of the numbers
*)
fun aplusb () =
let
val input = removeNl (valOf (TextIO.inputLine TextIO.stdIn))
in
foldl op+ 0 (map (fn s => valOf (Int.fromString s)) (split input))
end
Output:
- aplusb();
123 456
val it = 579 : int

Swift[edit]

Requires sending EOF.

import Foundation
 
let input = NSFileHandle.fileHandleWithStandardInput()
 
let data = input.availableData
let str = NSString(data: data, encoding: NSUTF8StringEncoding)!
 
let nums = str.componentsSeparatedByString(" ")
let a = (nums[0] as String).toInt()!
let b = (nums[1] as String).toInt()!
 
print(" \(a + b)")

Tcl[edit]

scan [gets stdin] "%d %d" x y
puts [expr {$x + $y}]

Alternatively:

puts [tcl::mathop::+ {*}[gets stdin]]

To/from a file:

set in [open "input.txt"]
set out [open "output.txt" w]
scan [gets $in] "%d %d" x y
puts $out [expr {$x + $y}]
close $in
close $out

TI-83 BASIC[edit]

:Prompt A,B
:Disp A+B

TI-89 BASIC[edit]

:aplusb(a,b)
:a+b

TorqueScript[edit]

Since torque is not compatible with standard input, I will show the closest to that. It's a function that takes a single string input, that will contain the 2 numbers.

Function aPlusB(%input)
{
return getWord(%input, 0) + getWord(%input, 1);
}

TUSCRIPT[edit]

$$ MODE TUSCRIPT
SET input="1 2"
SET input=SPLIT(input,": :")
SET input=JOIN (input)
SET output=SUM(input)

TXR[edit]

$ txr -p '(+ (read) (read))'
1.2 2.3
3.5

UNIX Shell[edit]

Works with: Bourne Shell
#!/bin/sh
read a b || exit
echo `expr "$a" + "$b"`
Works with: bash
Works with: ksh93
Works with: pdksh
Works with: zsh

Script "a+b.sh":

#!/bin/bash
read a b || exit
echo $(( a + b ))
Output:
echo 2 3 | ksh a+b.sh
5

C Shell[edit]

set line=$<
set input=($line)
@ sum = $input[1] + $input[2]
echo $sum

Ursala[edit]

Using standard input and output streams:

#import std
#import int
 
#executable&
 
main = %zP+ sum:-0+ %zp*FiNCS+ sep` @L

Overwriting a text file named as a command line parameter:

#import std
#import int
 
#executable -[parameterized]-
 
main = ~command.files.&h; <.contents:= %zP+ sum:-0+ %zp*FiNCS+ sep` @L+ ~contents>

Creating a new file named after the input file with suffix .out:

#import std
#import int
 
#executable -[parameterized]-
 
main =
 
~command.files.&h; ~&iNC+ file$[
contents: %zP+ sum:-0+ %zp*FiNCS+ sep` @L+ ~contents,
path: ~path; ^|C\~& ~=`.-~; ^|T/~& '.out'!]

Vala[edit]

Read from stdin while program running:

stdout.printf("Please enter int value for A\n");
int a = int.parse(stdin.read_line());
stdout.printf("Please enter int value for B\n");
int b = int.parse(stdin.read_line());
 
stdout.printf("A+B = %d\n", a+b);


VBA[edit]

Sub Rosetta_AB()
Dim stEval As String
stEval = InputBox("Enter two numbers, separated only by a space", "Rosetta Code", "2 2")
MsgBox "You entered " & stEval & vbCr & vbCr & _
"VBA converted this input to " & Replace(stEval, " ", "+") & vbCr & vbCr & _
"And evaluated the result as " & Evaluate(Replace(stEval, " ", "+")), vbInformation + vbOKOnly, "XLSM"
End Sub

VBScript[edit]

Option Explicit
Dim a, b
Select Case WScript.Arguments.Count
Case 0 'No arguments, prompt for them.
WScript.Echo "Enter values for a and b"
a = WScript.Stdin.ReadLine
if Instr(a, " ") > 0 then 'If two variables were passed
b = Split(a)(1)
a = Split(a)(0)
else
WScript.Echo "Enter value for b"
b = WScript.Stdin.ReadLine
end if
Case 1 'One argument, assume it's an input file, e.g. "in.txt"
Dim FSO : Set FSO = CreateObject("Scripting.FileSystemObject")
With FSO.OpenTextFile(WScript.Arguments(0), 1)
a = .ReadLine
b = Split(a)(1)
a = Split(a)(0)
.Close
End With
Case 2 'Two arguments, assume they are values
a = WScript.Arguments(0)
b = WScript.Arguments(1)
End Select
'At this point, a and b are strings as entered, make them numbers
a = CInt(a)
b = CInt(b)
 
'Write the sum
Wscript.Echo a + b
if 1 = WScript.Arguments.Count then
With FSO.CreateTextFile("out.txt")
.WriteLine a + b
.Close
End With
end if

Verilog[edit]

module TEST;
 
reg signed [11:0] y;
 
initial begin
y= sum(2, 2);
y= sum(3, 2);
y= sum(-3, 2);
end
 
function signed [11:0] sum;
input signed [10:0] a, b;
begin
sum= a + b;
$display("%d + %d = %d",a,b,sum);
end
endfunction
 
endmodule

VHDL[edit]

LIBRARY std;
USE std.TEXTIO.all;
 
 
entity test is
end entity test;
 
 
architecture beh of test is
begin
process
variable line_in, line_out : line;
variable a,b : integer;
begin
readline(INPUT, line_in);
read(line_in, a);
read(line_in, b);
 
write(line_out, a+b);
writeline(OUTPUT, line_out);
wait; -- needed to stop the execution
end process;
end architecture beh;

Visual Basic .NET[edit]

Module Module1
 
Sub Main()
Dim s() As String = Nothing
 
s = Console.ReadLine().Split(" "c)
Console.WriteLine(CInt(s(0)) + CInt(s(1)))
End Sub
 
End Module

Whitespace[edit]

    









 
 
 

X86 Assembly[edit]

Works with: NASM version Linux
section .text
global _start
 
_print:
mov ebx, 1
mov eax, 4
int 0x80
ret
 
_get_input:
mov edx, 4
mov ebx, 0
mov eax, 3
int 0x80
ret
 
_start:
mov edx, in_val_len
mov ecx, in_val_msg
call _print
mov ecx, a
call _get_input
;make 'a' an actual number rather than a char.
sub dword [a], 0x30
mov edx, in_val_len
mov ecx, in_val_msg
call _print
mov ecx, b
call _get_input
;calc real number for 'b'
sub dword [b], 0x30
mov eax, dword [a]
mov ebx, dword [b]
add eax, ebx
;get the character for our sum.
add eax, 0x30
mov dword [sum], eax
mov edx, out_val_len
mov ecx, out_val_msg
call _print
mov [sum+1], dword 0xa
mov edx, 4
mov ecx, sum
call _print
push 0x1
mov eax, 1
push eax
int 0x80
ret
 
section .data
in_val_msg db "Please input an integer:",0
in_val_len equ $-in_val_msg
out_val_msg db "The sum of a+b is: ",0
out_val_len equ $-out_val_msg
 
section .bss
a resd 1
b resd 1
sum resd 1

This will not work on numbers over 0(from 1 to 0). This is due to the fact, numbers higher than 0(10,11, etc) are in fact strings when taken from the keyboard. A much longer conversion code is required to loop through and treat each number in the string as separate numbers. For example, The number '10' would have to be treated as a 1 and a 0.

xEec[edit]

i# i# ma h#10 r o# p o$ p

XLISP[edit]

(DEFUN A-PLUS-B ()
(DISPLAY "Enter two numbers separated by a space.")
(NEWLINE)
(DISPLAY "> ")
(DEFINE A (READ))
(DEFINE B (READ))
(+ A B))
Output:
(A-PLUS-B)
Enter two numbers separated by a space.
> 2 2

4

XPL0[edit]

include c:\cxpl\codes;
int A, B;
[A:= IntIn(0);
B:= IntIn(0);
IntOut(0, A+B);
CrLf(0);
]

Yorick[edit]

a = b = 0;
read, a, b;
write, a + b;

ZED[edit]

Source -> http://ideone.com/WLtEfe Compiled -> http://ideone.com/fMt6ST

(A+B)
comment:
#true
(+) (read) (read)
 
(+) one two
comment:
#true
(003) "+" one two
 
(read)
comment:
#true
(001) "read"

zkl[edit]

do(2){ask("A B: ").split(" ").filter().sum().println()}
A B: 123    567
690
A B: -4 6
2

This actually works for any number of integers