A+B

From Rosetta Code
Revision as of 18:09, 16 June 2010 by Robin (talk | contribs)
Task
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.

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


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>

ALGOL 68

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

Console

<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

Translation of: C
Works with: Argile version 1.0.0

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

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>

Befunge

<lang befunge>&&+.@</lang>

C

<lang c>// Standard input-output streams

  1. 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

  1. 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 cpp>// Standard input-output streams

  1. 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

  1. 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>

C_sharp

<lang csharp>using System.IO;

class plus { public static void Main(string[] args) { int a,b; { StreamReader reader = new StreamReader("plus.in"); a = int.Parse(reader.ReadLine()); b = int.Parse(reader.ReadLine()); StreamWriter writer = new StreamWriter("plus.out"); writer.WriteLine(a+b); writer.Close(); } } }</lang>

Clojure

<lang clojure> (println (+ (Integer/parseInt (read-line)) (Integer/parseInt (read-line)))) 3 4 =>7 </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>

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>

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>: 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>

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>

GolfScript

<lang golfscript>~+</lang>

Haskell

<lang haskell>sum' :: [Char] -> Int sum' = sum . map read . words

main = getLine >>= (\xs -> print $ sum' xs)</lang>

Icon and Unicon

Icon

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

Unicon

The Icon solution also works in Unicon.

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

Works with: Firefox version 3

<lang html4strict><html> <body>

<script type='text/javascript'>

   var input = window.prompt('enter two integers, separated by whitespace',);
   document.getElementById('input').innerHTML = input;
   var sum = input.split(/\s+/).reduce( function(sum, str) {return sum + parseInt(str)}, 0);
   document.getElementById('output').innerHTML = sum;

</script> </body> </html></lang>

<lang logo>show apply "sum readlist</lang>

Lua

<lang Lua>a,b = io.read("*number", "*number") print(a+b)</lang>

Mathematica

Interactive in a notebook

<lang Mathematica>Input[] + Input[]</lang>

MATLAB

Completely vectorized version: <lang MATLAB>function APlusB()

   disp(sum( str2num(input('Input Stream: ','s')) ));
   

end</lang>

A little unvectorized for clarity. <lang MATLAB>function APlusB()

   inputStream = input('Input Stream: ','s');
   disp(sum( str2num(inputStream) ));
   

end</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>

OCaml

<lang ocaml>Scanf.scanf "%d %d" (fun a b -> Printf.printf "%d\n" (a + b))</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>

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>

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>

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>r = raw_input().split() print int(r[0]) + int(r[1])</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>

Ruby

<lang ruby>puts gets.split.map{|x| x.to_i}.inject{|sum, x| sum + x}</lang>

Works with: Ruby version 1.8.7+

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

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>

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>

UNIX Shell

Script "a+b.sh": <lang bash>#!/bin/sh read a b echo $(( a + b ))</lang> Output: <lang bash>echo 2 3 | ./a+b.sh 5</lang>

Ursala

Using standard input and output streams: <lang Ursala>#import std

  1. import int
  1. executable&

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

  1. import int
  1. 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

  1. import int
  1. executable -[parameterized]-

main =

~command.files.&h; ~&iNC+ file$[

  contents: %zP+ sum:-0+ %zp*FiNCS+ sep` @L+ ~contents,
  path: ~path; ^|C\~& ~=`.-~; ^|T/~& '.out'!]</lang>