A+B
![Task](http://static.miraheze.org/rosettacodewiki/thumb/b/ba/Rcode-button-task-crushed.png/64px-Rcode-button-task-crushed.png)
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.
A+B is one of few problems on contests, which traditionally lacks fabula.
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
ABAP
<lang 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.</lang>
Ada
<lang 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;</lang>
Using appropriate user defined types: <lang Ada>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;</lang>
ALGOL 68
Console
<lang algol68>print((read int + read int))</lang> Input:
1 2
Output:
+3
File
<lang algol68>open(stand in, "input.txt", stand in channel); open(stand out, "output.txt", stand out channel); print((read int + read int))</lang> Input "input.txt":
3 4
Output "output.txt":
+7
Argile
<lang Argile>(: Standard input-output streams :) use std, array Cfunc scanf "%d%d" (&val int a) (&val int b) printf "%d\n" (a + b)</lang> <lang Argile>(: 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</lang>
AutoHotkey
<lang AutoHotkey>InputBox, input , A+B, Two integer numbers`, separated by space. StringSplit, output, input, %A_Space% msgbox, % output1 . "+" . output2 "=" output1+output2</lang>
AutoIt
<lang 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 </lang>
AWK
<lang awk>{print $1 + $2}</lang>
Batch File
Prompts version
<lang dos>::aplusb.cmd @echo off setlocal set /p a="A: " set /p b="B: " set /a c=a+b echo %c% endlocal</lang>
All on the commandline version
<lang dos>::aplusb.cmd @echo off setlocal set a=%1 set b=%2 set /a c=a+b echo %c% endlocal</lang>
Formula on the command line version
<lang dos>::aplusb.cmd @echo off setlocal set /a c=%~1 echo %c% endlocal</lang>
Example of 'Formula on the command line version'
>aplusb 123+456 579 >aplusb "1+999" 1000
Parse the input stream version (thanks to Tom Lavedas on alt.msdos.batch.nt)
<lang dos>::aplusb.cmd @echo off setlocal set /p a="Input stream: " call :add %a% echo %res% endlocal goto :eof
- add
set /a res=res+%1 shift if "%1" neq "" goto :add</lang>
Example of 'parse the input stream version'
>aplusb Input stream: 1234 5678 6912 >aplusb Input stream: 123 234 345 456 567 678 789 890 4082
BASIC
<lang qbasic>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</lang>
BBC BASIC
<lang bbc> 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</lang>
That seems overly complicated. What's wrong with: <lang bbc> REPEAT
INPUT LINE "" q$ space% = INSTR(q$," ") PRINT VAL LEFT$(q$,space%-1) + VAL MID$(q$,space%+1) UNTIL FALSE</lang>
Befunge
<lang befunge>&&+.@</lang>
Brainf***
<lang brainf***>,>,[-<+>]<.</lang>
Brat
<lang brat>numbers = g.split[0,1].map(:to_i) p numbers[0] + numbers[1] #Prints the sum of the input</lang>
C
<lang 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;
}</lang> <lang c>// 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;
}</lang>
C#
<lang csharp>using System; using System.Linq;
class Program {
static void Main() { Console.WriteLine(Console.ReadLine().Split().Select(int.Parse).Sum()); }
}</lang>
Another way (not recommended since it does not work with more than two numbers):
<lang csharp>using System;
class Program
{ static void Main() { 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()); Console.ReadLine(); } }</lang>
C++
<lang cpp>// Standard input-output streams
- include <iostream>
using namespace std; int main() {
int a, b; cin >> a >> b; cout << a + b << endl; return 0;
}</lang> <lang cpp>// 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;
}</lang>
Clojure
<lang clojure>(println (+ (Integer/parseInt (read-line)) (Integer/parseInt (read-line)))) 3 4 =>7</lang>
<lang clojure>(eval (read-string (str "(+ " (read-line) " )") )) 3 3 6</lang>
CoffeeScript
<lang html4strict> <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>
</body> </html> </lang>
Common Lisp
<lang lisp>(format t (write-to-string (+ (read) (read))))</lang>
D
As in the Python version.
Console
<lang d>import std.stdio: readln, writeln; import std.conv: to; import std.string: split;
void main() {
auto r = readln().split(); writeln(to!int(r[0]) + to!int(r[1]));
}</lang>
File
<lang d>import std.stdio: writeln, File; import std.conv: to; import std.string: split;
void main() {
auto fin = File("input.txt", "r"); auto fout = File("output.txt", "w"); auto r = fin.readln().split(); fout.writeln(to!int(r[0]) + to!int(r[1]));
}</lang>
Delphi
Console version. <lang delphi> program SUM;
{$APPTYPE CONSOLE}
uses
SysUtils;
var
s1, s2:string;
begin
ReadLn(s1); Readln(s2); Writeln(StrToIntDef(s1, 0) + StrToIntDef(s2,0));
end. </lang>
DMS
<lang 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" )</lang>
Elena
<lang elena>#define basic'* = std'basic'*.
- define text'* = ext'text'*.
- symbol Program =>
[
#var A := basic'Integer. #var B := basic'Integer. text'LineInput >> A >> B. 'program'output << A + B.
]. </lang>
Erlang
<lang 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.
</lang>
Euphoria
<lang 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)</lang>
F#
<lang fsharp>open System let plus = (fun (a:string) (b:string) -> Console.WriteLine(int(a)+int(b))) (Console.ReadLine()) (Console.ReadLine());;</lang>
Factor
<lang factor>USING: math.parser splitting ;
- a+b ( -- )
readln " " split1 [ string>number ] bi@ + number>string print ;</lang>
( scratchpad ) a+b 2 2 4
FALSE
<lang false>[0[^$$'9>'0@>|~]['0-\10*+]#%]n: {read an integer} n;!n;!+.</lang>
Fantom
<lang 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) }
} </lang>
Forth
<lang Forth>pad dup 80 accept evaluate + .</lang>
Fortran
<lang fortran>program a_plus_b
implicit none integer :: a integer :: b
read (*, *) a, b write (*, '(i0)') a + b
end program a_plus_b</lang>
GML
<lang 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)</lang>
Go
<lang Go>package main import (
"fmt"
) func main() {
var a,b int; fmt.Scanf("%d %d", &a, &b); fmt.Printf("%d\n", a+b);
}</lang>
abAdder()
Golfscript
<lang golfscript>~+</lang>
Groovy
<lang 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
}</lang>
Haskell
<lang haskell>main :: IO () main = getLine >>= print . sum . map read . words</lang>
HicEst
A and B are input via edit controls with spinners limiting inputs to +-1000. <lang HicEst>DLG(Edit=A, DNum, MIn=-1000, MAx=1000, E=B, DN, MI=-1000, MA=1000) WRITE(Messagebox, Name) A, B, "Sum = ", A+B</lang>
Icon and Unicon
<lang icon>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</lang>
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: <lang J> 2+3 5</lang>
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 +/. <lang J>+/". (1!:1(3))-.LF</lang> Here's a little script, called "a+b.ijs": <lang J>#!/Applications/j602/bin/jconsole echo +/". (1!:1(3))-.LF exit </lang> Here is the execution of the script: <lang bash>echo 2 3 | ./a+b.ijs 5</lang>
Java
<lang 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 }
}</lang> Object of class Scanner works slow enough, because of that contestants prefer to avoid its use. Often, longer solution works faster and easily scales to problems.
<lang java>import java.io.*; 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()); }
}</lang>
<lang java>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"); } } }</lang>
JavaScript
<lang html4strict><html> <body>
<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></lang>
Joy
Console
<lang Joy>get get +.</lang>
File
<lang Joy>"input.txt" include "output.txt" "w" fopen get get + fput pop.</lang>
Liberty BASIC
<lang lb>input, n$ print eval(word$(n$,1);" + ";word$(n$,2))</lang>
Lisaac
<lang lisaac>Section Header
+ name := A_PLUS_B
Section Public
- main <- ( (IO.read_integer; IO.last_integer) + (IO.read_integer; IO.last_integer) ).println;</lang>
Logo
<lang logo>show apply "sum readlist</lang>
Lua
<lang Lua>a,b = io.read("*number", "*number") print(a+b)</lang>
Kite
<lang Kite>
- !/usr/bin/kite
import "System.file";
in = System.file.stdin; line = in|readline; while(not (line is null)) [
arry = line|split(" "); result = (arry[0])|int + (arry[1])|int; result|print;
line = in|readline;
]; </lang>
Output: <lang Kite> $ kite a_plus_b.kt <<EOF 5 6 EOF 11 $ </lang>
Mathematica
Interactive in a notebook <lang Mathematica>Input[] + Input[]</lang>
MATLAB
<lang 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</lang>
Modula-2
<lang modula2>MODULE ab;
IMPORT InOut;
VAR A, B : INTEGER;
BEGIN
InOut.ReadInt (A); InOut.ReadInt (B); InOut.WriteInt (A + B, 8); InOut.WriteLn
END ab.</lang>
MUMPS
<lang 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</lang>
newLISP
<lang newLISP>(println (apply + (map int (parse (read-line))))) </lang>
Objeck
<lang objeck>bundle Default {
class Hello { function : Main(args : String[]) ~ Nil { line := IO.Console->GetInstance()->ReadString()->Trim(); split := line->Find(' '); if(split > 0) { l := line->SubString(split); r := line->SubString(split + 1, line->Size() - split - 1); (l->ToInt() + r->ToInt())->PrintLine(); }; } }
}</lang>
Nimrod
A+B: <lang nimrod> import strutils, os
echo parseInt(paramStr(1)) + parseInt(paramStr(2)) </lang>
Arbitrary number of arguments: <lang nimrod> import strutils, os var sum = 0 for i in countup(1, paramCount()):
sum = sum + parseInt(paramStr(i))
echo sum </lang>
Oberon-2
<lang oberon2>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.</lang> Producing
12 34 46
OCaml
<lang ocaml>Scanf.scanf "%d %d" (fun a b -> Printf.printf "%d\n" (a + b))</lang>
OpenEdge/Progress
<lang 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":U. IMPORT a b. INPUT CLOSE.
END. ELSE
UPDATE a b.
MESSAGE a + b VIEW-AS ALERT-BOX</lang>
Oz
<lang 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}}</lang>
PARI/GP
User input: <lang parigp>input()+input()</lang>
File input: <lang parigp>read("file1")+read("file2")</lang>
Pascal
<lang pascal>var
a, b: integer;
begin
readln(a, b); writeln(a + b);
end.</lang> Same with input from file input.txt and output from file output.txt. <lang pascal>var
a, b: integer;
begin
reset(input, 'input.txt'); rewrite(output, 'output.txt'); readln(a, b); writeln(a + b); close(input); close(output);
end.</lang>
Perl
<lang Perl>my ($a,$b) = split(/\D+/,<STDIN>); print "$a $b " . ($a + $b) . "\n";</lang>
Perl 6
<lang perl6>my ($a,$b) = $*IN.get.words; say $a+$b;</lang>
or, using the reduction meta operator: <lang perl6>say [+] $*IN.get.words</lang>
PHP
<lang php>fscanf(STDIN, "%d %d\n", $a, $b); //Reads 2 numbers from STDIN echo ($a + $b) . "\n";</lang> <lang php>$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);</lang>
PicoLisp
<lang PicoLisp>(+ (read) (read)) 3 4 -> 7</lang>
Piet
The code is fairly straightforward. The individual commands are as follows: <lang text>in(num) in(num) add out(num)</lang>
PostScript
<lang postscript>(%stdin) (r) file % get stdin dup token pop % read A exch token pop % read B add =</lang>
PowerShell
<lang powershell>$a,$b = -split "$input" [int]$a + [int]$b</lang> This solution does not work interactively, while the following only works interactively: <lang powershell>$a,$b = -split (Read-Host) [int]$a + [int]$b</lang>
Prolog
Works with SWI-Prolog <lang 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).</lang>
output : <lang Prolog>?- plus. |: 4 5 9 true.</lang>
Pure
<lang pure>using system; printf "%d\n" (x+y) when x,y = scanf "%d %d" end;</lang>
PureBasic
Console
<lang PureBasic>x$=Input() a=Val(StringField(x$,1," ")) b=Val(StringField(x$,2," ")) PrintN(str(a+b))</lang>
File
<lang PureBasic>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 </lang>
Python
Console
<lang python>try: raw_input except: raw_input = input
print(sum(int(x) for x in raw_input().split()))</lang>
File
<lang python>fin = open("input.txt", "r") fout = open("output.txt","w") r = fin.readline().split() fout.write(str(int(r[0]) + int(r[1])))</lang>
R
<lang r>sum(scan("", numeric(0), 2))</lang>
Racket
<lang scheme>
- lang racket
(define (do-sum)
(display "Give a number: ") (let ((a (string->number (read-line)))) (display "Give another number: ") (let ((b (string->number (read-line)))) (if (and (number? a) (number? b)) (printf "Sum = ~a\n" (+ a b)) (display "a or b is not a number!")))))
(do-sum) </lang>
REBOL
<lang rebol>forever [x: load input print x/1 + x/2]</lang>
Sample output:
1 2 3 2 2 4 3 2 5
REXX
<lang rexx>pull a b say a+b</lang>
Retro
<lang Retro>: try ( "-n ) getToken toNumber getToken toNumber + putn ;</lang>
<lang Retro>try 1 2</lang>
Ruby
<lang ruby>puts gets.split.map{|x| x.to_i}.inject{|sum, x| sum + x}</lang>
<lang ruby>puts gets.split.map(&:to_i).inject(&:+)</lang>
Scala
<lang scala>println(readLine() split " " take 2 map (_.toInt) sum)</lang>
Scheme
<lang scheme>(write (+ (read) (read)))</lang>
sed
<lang sed>: 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</lang>
Shiny
<lang shiny>if (io.line 'stdin').match ~(\d+)\s+(\d+)~
say "$a $b %(a+b)d"
end</lang>
SNOBOL4
Simple-minded solution (literally "two somethings separated by space") <lang snobol> input break(" ") . a " " rem . b output = a + b end</lang>
"Integer aware" solution: <lang snobol> nums = "0123456789" input span(nums) . a break(nums) span(nums) . b output = a + b end</lang>
SPARK
<lang Ada>-- 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;</lang>
SQL
<lang sql>select A+B</lang>
Example: <lang sql>select 2+3</lang>
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).
Tcl
<lang tcl>scan [gets stdin] "%d %d" x y puts [expr {$x + $y}]</lang> Alternatively: <lang tcl>puts [tcl::mathop::+ {*}[gets stdin]]</lang> To/from a file: <lang tcl>set in [open "input.txt"] set out [open "output.txt" w] scan [gets $in] "%d %d" x y puts $out [expr {$x + $y}] close $in close $out</lang>
TI-83 BASIC , TI-89 BASIC
<lang ti83b>:Prompt A,B
- Disp A+B</lang>
TUSCRIPT
<lang tuscript> $$ MODE TUSCRIPT SET input="1 2" SET input=SPLIT(input,": :") SET input=JOIN (input) SET output=SUM(input) </lang>
UNIX Shell
<lang sh>#!/bin/sh read a b echo `expr $a + $b`</lang>
Script "a+b.sh": <lang bash>#!/bin/bash read a b echo $(( a + b ))</lang> Output: <lang bash>echo 2 3 | ./a+b.sh 5</lang>
<lang bash>read a b && echo $((a + b))</lang>
Ursala
Using standard input and output streams: <lang Ursala>#import std
- import int
- executable&
main = %zP+ sum:-0+ %zp*FiNCS+ sep` @L</lang> Overwriting a text file named as a command line parameter: <lang Ursala>#import std
- import int
- executable -[parameterized]-
main = ~command.files.&h; <.contents:= %zP+ sum:-0+ %zp*FiNCS+ sep` @L+ ~contents></lang>
Creating a new file named after the input file with suffix .out
:
<lang Ursala>#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'!]</lang>
X86 Assembly
<lang asm>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</lang> 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.
Yorick
<lang yorick>a = b = 0; read, a, b; write, a + b;</lang>
Visual Basic .NET
<lang vbnet> 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 </lang>
- Programming Tasks
- Solutions by Programming Task
- ABAP
- Ada
- ALGOL 68
- Argile
- AutoHotkey
- AutoIt
- AWK
- Batch File
- BASIC
- BBC BASIC
- Befunge
- Brainf***
- Brainf*** examples needing attention
- Examples needing attention
- Brat
- C
- C sharp
- C++
- Clojure
- CoffeeScript
- Common Lisp
- D
- Delphi
- DMS
- Elena
- Erlang
- Euphoria
- F Sharp
- Factor
- FALSE
- Fantom
- Forth
- Fortran
- GML
- Go
- Golfscript
- Groovy
- Haskell
- HicEst
- Icon
- Unicon
- J
- Java
- JavaScript
- Joy
- Liberty BASIC
- Lisaac
- Logo
- Lua
- Kite
- Mathematica
- MATLAB
- Modula-2
- MUMPS
- NewLISP
- Objeck
- Nimrod
- Oberon-2
- OCaml
- OpenEdge/Progress
- Oz
- PARI/GP
- Pascal
- Perl
- Perl 6
- PHP
- PicoLisp
- Piet
- PostScript
- PowerShell
- Prolog
- Pure
- PureBasic
- Python
- R
- Racket
- REBOL
- REXX
- Retro
- Ruby
- Scala
- Scheme
- Sed
- Shiny
- SNOBOL4
- SPARK
- SQL
- Tcl
- TI-83 BASIC
- TI-89 BASIC
- TUSCRIPT
- UNIX Shell
- Ursala
- X86 Assembly
- Yorick
- Visual Basic .NET