A+B
You are encouraged to solve this task according to the task description, using any language you may know.
A+B - in programming contests, classic problem, which is given so contestants can gain familiarity with online judging system being used.
Problem statement
Given 2 integer numbers, A and B. One needs to find their sum.
- Input data
- Two integer numbers are written in the input stream, separated by space.
- Output data
- The required output is one integer: the sum of A and B.
- Example:
Input Output 2 2 4 3 2 5
[edit] 0815
|x|+%
[edit] ABAP
report z_sum_a_b.
data: lv_output type i.
selection-screen begin of block input.
parameters:
p_first type i,
p_second type i.
selection-screen end of block input.
at selection-screen output.
%_p_first_%_app_%-text = 'First Number: '.
%_p_second_%_app_%-text = 'Second Number: '.
start-of-selection.
lv_output = p_first + p_second.
write : / lv_output.
[edit] Ada
-- Standard I/O Streams
with Ada.Integer_Text_Io;
procedure APlusB is
A, B : Integer;
begin
Ada.Integer_Text_Io.Get (Item => A);
Ada.Integer_Text_Io.Get (Item => B);
Ada.Integer_Text_Io.Put (A+B);
end APlusB;
Using appropriate user defined types:
with Ada.Text_IO;
procedure A_Plus_B is
type Small_Integers is range -2_000 .. +2_000;
subtype Input_Values is Small_Integers range -1_000 .. +1_000;
package IO is new Ada.Text_IO.Integer_IO (Num => Small_Integers);
A, B : Input_Values;
begin
IO.Get (A);
IO.Get (B);
IO.Put (A + B, Width => 4, Base => 10);
end A_Plus_B;
[edit] ALGOL 68
[edit] Console
print((read int + read int))
Input:
1 2
Output:
+3
[edit] File
open(stand in, "input.txt", stand in channel);
open(stand out, "output.txt", stand out channel);
print((read int + read int))
Input "input.txt":
3 4
Output "output.txt":
+7
[edit] ANTLR
[edit] Java
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
[edit] Argile
(: 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
[edit] AutoHotkey
InputBox, input , A+B, Two integer numbers`, separated by space.
StringSplit, output, input, %A_Space%
msgbox, % output1 . "+" . output2 "=" output1+output2
[edit] AutoIt
;AutoIt Version: 3.2.10.0
$num = "45 54"
consolewrite ("Sum of " & $num & " is: " & sum($num))
Func sum($numbers)
$numm = StringSplit($numbers," ")
Return $numm[1]+$numm[$numm[0]]
EndFunc
[edit] AWK
{print $1 + $2}
[edit] Batch File
Prompts version
::aplusb.cmd
@echo off
setlocal
set /p a="A: "
set /p b="B: "
set /a c=a+b
echo %c%
endlocal
All on the commandline version
::aplusb.cmd
@echo off
setlocal
set a=%1
set b=%2
set /a c=a+b
echo %c%
endlocal
Formula on the command line version
::aplusb.cmd
@echo off
setlocal
set /a c=%~1
echo %c%
endlocal
Example of 'Formula on the command line version'
>aplusb 123+456 579 >aplusb "1+999" 1000
Parse the input stream version (thanks to Tom Lavedas on alt.msdos.batch.nt)
::aplusb.cmd
@echo off
setlocal
set /p a="Input stream: "
call :add %a%
echo %res%
endlocal
goto :eof
:add
set /a res=res+%1
shift
if "%1" neq "" goto :add
Example of 'parse the input stream version'
>aplusb Input stream: 1234 5678 6912 >aplusb Input stream: 123 234 345 456 567 678 789 890 4082
[edit] BASIC
DEFINT A-Z
tryagain:
backhere = CSRLIN
INPUT "", i$
i$ = LTRIM$(RTRIM$(i$))
where = INSTR(i$, " ")
IF where THEN
a = VAL(LEFT$(i$, where - 1))
b = VAL(MID$(i$, where + 1))
c = a + b
LOCATE backhere, LEN(i$) + 1
PRINT c
ELSE
GOTO tryagain
END IF
[edit] BASIC256
dim a(2)
input "Enter two numbers seperated by a space?", t$
a = explode(t$," ")
print t$ + " " + (a[0] + a[1])
[edit] BBC BASIC
REPEAT
hereY% = VPOS
INPUT LINE "" q$
hereX% = LEN(q$) + 1
WHILE LEFT$(q$, 1) = " "
q$ = MID$(q$, 2)
ENDWHILE
space% = INSTR(q$, " ")
IF space% THEN
a = VAL(LEFT$(q$, space% - 1))
b = VAL(MID$(q$, space% + 1))
PRINT TAB(hereX%, hereY%) ; a + b
ENDIF
UNTIL FALSE
That seems overly complicated. What's wrong with:
REPEAT
INPUT LINE "" q$
space% = INSTR(q$," ")
PRINT VAL LEFT$(q$,space%-1) + VAL MID$(q$,space%+1)
UNTIL FALSE
[edit] Befunge
&&+.@
[edit] Bracmat
filter is a pattern that checks that input is a non-fractional number not less than -1000 and not greater than 1000. The filter is applied to each input.
( out
$ ( put$"Enter two integer numbers between -1000 and 1000:"
& (filter=~/#%:~<-1000:~>1000)
& get':(!filter:?a) (!filter:?b)
& !a+!b
| "Invalid input. Try again"
)
);
[edit] Brainf***
, Read first number
>,, Eat separator and read second number
[<+>-] Add ASCII values
,++ Use newline to get a 12
[<---->-] Subtract 48 to get back to ASCII
<. and print
[edit] Brat
numbers = g.split[0,1].map(:to_i)
p numbers[0] + numbers[1] #Prints the sum of the input
[edit] Burlesque
ps++
[edit] C
// Standard input-output streams
#include <stdio.h>
int main()
{
int a, b;
scanf("%d%d", &a, &b);
printf("%d\n", a + b);
return 0;
}
// Input file: input.txt
// Output file: output.txt
#include <stdio.h>
int main()
{
freopen("input.txt", "rt", stdin);
freopen("output.txt", "wt", stdout);
int a, b;
scanf("%d%d", &a, &b);
printf("%d\n", a + b);
return 0;
}
[edit] C#
using System;
using System.Linq;
class Program
{
static void Main()
{
Console.WriteLine(Console.ReadLine().Split().Select(int.Parse).Sum());
}
}
Another way (not recommended since it does not work with more than two numbers):
using System;
class Program
{
static void Main()
{
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;
}
}
[edit] C++
// Standard input-output streams
#include <iostream>
using namespace std;
void 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;
}
[edit] Clojure
(println (+ (Integer/parseInt (read-line)) (Integer/parseInt (read-line))))
3
4
=>7
(eval (read-string (str "(+ " (read-line) " )") ))
3 3
6
[edit] CoffeeScript
<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>
[edit] Common Lisp
(write (+ (read) (read)))
[edit] D
[edit] From Console
import std.stdio, std.conv, std.string;
void main() {
string[] r;
try
r = readln().split();
catch (StdioException e)
r = ["10", "20"];
writeln(to!int(r[0]) + to!int(r[1]));
}
- Output:
30
[edit] From File
import std.stdio, std.conv, std.string;
void main() {
auto fin = File("sum_input.txt", "r");
auto r = fin.readln().split();
auto fout = File("sum_output.txt", "w");
fout.writeln(to!int(r[0]) + to!int(r[1]));
}
[edit] dc
? + psz
The question mark ? reads and executes a line of input. The user must enter a dc program that pushes two numbers to the stack, such as 2 3 or 5 _1. (The user must use underscore _ for negative numbers.)
[edit] Déjà Vu
[edit] Console
0
for k in split " " input:
+ to-num k
[edit] Delphi
Console version.
program SUM;
{$APPTYPE CONSOLE}
uses
SysUtils;
var
s1, s2:string;
begin
ReadLn(s1);
Readln(s2);
Writeln(StrToIntDef(s1, 0) + StrToIntDef(s2,0));
end.
[edit] 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" )
[edit] DWScript
Ghetto GUI version
var a := StrToInt(InputBox('A+B', 'Enter 1st number', '0'));
var b := StrToInt(InputBox('A+B', 'Enter 2nd number', '0'));
ShowMessage('Sum is '+IntToStr(a+b));
[edit] Eiffel
argument(0) contains the path of the executable - thus we start at argument(1)
class
APPLICATION
inherit
ARGUMENTS
create
make
feature {NONE} -- Initialization
make
-- Run application.
do
print(argument(1).to_integer + argument(2).to_integer)
end
end
[edit] Ela
open console list string read
readn() |> string.split " " |> map readStr |> sum
Output:
1 2 3 4 5 6 21
[edit] Elena
#define std'basic'*.
#define ext'io'*.
#symbol Console =>
[
#var anOutput := __wrap(ELineInput, 'program'input).
#var A := anOutput >> Integer.
#var B := anOutput >> Integer.
'program'output << A + B.
].
[edit] Erlang
-module(aplusb).
-export([start/0]).
start() ->
case io:fread("","~d~d") of
eof -> ok;
{ok, [A,B]} ->
io:format("~w~n",[A+B]),
start()
end.
[edit] Euler Math Toolbox
>s=lineinput("Two numbers seperated by a blank");
Two numbers seperated by a blank? >4 5
>vs=strtokens(s)
4
5
>vs[1]()+vs[2]()
9
[edit] Euphoria
include get.e
function snd(sequence s)
return s[2]
end function
integer a,b
a = snd(get(0))
b = snd(get(0))
printf(1," %d\n",a+b)
[edit] 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
[edit] F#
open System
let plus = (fun (a:string) (b:string) -> Console.WriteLine(int(a)+int(b))) (Console.ReadLine()) (Console.ReadLine());;
[edit] Factor
USING: math.parser splitting ;
: a+b ( -- )
readln " " split1
[ string>number ] bi@ +
number>string print ;
( scratchpad ) a+b 2 2 4
[edit] FALSE
[0[^$$'9>'0@>|~]['0-\10*+]#%]n: {read an integer}
n;!n;!+.
[edit] Fantom
class APlusB
{
public static Void main ()
{
echo ("Enter two numbers: ")
Str input := Env.cur.in.readLine
Int sum := 0
input.split.each |n| { sum += n.toInt }
echo (sum)
}
}
[edit] FBSL
Using stdin and stdout
#APPTYPE CONSOLE
DIM %a, %b
SCANF("%d%d", @a, @b)
PRINT a, "+", b, "=", a + b
PAUSE
[edit] Fish
i:o:"-"=?v1$68*-v
v >~01-0 >
>i:o:" "=?v68*-$a*+
>~*i:o:"-"=?v1$68*-v
v >~01-0 >
>i:o:d=?v68*-$a*+
>~*+aonao;
[edit] Forth
pad dup 80 accept evaluate + .
[edit] Fortran
program a_plus_b
implicit none
integer :: a
integer :: b
read (*, *) a, b
write (*, '(i0)') a + b
end program a_plus_b
[edit] GML
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)
[edit] Go
package main
import "fmt"
func main() {
var a, b int
fmt.Scan(&a, &b)
fmt.Println(a + b)
}
[edit] Golfscript
~+
[edit] Gosu
uses java.io.InputStreamReader
uses java.util.Scanner
uses java.lang.System
var scanner = new Scanner( new InputStreamReader( System.in ) )
var a = scanner.nextInt()
var b = scanner.nextInt()
print( a + b )
[edit] Groovy
def abAdder = {
def reader = new Scanner(System.in)
def a = reader.nextInt();
def b = reader.nextInt();
assert (-1000..1000).containsAll([a,b]) : "both numbers must be between -1000 and 1000 (inclusive)"
a + b
}
abAdder()
[edit] GUISS
We cannot use variables, but we can find the sum of two numbers.Here we add 3 + 2:
Start,Programs,Accessories,Calculator,Button:3,Button:[plus],
Button:2,Button:[equals]
[edit] Haskell
main = getLine >>= print . sum . map read . words
[edit] HicEst
A and B are input via edit controls with spinners limiting inputs to +-1000.
DLG(Edit=A, DNum, MIn=-1000, MAx=1000, E=B, DN, MI=-1000, MA=1000)
WRITE(Messagebox, Name) A, B, "Sum = ", A+B
[edit] Icon and Unicon
procedure main()
numChars := '-'++&digits
read() ? {
A := (tab(upto(numChars)), integer(tab(many(numChars))))
B := (tab(upto(numChars)), integer(tab(many(numChars))))
}
write((\A + \B) | "Bad input")
end
[edit] J
Typically, in J, you would find the sum of two numbers (let us say 2 and 3) by entering both of them on a line with a + sign between them:
2+3
5
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
[edit] Java
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");
}
}
}
[edit] JavaScript
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: <integer> <integer>'
)
process.exit()
}
)
$ node io.js 2 3 5 $ node io.js x 3 usage: <integer> <integer>
[edit] Julia
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
[edit] Joy
[edit] Console
get get +.
[edit] File
"input.txt" include
"output.txt" "w" fopen
get get + fput pop quit.
[edit] Lang5
read read + .
read " " split expand drop + .
[edit] Liberty BASIC
input, n$
print eval(word$(n$,1);" + ";word$(n$,2))
[edit] Lisaac
Section Header
+ name := A_PLUS_B
Section Public
- main <- ( (IO.read_integer; IO.last_integer) +
(IO.read_integer; IO.last_integer) ).println;
[edit] Logo
show apply "sum readlist
[edit] Lua
a,b = io.read("*number", "*number")
print(a+b)
[edit] Kite
#!/usr/bin/kite
import "System.file";
in = System.file.stdin;
line = in|readline;
while(not (line is null)) [
arry = line|split(" ");
result = (arry[0])|int + (arry[1])|int;
result|print;
line = in|readline;
];
Output:
$ kite a_plus_b.kt <<EOF
5 6
EOF
11
$
[edit] Maple
> convert( scanf( "%d %d" ), '`+`' );
23 34
57
[edit] Mathematica
Interactive in a notebook
Input[] + Input[]
[edit] MATLAB
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
[edit] Mercury
:- module a_plus_b.
:- interface.
:- import_module io.
:- pred main(io::di, io::uo) is det.
:- implementation.
:- import_module int, list, string.
main(!IO) :-
io.read_line_as_string(Result, !IO),
( if
Result = ok(Line),
[AStr, BStr] = string.words(Line),
string.to_int(AStr, A), string.to_int(BStr, B)
then
io.format("%d\n", [i(A + B)], !IO)
else
true
).
[edit] mIRC Scripting Language
alias a+b {
echo -ag $calc($1 + $2)
}
[edit] МК-61/52
С/П + С/П
[edit] ML/I
The two numbers are read from 'standard input' or its equivalent.
MCSKIP "WITH" NL
"" A+B
"" assumes macros on input stream 1, terminal on stream 2
MCSKIP MT,<>
MCINS %.
MCDEF SL SPACES NL AS <MCSET T1=%A1.
MCSET T2=%A2.
%T1+T2.
MCSET S10=0
>
MCSKIP SL WITH *
MCSET S1=1
*MCSET S10=2
[edit] Modula-2
MODULE ab;
IMPORT InOut;
VAR A, B : INTEGER;
BEGIN
InOut.ReadInt (A);
InOut.ReadInt (B);
InOut.WriteInt (A + B, 8);
InOut.WriteLn
END ab.
[edit] MUMPS
ANB
NEW A,B,T,S
READ !,"Input two integers between -1000 and 1000, separated by a space: ",S
SET A=$PIECE(S," ",1),B=$PIECE(S," ",2)
SET T=(A>=-1000)&(A<=1000)&(B>=-1000)&(B<=1000)&(A\1=A)&(B\1=B)
IF T WRITE !,(A+B)
IF 'T WRITE !,"Bad input"
QUIT
[edit] Nemerle
using System;
using System.Console;
using System.Linq;
module AplusB
{
Main() : void
{
WriteLine(ReadLine().Split().Select(int.Parse).Sum());
}
}
[edit] NetRexx
/* NetRexx */
options replace format comments java crossref savelog symbols binary
parse ask a b .
say a '+' b '=' a + b
[edit] newLISP
(println (apply + (map int (parse (read-line)))))
[edit] Nimrod
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
[edit] 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();
};
}
}
}
[edit] Oberon-2
MODULE ab;
IMPORT In, Out;
VAR A, B : INTEGER;
BEGIN
In.Int (A);
In.Int (B);
Out.Int (A + B, 8);
Out.Ln
END ab.
Producing
12 34
46
[edit] OCaml
Scanf.scanf "%d %d" (fun a b -> Printf.printf "%d\n" (a + b))
[edit] OpenEdge/Progress
DEFINE VARIABLE a AS INTEGER NO-UNDO FORMAT "->>>9".
DEFINE VARIABLE b AS INTEGER NO-UNDO FORMAT "->>>9".
IF SESSION:BATCH THEN DO:
INPUT FROM "input.txt".
IMPORT a b.
INPUT CLOSE.
END.
ELSE
UPDATE a b.
MESSAGE a + b VIEW-AS ALERT-BOX
[edit] Openscad
a = 5 + 4;
echo (a);
[edit] Oxygene
// Sum 2 integers read fron standard input
//
// Nigel Galloway - April 16th., 2012
//
namespace aplusb;
interface
uses System.Text.RegularExpressions.*;
type
aplusb = class
public
class method Main;
end;
implementation
class method aplusb.Main;
var
gc: GroupCollection;
m : Match;
begin
m := new Regex('^\s*(?<a>-?[1-9]\d{0,2}|0|-?1000)\s+(?<b>-?[1-9]\d{0,2}|0|-?1000)\s*$').Match(Console.ReadLine());
if m.Success then
begin
gc := m.Groups;
Console.WriteLine("{0} + {1} = {2}", gc['a'].Value, gc['b'].Value, Integer.Parse(gc['a'].Value) + Integer.Parse(gc['b'].Value));
end
else Console.WriteLine("Invalid Input");
end;
end.
Produces:
>aplusb 23 -99 23 + -99 = -76
[edit] Oz
declare
class TextFile from Open.file Open.text end
StdIn = {New TextFile init(name:stdin)}
fun {ReadInt}
{String.toInt {StdIn getS($)}}
end
in
{Show {ReadInt}+{ReadInt}}
[edit] PARI/GP
User input:
input()+input()
File input:
read("file1")+read("file2")
[edit] Pascal
var
a, b: integer;
begin
readln(a, b);
writeln(a + b);
end.
Same with input from file input.txt and output from file output.txt.
var
a, b: integer;
begin
reset(input, 'input.txt');
rewrite(output, 'output.txt');
readln(a, b);
writeln(a + b);
close(input);
close(output);
end.
[edit] Perl
my ($a,$b) = split(/\D+/,<STDIN>);
print "$a $b " . ($a + $b) . "\n";
[edit] Perl 6
say [+] .words for lines
[edit] PHP
fscanf(STDIN, "%d %d\n", $a, $b); //Reads 2 numbers from STDIN
echo ($a + $b) . "\n";
$in = fopen("input.dat", "r");
fscanf($in, "%d %d\n", $a, $b); //Reads 2 numbers from file $in
fclose($in);
$out = fopen("output.dat", "w");
fwrite($out, ($a + $b) . "\n");
fclose($out);
[edit] PicoLisp
(+ (read) (read))
3 4
-> 7
[edit] Piet
The code is fairly straightforward. The individual commands are as follows:
in(num)
in(num)
add
out(num)
[edit] Pike
string line = Stdio.stdin->gets();
sscanf(line, "%d %d", int a, int b);
write(a+b +"\n");
[edit] PL/I
get (a, b);
put (a+b);
[edit] PostScript
(%stdin) (r) file % get stdin
dup
token pop % read A
exch
token pop % read B
add
=
[edit] PowerShell
$a,$b = -split "$input"
[int]$a + [int]$b
This solution does not work interactively, while the following only works interactively:
$a,$b = -split (Read-Host)
[int]$a + [int]$b
[edit] ProDOS
With the math module:
editvar /newvar /value=a /title=Enter an integer:
editvar /newvar /value=b /title=Enter another integer:
editvar /newvar /value=c
do add -a-,-b-=-c-
printline -c-
Without the math module:
editvar /newvar /value=a /title=Enter an integer:
editvar /newvar /value=b /title=Enter another integer:
editvar /newvar /value=c=-a-+-b-
printline -c-
[edit] 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.
[edit] Pure
using system;
printf "%d\n" (x+y) when x,y = scanf "%d %d" end;
[edit] PureBasic
[edit] Console
x$=Input()
a=Val(StringField(x$,1," "))
b=Val(StringField(x$,2," "))
PrintN(str(a+b))
[edit] File
If ReadFile(0,"in.txt")
x$=ReadString(0)
a=Val(StringField(x$,1," "))
b=Val(StringField(x$,2," "))
If OpenFile(1,"out.txt")
WriteString(1,str(a+b))
CloseFile(1)
EndIf
CloseFile(0)
EndIf
[edit] Python
[edit] Console
try: raw_input
except: raw_input = input
print(sum(int(x) for x in raw_input().split()))
[edit] File
a = int(raw_input("Enter integer 1: "))
b = int(raw_input("Enter integer 2: "))
print a + b
[edit] R
sum(scan("", numeric(0), 2))
[edit] Racket
#lang racket
(+ (read) (read))
Or, with additional error checking:
#lang racket
(define a (read))
(unless (number? a) (error 'a+b "number" a))
(define b (read))
(unless (number? b) (error 'a+b "number" b))
(displayln (+ a b))
[edit] REBOL
forever [x: load input print x/1 + x/2]
Sample output:
1 2 3 2 2 4 3 2 5
[edit] Retro
: try ( "-n ) getToken toNumber getToken toNumber + putn ;
try 1 2
[edit] REXX
[edit] version 1, unnormalized
The numbers can be any valid REXX number (integer, fixed point decimal, floating point (with exponential notation, ...).
parse pull a b
say a+b
[edit] version 2, normalizied
If the user entered 4.00000 and wanted to add 5 to that, and expects 9,
then the output needs to be normalized before displaying the result.
Normally, REXX will keep the greatest precision in the results;
adding 4.00000 and 5 will yield 9.00000
parse pull a b
say (a+b)/1 /*dividing by 1 normalizes the REXX number.*/
[edit] version 3, extended precision
Using the numeric digits statement allows more digits to be used, the default is 9.
numeric digits 300
parse pull a b
z=(a+b)/1
say z
[edit] version 4, multiple numbers
This REXX program version adds all the numbers entered (not just two).
numeric digits 1000 /*just in case the user gets ka-razy. */
say 'enter some numbers to be summed:'
parse pull y
many=words(y)
sum=0
do j=1 for many
sum=sum+word(y,j)
end
say 'sum of' many "numbers = " sum/1
[edit] Ruby
puts gets.split.map{|x| x.to_i}.inject{|sum, x| sum + x}
puts gets.split.map(&:to_i).inject(&:+)
[edit] Run BASIC
input, x$
print val(word$(x$,1)) + val(word$(x$,2))
[edit] Scala
println(readLine() split " " take 2 map (_.toInt) sum)
[edit] Scheme
(let* ((x (read))
(y (read)))
(write (+ x y)))
[edit] sed
Sed is for string processing and has no facility for manipulating numbers as numeric values. However, being Turing complete, sed can be coerced into performing mathematics.
: Loop
# All done
/^-*00* /s///
/ -*00*$/s///
t
# Negative Check
/^\(-*\)[0-9].* \1[0-9]/!b Negative
# Create magic lookup table
s/\(.[0-9]*\) \(.[0-9]*\)/\1;987654321000009999000999009909 \2;012345678999990000999000990090/
s/ \(-\)*\(9*;\)/ \10\2/
# Decrement 1st number
s/\([^0]\)\(0*\);[^0]*\1\(.\).*\2\(9*\).* \(.*\)/\3\4 \5/
# Increment 2nd
s/\([^9]\)\(9*\);[^9]*\1\(.\).*\2\(0*\).*/\3\4/
t Loop
: Negative
# Create magic lookup table
s/\(.[0-9]*\) \(.[0-9]*\)/\1;987654321000009999000999009909 \2;987654321000009999000999009909/
# Decrement 1st number
s/\([^0]\)\(0*\);[^0]*\1\(.\).*\2\(9*\).* \(.*\)/\3\4 \5/
# Decrement 2nd
s/\([^0]\)\(0*\);[^0]*\1\(.\).*\2\(9*\).*/\3\4/
t Loop
Another method, based off of this StackExchange answer:
#!/bin/sed -f
# Add a marker in front of each digit, for tracking tens, hundreds, etc.
s/[0-9]/<&/g
# Convert numbers to, in essence, tally marks
s/0//g; s/1/|/g; s/2/||/g; s/3/|||/g; s/4/||||/g; s/5/|||||/g
s/6/||||||/g; s/7/|||||||/g; s/8/||||||||/g; s/9/|||||||||/g
# Multiply by ten for each digit from the back they were.
:tens
s/|</<||||||||||/g
t tens
# We don't want the digit markers any more
s/<//g
# Negative minus negative is the negation of their absolute values.
s/^-\(|*\) *-/-\1/
# Negative plus positive equals positive plus negative, and we want the negative at the back.
s/^-\(|*\) \+\(|*\)$/\2-\1/
# Get rid of any space between the numbers
s/ //g
# A tally on each side can be canceled.
:minus
s/|-|/-/
t minus
s/-$//
# Convert back to digits
:back
s/||||||||||/</g
s/<\([0-9]*\)$/<0\1/g
s/|||||||||/9/g;
s/|||||||||/9/g; s/||||||||/8/g; s/|||||||/7/g; s/||||||/6/g;
s/|||||/5/g; s/||||/4/g; s/|||/3/g; s/||/2/g; s/|/1/g;
s/</|/g
t back
s/^$/0/
[edit] Seed7
$ include "seed7_05.s7i";
const proc: main is func
local
var integer: a is 0;
var integer: b is 0;
begin
read(a);
read(b);
writeln(a + b);
end func;
[edit] Shiny
if (io.line 'stdin').match ~(\d+)\s+(\d+)~
say "$a $b %(a+b)d"
end
[edit] SNOBOL4
Simple-minded solution (literally "two somethings separated by space")
input break(" ") . a " " rem . b
output = a + b
end
"Integer aware" solution:
nums = "0123456789"
input span(nums) . a break(nums) span(nums) . b
output = a + b
end
==Smalltalk=/g s/= 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:
|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.
[edit] SPARK
-- By Jacob Sparre Andersen
-- Validates with SPARK GPL 2010's Examiner/Simplifier
with SPARK_IO; --# inherit SPARK_IO;
--# main_program;
procedure A_Plus_B
--# global in out SPARK_IO.Inputs, SPARK_IO.Outputs;
--# derives SPARK_IO.Inputs from SPARK_IO.Inputs &
--# SPARK_IO.Outputs from SPARK_IO.Inputs, SPARK_IO.Outputs;
is
subtype Small_Integers is Integer range -1_000 .. +1_000;
A, B : Integer;
A_OK, B_OK : Boolean;
begin
SPARK_IO.Get_Integer
(File => SPARK_IO.Standard_Input,
Item => A,
Width => 0,
Read => A_OK);
A_OK := A_OK and A in Small_Integers;
SPARK_IO.Get_Integer
(File => SPARK_IO.Standard_Input,
Item => B,
Width => 0,
Read => B_OK);
B_OK := B_OK and B in Small_Integers;
if A_OK and B_OK then
SPARK_IO.Put_Integer
(File => SPARK_IO.Standard_Output,
Item => A + B,
Width => 4,
Base => 10);
else
SPARK_IO.Put_Line
(File => SPARK_IO.Standard_Output,
Item => "Input data does not match specification.",
Stop => 0);
end if;
end A_Plus_B;
[edit] SQL
SELECT A+B
Example:
SELECT 2+3
This should produce a result set containing the value 5.
Note however that declaration of variables is outside the scope of the ANSI SQL standards, unless by variables you mean tables (which would complicate the example considerably).
[edit] Tcl
scan [gets stdin] "%d %d" x y
puts [expr {$x + $y}]
Alternatively:
puts [tcl::mathop::+ {*}[gets stdin]]
To/from a file:
set in [open "input.txt"]
set out [open "output.txt" w]
scan [gets $in] "%d %d" x y
puts $out [expr {$x + $y}]
close $in
close $out
[edit] TI-83 BASIC, TI-89 BASIC
:Prompt A,B
:Disp A+B
Alternate TI-89 BASIC version (returns the result on the Home screen):
:aplusb(a,b)
:a+b
[edit] TorqueScript
Since torque is not compatible with standard input, I will show the closest to that. It's a function that takes a single string input, that will contain the 2 numbers.
Function aPlusB(%input)
{
return getWord(%input, 0) + getWord(%input, 1);
}
[edit] TUSCRIPT
$$ MODE TUSCRIPT
SET input="1 2"
SET input=SPLIT(input,": :")
SET input=JOIN (input)
SET output=SUM(input)
[edit] UNIX Shell
#!/bin/sh
read a b || exit
echo `expr "$a" + "$b"`
Script "a+b.sh":
#!/bin/bash
read a b || exit
echo $(( a + b ))
Output:
echo 2 3 | ksh a+b.sh
5
[edit] C Shell
set line=$<
set input=($line)
@ sum = $input[1] + $input[2]
echo $sum
[edit] Ursala
Using standard input and output streams:
#import std
#import int
#executable&
main = %zP+ sum:-0+ %zp*FiNCS+ sep` @L
Overwriting a text file named as a command line parameter:
#import std
#import int
#executable -[parameterized]-
main = ~command.files.&h; <.contents:= %zP+ sum:-0+ %zp*FiNCS+ sep` @L+ ~contents>
Creating a new file named after the input file with suffix .out:
#import std
#import int
#executable -[parameterized]-
main =
~command.files.&h; ~&iNC+ file$[
contents: %zP+ sum:-0+ %zp*FiNCS+ sep` @L+ ~contents,
path: ~path; ^|C\~& ~=`.-~; ^|T/~& '.out'!]
[edit] Vala
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);
[edit] VBScript
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
[edit] VHDL
LIBRARY std;
USE std.TEXTIO.all;
entity test is
end entity test;
architecture beh of test is
begin
process
variable line_in, line_out : line;
variable a,b : integer;
begin
readline(INPUT, line_in);
read(line_in, a);
read(line_in, b);
write(line_out, a+b);
writeline(OUTPUT, line_out);
wait; -- needed to stop the execution
end process;
end architecture beh;
[edit] Visual Basic .NET
Module Module1
Sub Main()
Dim s() As String = Nothing
s = Console.ReadLine().Split(" "c)
Console.WriteLine(CInt(s(0)) + CInt(s(1)))
End Sub
End Module
[edit] Whitespace
[edit] X86 Assembly
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.
[edit] XPL0
include c:\cxpl\codes;
int A, B;
[A:= IntIn(0);
B:= IntIn(0);
IntOut(0, A+B);
CrLf(0);
]
[edit] Yorick
a = b = 0;
read, a, b;
write, a + b;
[edit] ZED
(A+B)
comment
(always)
(+) (read) (default-input-port)
(read) (default-input-port)
- Programming Tasks
- Solutions by Programming Task
- 0815
- ABAP
- Ada
- ALGOL 68
- ANTLR
- Java
- Argile
- AutoHotkey
- AutoIt
- AWK
- Batch File
- BASIC
- BASIC256
- BBC BASIC
- Befunge
- Bracmat
- Brainf***
- Brainf*** examples needing attention
- Examples needing attention
- Brat
- Burlesque
- C
- C sharp
- C++
- Clojure
- CoffeeScript
- Common Lisp
- D
- Dc
- Déjà Vu
- Delphi
- DMS
- DWScript
- Eiffel
- Ela
- Elena
- Erlang
- Euler Math Toolbox
- Euphoria
- EGL
- F Sharp
- Factor
- FALSE
- Fantom
- FBSL
- Fish
- Forth
- Fortran
- GML
- Go
- Golfscript
- Gosu
- Groovy
- GUISS
- Haskell
- HicEst
- Icon
- Unicon
- J
- JavaScript
- Julia
- Joy
- Lang5
- Liberty BASIC
- Lisaac
- Logo
- Lua
- Kite
- Maple
- Mathematica
- MATLAB
- Mercury
- MIRC Scripting Language
- МК-61/52
- ML/I
- Modula-2
- MUMPS
- Nemerle
- NetRexx
- NewLISP
- Nimrod
- Objeck
- Oberon-2
- OCaml
- OpenEdge/Progress
- Openscad
- Oxygene
- Oz
- PARI/GP
- Pascal
- Perl
- Perl 6
- PHP
- PicoLisp
- Piet
- Pike
- PL/I
- PostScript
- PowerShell
- ProDOS
- Prolog
- Pure
- PureBasic
- Python
- R
- Racket
- REBOL
- Retro
- REXX
- Ruby
- Run BASIC
- Scala
- Scheme
- Sed
- Seed7
- Shiny
- SNOBOL4
- Smalltalk
- SPARK
- SQL
- Tcl
- TI-83 BASIC
- TI-89 BASIC
- TorqueScript
- TUSCRIPT
- UNIX Shell
- C Shell
- Ursala
- Vala
- VBScript
- VHDL
- Visual Basic .NET
- Whitespace
- X86 Assembly
- XPL0
- Yorick
- ZED

