Input/Output for pairs of numbers: Difference between revisions
(Added XPL0 example.) |
(Added Easylang) |
||
(9 intermediate revisions by 8 users not shown) | |||
Line 23: | Line 23: | ||
{{trans|Python}} |
{{trans|Python}} |
||
< |
<syntaxhighlight lang="11l">F do_stuff(a, b) |
||
R a + b |
R a + b |
||
Line 29: | Line 29: | ||
L 1..t |
L 1..t |
||
V (a, b) = input().split(‘ ’).map(Int) |
V (a, b) = input().split(‘ ’).map(Int) |
||
print(do_stuff(a, b))</ |
print(do_stuff(a, b))</syntaxhighlight> |
||
=={{header|Action!}}== |
=={{header|Action!}}== |
||
< |
<syntaxhighlight lang="action!">INT FUNC CalcSum(CHAR ARRAY s) |
||
INT sum,i |
INT sum,i |
||
CHAR ARRAY tmp(100) |
CHAR ARRAY tmp(100) |
||
Line 65: | Line 65: | ||
PrintIE(sums(i)) |
PrintIE(sums(i)) |
||
OD |
OD |
||
RETURN</ |
RETURN</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Input_Output_for_pairs_of_numbers.png Screenshot from Atari 8-bit computer] |
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Input_Output_for_pairs_of_numbers.png Screenshot from Atari 8-bit computer] |
||
Line 85: | Line 85: | ||
=={{header|Ada}}== |
=={{header|Ada}}== |
||
There can be newlines before or between numbers. The pairs may be on separate lines or the same line. |
There can be newlines before or between numbers. The pairs may be on separate lines or the same line. |
||
< |
<syntaxhighlight lang="ada">with Ada.Text_IO; use Ada.Text_IO; |
||
with Ada.Integer_Text_IO; use Ada.Integer_Text_IO; |
with Ada.Integer_Text_IO; use Ada.Integer_Text_IO; |
||
Line 100: | Line 100: | ||
New_Line; |
New_Line; |
||
end loop; |
end loop; |
||
end Main;</ |
end Main;</syntaxhighlight> |
||
{{output}} |
{{output}} |
||
Output using the example input: |
Output using the example input: |
||
Line 113: | Line 113: | ||
=={{header|ALGOL 68}}== |
=={{header|ALGOL 68}}== |
||
Simple version - there can be newlines before or between the numbers |
Simple version - there can be newlines before or between the numbers |
||
< |
<syntaxhighlight lang="algol68"># read a number from stand in then read and add that many pairs of numbers from stand in # |
||
# and write the sum to stand out. If non integer data is supplied, a runtime error will occur # |
# and write the sum to stand out. If non integer data is supplied, a runtime error will occur # |
||
TO ( INT n; read( ( n, newline ) ); n ) DO |
TO ( INT n; read( ( n, newline ) ); n ) DO |
||
Line 120: | Line 120: | ||
print( ( a + b, newline ) ) |
print( ( a + b, newline ) ) |
||
OD |
OD |
||
</syntaxhighlight> |
|||
</lang> |
|||
Strict version - the pairs of numbers must appear on the same line. |
Strict version - the pairs of numbers must appear on the same line. |
||
< |
<syntaxhighlight lang="algol68"> |
||
# read a number from stand in then read and add that many pairs of numbers from stand in # |
# read a number from stand in then read and add that many pairs of numbers from stand in # |
||
# and write the sum to stand out. If non integer data is supplied, a runtime error will occur # |
# and write the sum to stand out. If non integer data is supplied, a runtime error will occur # |
||
Line 141: | Line 141: | ||
get( numbers, ( a, b ) ); |
get( numbers, ( a, b ) ); |
||
print( ( a + b, newline ) ) |
print( ( a + b, newline ) ) |
||
OD</ |
OD</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 150: | Line 150: | ||
+10 |
+10 |
||
</pre> |
</pre> |
||
=={{header|Applesoft BASIC}}== |
|||
<syntaxhighlight lang="gwbasic"> 100 GOSUB 230"INPUT LINE" |
|||
110 LET N = VAL (L$) - 1 |
|||
120 IF N < 0 THEN END |
|||
130 DIM SUM(N) |
|||
140 FOR I = 0 TO N |
|||
150 GOSUB 330"SUM PAIR FROM INPUT LINE" |
|||
160 LET SUM(I) = S |
|||
170 NEXT I |
|||
190 FOR I = 0 TO N |
|||
200 PRINT SUM(I) |
|||
210 NEXT |
|||
220 END |
|||
230 LET L$ = "" |
|||
240 LET C$ = "" |
|||
250 FOR C = 0 TO 1 STEP 0 |
|||
260 LET L$ = L$ + C$ |
|||
270 GET C$ |
|||
280 PRINT CHR$ (0)C$; |
|||
290 LET C = C$ = CHR$ (13) |
|||
300 NEXT C |
|||
310 LET C = FRE (0) |
|||
320 RETURN |
|||
330 GOSUB 230"INPUT LINE" |
|||
340 FOR C = 1 TO LEN(L$) |
|||
350 IF MID$(L$, C, 1) <> " " THEN NEXT C |
|||
360 S = VAL(MID$(L$, 1, C - 1)) + VAL(MID$(L$, C + 1)) |
|||
370 RETURN</syntaxhighlight> |
|||
'''Input''' |
|||
<pre> |
|||
5 |
|||
1 2 |
|||
10 20 |
|||
-3 5 |
|||
100 2 |
|||
5 5 |
|||
</pre> |
|||
{{out}} |
|||
<pre> |
|||
3 |
|||
30 |
|||
2 |
|||
102 |
|||
10 |
|||
</pre> |
|||
=={{header|Arturo}}== |
|||
<syntaxhighlight lang="arturo">printNumbers: function [num]-> |
|||
print [num\0 "+" num\1 "=" num\0 + num\1] |
|||
lineCount: to :integer strip input "" |
|||
do.times:lineCount [ |
|||
numbers: to [:integer] split.words input "" |
|||
printNumbers numbers |
|||
]</syntaxhighlight> |
|||
{{out}} |
|||
<pre>3 |
|||
2 10 |
|||
2 + 10 = 12 |
|||
4 5 |
|||
4 + 5 = 9 |
|||
-123 45 |
|||
-123 + 45 = -78</pre> |
|||
=={{header|AWK}}== |
=={{header|AWK}}== |
||
< |
<syntaxhighlight lang="awk">NR == 1 {n=$1; next} |
||
NR > n+1 {exit} |
NR > n+1 {exit} |
||
{print $1+$2}</ |
{print $1+$2}</syntaxhighlight> |
||
=={{header|Batch File}}== |
=={{header|Batch File}}== |
||
< |
<syntaxhighlight lang="dos"> |
||
@echo off |
@echo off |
||
setlocal enabledelayedexpansion |
setlocal enabledelayedexpansion |
||
Line 172: | Line 241: | ||
for /l %%i in (1,1,%pairs%) do echo !sum%%i! |
for /l %%i in (1,1,%pairs%) do echo !sum%%i! |
||
pause>nul |
pause>nul |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{in}} |
{{in}} |
||
<pre> |
<pre> |
||
Line 193: | Line 262: | ||
=={{header|BBC BASIC}}== |
=={{header|BBC BASIC}}== |
||
The specification is a bit ambiguous, but I understood it as wanting us to read all the numbers in <i>first</i> and then print all the sums. This program does that. It could be a couple of lines shorter if we were allowed to use a comma instead of a space as separator. |
The specification is a bit ambiguous, but I understood it as wanting us to read all the numbers in <i>first</i> and then print all the sums. This program does that. It could be a couple of lines shorter if we were allowed to use a comma instead of a space as separator. |
||
< |
<syntaxhighlight lang="bbcbasic">INPUT n% |
||
DIM pairs%(n% - 1, 1) |
DIM pairs%(n% - 1, 1) |
||
FOR i% = 0 TO n% - 1 |
FOR i% = 0 TO n% - 1 |
||
Line 202: | Line 271: | ||
FOR i% = 0 TO n% - 1 |
FOR i% = 0 TO n% - 1 |
||
PRINT pairs%(i%, 0) + pairs%(i%, 1) |
PRINT pairs%(i%, 0) + pairs%(i%, 1) |
||
NEXT</ |
NEXT</syntaxhighlight> |
||
With the sample inputs: |
With the sample inputs: |
||
<pre>?5 |
<pre>?5 |
||
Line 217: | Line 286: | ||
=={{header|C}}== |
=={{header|C}}== |
||
< |
<syntaxhighlight lang="c">#include <stdio.h> |
||
#include <stdlib.h> |
#include <stdlib.h> |
||
Line 236: | Line 305: | ||
return 0; |
return 0; |
||
}</ |
}</syntaxhighlight> |
||
Output for example input |
Output for example input |
||
Line 249: | Line 318: | ||
=={{header|C sharp}}== |
=={{header|C sharp}}== |
||
< |
<syntaxhighlight lang="csharp">using System; |
||
using static System.Linq.Enumerable; |
using static System.Linq.Enumerable; |
||
Line 261: | Line 330: | ||
} |
} |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 273: | Line 342: | ||
=={{header|C++}}== |
=={{header|C++}}== |
||
< |
<syntaxhighlight lang="cpp">#include <iostream> |
||
#include <vector> |
#include <vector> |
||
using namespace std; |
using namespace std; |
||
Line 297: | Line 366: | ||
cout << doStuff(list[j].first, list[j].second) << endl;; |
cout << doStuff(list[j].first, list[j].second) << endl;; |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
Run as per given input |
Run as per given input |
||
Line 318: | Line 387: | ||
=={{header|D}}== |
=={{header|D}}== |
||
This works with any number of integers on lines. |
This works with any number of integers on lines. |
||
< |
<syntaxhighlight lang="d">void main() { |
||
import std.stdio, std.string, std.conv, std.algorithm; |
import std.stdio, std.string, std.conv, std.algorithm; |
||
foreach (immutable _; 0 .. readln.strip.to!uint) |
foreach (immutable _; 0 .. readln.strip.to!uint) |
||
readln.split.to!(int[]).sum.writeln; |
readln.split.to!(int[]).sum.writeln; |
||
}</ |
}</syntaxhighlight> |
||
=={{header|EasyLang}}== |
|||
<syntaxhighlight> |
|||
n = number input |
|||
for i to n |
|||
a[] = number strsplit input " " |
|||
print a[1] + a[2] |
|||
. |
|||
input_data |
|||
5 |
|||
1 2 |
|||
10 20 |
|||
-3 5 |
|||
100 2 |
|||
5 5 |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
3 |
|||
30 |
|||
2 |
|||
102 |
|||
10 |
|||
</pre> |
|||
=={{header|Factor}}== |
=={{header|Factor}}== |
||
< |
<syntaxhighlight lang="factor"> |
||
USING: io math.parser prettyprint sequences splitting ; |
USING: io math.parser prettyprint sequences splitting ; |
||
IN: rosetta-code.pair-output |
IN: rosetta-code.pair-output |
||
Line 335: | Line 429: | ||
MAIN: main |
MAIN: main |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 347: | Line 441: | ||
=={{header|Fortran}}== |
=={{header|Fortran}}== |
||
{{works with|Fortran|95 and later}} |
{{works with|Fortran|95 and later}} |
||
< |
<syntaxhighlight lang="fortran">program i_o_pairs |
||
implicit none |
implicit none |
||
Line 362: | Line 456: | ||
write(*, "(i0)") sum(pairs, 2) |
write(*, "(i0)") sum(pairs, 2) |
||
end program</ |
end program</syntaxhighlight> |
||
=={{header|FreeBASIC}}== |
=={{header|FreeBASIC}}== |
||
< |
<syntaxhighlight lang="freebasic">' FB 1.05.0 Win64 |
||
Dim As UInteger n |
Dim As UInteger n |
||
Line 379: | Line 473: | ||
Print Str(sums(i)) |
Print Str(sums(i)) |
||
Next |
Next |
||
Sleep</ |
Sleep</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 396: | Line 490: | ||
10 |
10 |
||
</pre> |
</pre> |
||
=={{header|Free Pascal}}== |
|||
''See [[#Pascal|Pascal]]'' |
|||
=={{header|Go}}== |
=={{header|Go}}== |
||
< |
<syntaxhighlight lang="go">package main |
||
import ( |
import ( |
||
Line 420: | Line 517: | ||
fmt.Println(a + b) |
fmt.Println(a + b) |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Haskell}}== |
=={{header|Haskell}}== |
||
This solution will actually add any number of integers placed on each line. Additionally, after removing the bits of code that cut out the specified number of lines, the solution will sum any number of lines of integers. |
This solution will actually add any number of integers placed on each line. Additionally, after removing the bits of code that cut out the specified number of lines, the solution will sum any number of lines of integers. |
||
< |
<syntaxhighlight lang="haskell">main = do |
||
contents <- getContents |
contents <- getContents |
||
let numberOfLines = read.head.lines$ contents |
let numberOfLines = read.head.lines$ contents |
||
nums = map (map read.words).take numberOfLines.tail.lines$ contents |
nums = map (map read.words).take numberOfLines.tail.lines$ contents |
||
sums = map sum nums |
sums = map sum nums |
||
mapM_ print sums</ |
mapM_ print sums</syntaxhighlight> |
||
=={{header|J}}== |
=={{header|J}}== |
||
<syntaxhighlight lang="j"> |
|||
<lang J> |
|||
$ cat <<EOF | jconsole -js '([: exit 0: [: smoutput [: ,. [: ({. {. }.) [: (+/"1) [: (0&".;._2) (1!:1)) 3' |
$ cat <<EOF | jconsole -js '([: exit 0: [: smoutput [: ,. [: ({. {. }.) [: (+/"1) [: (0&".;._2) (1!:1)) 3' |
||
> 5 |
> 5 |
||
Line 447: | Line 544: | ||
102 |
102 |
||
10 |
10 |
||
</syntaxhighlight> |
|||
</lang> |
|||
Considerably simpler than [[http://rosettacode.org/wiki/Input/Output_for_Lines_of_Text#J|see explanation]] output for lines of text, this sentence is a single fork. J pads the numeric arrays of 0&".;._2 (numbers cut) with 0 . We form the +/"1 (row sums), then take the sum of the first row of the beheaded sums ({. {. }.) for display. ,. (raveled items) reshapes the vector into a column-vector shaped matrix. And the [: (cap) causes the monadic form of the verb to cap's right. |
Considerably simpler than [[http://rosettacode.org/wiki/Input/Output_for_Lines_of_Text#J|see explanation]] output for lines of text, this sentence is a single fork. J pads the numeric arrays of 0&".;._2 (numbers cut) with 0 . We form the +/"1 (row sums), then take the sum of the first row of the beheaded sums ({. {. }.) for display. ,. (raveled items) reshapes the vector into a column-vector shaped matrix. And the [: (cap) causes the monadic form of the verb to cap's right. |
||
=={{header|Java}}== |
=={{header|Java}}== |
||
< |
<syntaxhighlight lang="java">import java.util.Scanner; |
||
public class Main { |
public class Main { |
||
Line 471: | Line 568: | ||
} |
} |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
=={{header|jq}}== |
=={{header|jq}}== |
||
Line 478: | Line 575: | ||
The solution below assumes the input is in a file named input.txt, and is quite lenient about the presentation of the numbers. For example, it does not require that each pair of numbers be presented on the same line. |
The solution below assumes the input is in a file named input.txt, and is quite lenient about the presentation of the numbers. For example, it does not require that each pair of numbers be presented on the same line. |
||
<syntaxhighlight lang="sh"> |
|||
<lang sh> |
|||
< input.txt jq -n ' |
< input.txt jq -n ' |
||
input as $n |
input as $n |
||
Line 486: | Line 583: | ||
| [input,input] | add |
| [input,input] | add |
||
end' |
end' |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 497: | Line 594: | ||
=={{header|Julia}}== |
=={{header|Julia}}== |
||
< |
<syntaxhighlight lang="julia">parseints() = (a = split(strip(readline()), r"\s+"); map(x -> parse(Int, x), a)) |
||
const lines = parseints()[1] |
const lines = parseints()[1] |
||
Line 504: | Line 601: | ||
println(sum(parseints())) |
println(sum(parseints())) |
||
end |
end |
||
</ |
</syntaxhighlight>{{out}} |
||
<pre> |
<pre> |
||
3 |
3 |
||
Line 516: | Line 613: | ||
=={{header|Kotlin}}== |
=={{header|Kotlin}}== |
||
< |
<syntaxhighlight lang="scala">// version 1.0.6 |
||
import java.util.Scanner |
import java.util.Scanner |
||
Line 531: | Line 628: | ||
println() |
println() |
||
for (i in 0 until n) println(x[i] + y[i]) |
for (i in 0 until n) println(x[i] + y[i]) |
||
}</ |
}</syntaxhighlight> |
||
Sample input/output: |
Sample input/output: |
||
{{out}} |
{{out}} |
||
Line 551: | Line 648: | ||
=={{header|Lua}}== |
=={{header|Lua}}== |
||
This solution will sum any number of space-separated numbers per input line, assuming the user won't input too many to store in the available RAM. |
This solution will sum any number of space-separated numbers per input line, assuming the user won't input too many to store in the available RAM. |
||
< |
<syntaxhighlight lang="lua">local intTab, numLines, sum = {}, io.read() |
||
for i = 1, numLines do |
for i = 1, numLines do |
||
sum = 0 |
sum = 0 |
||
Line 557: | Line 654: | ||
table.insert(intTab, sum) |
table.insert(intTab, sum) |
||
end |
end |
||
for _, result in pairs(intTab) do print(result) end</ |
for _, result in pairs(intTab) do print(result) end</syntaxhighlight> |
||
=={{header|Nim}}== |
=={{header|Nim}}== |
||
< |
<syntaxhighlight lang="nim">import sequtils, strutils |
||
let lineCount = stdin.readLine.parseInt() |
let lineCount = stdin.readLine.parseInt() |
||
Line 568: | Line 665: | ||
assert fields.len == 2 |
assert fields.len == 2 |
||
let pair = fields.map(parseInt) |
let pair = fields.map(parseInt) |
||
echo pair[0] + pair[1]</ |
echo pair[0] + pair[1]</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
Line 580: | Line 677: | ||
=={{header|OCaml}}== |
=={{header|OCaml}}== |
||
< |
<syntaxhighlight lang="ocaml">let () = |
||
let n = int_of_string (input_line stdin) in |
let n = int_of_string (input_line stdin) in |
||
for i = 1 to n do |
for i = 1 to n do |
||
Line 591: | Line 688: | ||
| _ -> |
| _ -> |
||
raise (Invalid_argument "wrong input") |
raise (Invalid_argument "wrong input") |
||
done</ |
done</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 613: | Line 710: | ||
Interestingly, this task is not possible to implement directly in GP, since <code>input()</code>, like the gp REPL itself, ignores spaces. One must use PARI: |
Interestingly, this task is not possible to implement directly in GP, since <code>input()</code>, like the gp REPL itself, ignores spaces. One must use PARI: |
||
< |
<syntaxhighlight lang="c">#include <stdio.h> |
||
#include <stdlib.h> |
#include <stdlib.h> |
||
#include <pari/pari.h> |
#include <pari/pari.h> |
||
Line 646: | Line 743: | ||
pari_printf("%Ps", f); |
pari_printf("%Ps", f); |
||
return 0; |
return 0; |
||
}</ |
}</syntaxhighlight> |
||
Of course for such a simple task this has very little advantage over C, but it does demonstrate the general principle. |
Of course for such a simple task this has very little advantage over C, but it does demonstrate the general principle. |
||
=={{header|Pascal}}== |
|||
<syntaxhighlight lang="pascal">program inputOutputForPairsOfNumbers(input, output); |
|||
var |
|||
lines: integer; |
|||
x: integer; |
|||
y: integer; |
|||
begin |
|||
readLn(lines); |
|||
for lines := 1 to lines do |
|||
begin |
|||
readLn(x, y); |
|||
writeLn(x + y) |
|||
end |
|||
end.</syntaxhighlight> |
|||
{{out}} |
|||
3 |
|||
30 |
|||
2 |
|||
102 |
|||
10 |
|||
=={{header|Perl}}== |
=={{header|Perl}}== |
||
Reads from STDIN, added any pair of numbers. |
Reads from STDIN, added any pair of numbers. |
||
< |
<syntaxhighlight lang="perl">$n = scalar <>; |
||
for (1..$n) { |
for (1..$n) { |
||
($a,$b) = split ' ', <>; |
($a,$b) = split ' ', <>; |
||
print $a + $b . "\n"; |
print $a + $b . "\n"; |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Phix}}== |
=={{header|Phix}}== |
||
<!--< |
<!--<syntaxhighlight lang="phix">(notonline)--> |
||
<span style="color: #008080;">without</span> <span style="color: #008080;">js</span> <span style="color: #000080;font-style:italic;">-- (file i/o)</span> |
<span style="color: #008080;">without</span> <span style="color: #008080;">js</span> <span style="color: #000080;font-style:italic;">-- (file i/o)</span> |
||
<span style="color: #004080;">string</span> <span style="color: #000000;">line</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">gets</span><span style="color: #0000FF;">(</span><span style="color: #000000;">0</span><span style="color: #0000FF;">)</span> |
<span style="color: #004080;">string</span> <span style="color: #000000;">line</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">gets</span><span style="color: #0000FF;">(</span><span style="color: #000000;">0</span><span style="color: #0000FF;">)</span> |
||
Line 678: | Line 796: | ||
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"===\n"</span><span style="color: #0000FF;">)</span> |
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"===\n"</span><span style="color: #0000FF;">)</span> |
||
<span style="color: #7060A8;">pp</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)</span> |
<span style="color: #7060A8;">pp</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)</span> |
||
<!--</ |
<!--</syntaxhighlight>--> |
||
{{out}} |
{{out}} |
||
(or more accurately the final state of the console) |
(or more accurately the final state of the console) |
||
Line 691: | Line 809: | ||
{3,30,2,102,10} |
{3,30,2,102,10} |
||
</pre> |
</pre> |
||
===avoiding file i/o=== |
|||
And hence runnable in a browser, as well as on the desktop.<br> |
|||
User input would need to be a proper GUI rather than a console prompt, perhaps like [[Arithmetic/Integer#Phix]] or the much prettier/more polished [[Morse_code#Phix]]. |
|||
<!--<syntaxhighlight lang="phix">(phixonline)--> |
|||
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span> |
|||
<span style="color: #004080;">sequence</span> <span style="color: #000000;">lines</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">split</span><span style="color: #0000FF;">(</span><span style="color: #008000;">""" |
|||
5 |
|||
1 2 |
|||
10 20 |
|||
-3 5 |
|||
100 2 |
|||
5 5"""</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"\n"</span><span style="color: #0000FF;">)</span> |
|||
<span style="color: #004080;">string</span> <span style="color: #000000;">line</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">lines</span><span style="color: #0000FF;">[</span><span style="color: #000000;">1</span><span style="color: #0000FF;">]</span> |
|||
<span style="color: #004080;">sequence</span> <span style="color: #000000;">r</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">scanf</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">trim</span><span style="color: #0000FF;">(</span><span style="color: #000000;">line</span><span style="color: #0000FF;">),</span><span style="color: #008000;">"%d"</span><span style="color: #0000FF;">),</span> <span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{}</span> |
|||
<span style="color: #008080;">if</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">r</span><span style="color: #0000FF;">)!=</span><span style="color: #000000;">1</span> <span style="color: #008080;">then</span> |
|||
<span style="color: #7060A8;">crash</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"input not a number"</span><span style="color: #0000FF;">)</span> |
|||
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span> |
|||
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"\n"</span><span style="color: #0000FF;">)</span> |
|||
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">r</span><span style="color: #0000FF;">[</span><span style="color: #000000;">1</span><span style="color: #0000FF;">][</span><span style="color: #000000;">1</span><span style="color: #0000FF;">]</span> <span style="color: #008080;">do</span> |
|||
<span style="color: #000000;">line</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">lines</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">+</span><span style="color: #000000;">1</span><span style="color: #0000FF;">]</span> |
|||
<span style="color: #000000;">r</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">scanf</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">trim</span><span style="color: #0000FF;">(</span><span style="color: #000000;">line</span><span style="color: #0000FF;">),</span><span style="color: #008000;">"%d %d"</span><span style="color: #0000FF;">)</span> |
|||
<span style="color: #008080;">if</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">r</span><span style="color: #0000FF;">)!=</span><span style="color: #000000;">1</span> <span style="color: #008080;">then</span> |
|||
<span style="color: #7060A8;">crash</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"input not a pair of numbers"</span><span style="color: #0000FF;">)</span> |
|||
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span> |
|||
<span style="color: #000000;">s</span> <span style="color: #0000FF;">&=</span> <span style="color: #7060A8;">sum</span><span style="color: #0000FF;">(</span><span style="color: #000000;">r</span><span style="color: #0000FF;">[</span><span style="color: #000000;">1</span><span style="color: #0000FF;">])</span> |
|||
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span> |
|||
<span style="color: #7060A8;">pp</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)</span> |
|||
<!--</syntaxhighlight>--> |
|||
Output same as the last line of the above. |
|||
=={{header|PowerShell}}== |
=={{header|PowerShell}}== |
||
<syntaxhighlight lang="powershell"> |
|||
<lang PowerShell> |
|||
# script.ps1 |
# script.ps1 |
||
Line 705: | Line 852: | ||
# ./script file.txt |
# ./script file.txt |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Python}}== |
=={{header|Python}}== |
||
< |
<syntaxhighlight lang="python">def do_stuff(a, b): |
||
return a + b |
return a + b |
||
Line 714: | Line 861: | ||
for x in range(0, t): |
for x in range(0, t): |
||
a, b = raw_input().strip().split() |
a, b = raw_input().strip().split() |
||
print do_stuff(int(a), int(b))</ |
print do_stuff(int(a), int(b))</syntaxhighlight> |
||
===Python: Alternative=== |
===Python: Alternative=== |
||
Or without the function do_stuff() and that works for Python 3 and Python 2: |
Or without the function do_stuff() and that works for Python 3 and Python 2: |
||
< |
<syntaxhighlight lang="python">>>> try: raw_input |
||
except NameError: raw_input = input |
except NameError: raw_input = input |
||
Line 738: | Line 885: | ||
5 5 |
5 5 |
||
10 |
10 |
||
>>> </ |
>>> </syntaxhighlight> |
||
(All but the first line of single numbers, (the 5), is output from the program). |
(All but the first line of single numbers, (the 5), is output from the program). |
||
===Python: With prompts=== |
===Python: With prompts=== |
||
More than is asked for by the task, but if working interactively then the following version adds prompts. |
More than is asked for by the task, but if working interactively then the following version adds prompts. |
||
< |
<syntaxhighlight lang="python">>>> for i in range(int(raw_input('lines: '))): |
||
print(sum(int(numberstring) |
print(sum(int(numberstring) |
||
for numberstring in raw_input('two numbers: ').strip().split())) |
for numberstring in raw_input('two numbers: ').strip().split())) |
||
Line 759: | Line 906: | ||
two numbers: 5 5 |
two numbers: 5 5 |
||
10 |
10 |
||
>>> </ |
>>> </syntaxhighlight> |
||
=={{header|Quackery}}== |
|||
<syntaxhighlight lang="Quackery"> [] |
|||
$ "How many pairs? " input |
|||
quackery times |
|||
[ $ "Pair " |
|||
i^ 1+ number$ join |
|||
$ ": " join input |
|||
join |
|||
$ " + echo cr " join ] |
|||
quackery</syntaxhighlight> |
|||
{{out}} |
|||
<pre>How many pairs? 5 |
|||
Pair 1: 1 2 |
|||
Pair 2: 10 20 |
|||
Pair 3: -3 5 |
|||
Pair 4: 100 2 |
|||
Pair 5: 5 5 |
|||
3 |
|||
30 |
|||
2 |
|||
102 |
|||
10 |
|||
</pre> |
|||
=={{header|Racket}}== |
=={{header|Racket}}== |
||
< |
<syntaxhighlight lang="racket">#lang racket |
||
;(define line-number (read)) ;reads all kind of things |
;(define line-number (read)) ;reads all kind of things |
||
;(for ([i (in-range line-number)]) |
;(for ([i (in-range line-number)]) |
||
Line 773: | Line 947: | ||
(displayln (apply + |
(displayln (apply + |
||
(map string->number |
(map string->number |
||
(string-split (read-line))))))</ |
(string-split (read-line))))))</syntaxhighlight> |
||
=={{header|Raku}}== |
=={{header|Raku}}== |
||
(formerly Perl 6) |
(formerly Perl 6) |
||
<lang |
<syntaxhighlight lang="raku" line>for ^get() { say [+] get.words }</syntaxhighlight> |
||
This does more than the task asks. It will sum as many numbers as you care to put on each line, and the numbers need not be integers, but may also be a mix of rational, floating-point, or complex numbers. More subtly, <tt>get</tt> can read from a file specified as a command-line argument, but defaults to taking STDIN if no filename is specified. |
This does more than the task asks. It will sum as many numbers as you care to put on each line, and the numbers need not be integers, but may also be a mix of rational, floating-point, or complex numbers. More subtly, <tt>get</tt> can read from a file specified as a command-line argument, but defaults to taking STDIN if no filename is specified. |
||
=={{header|REXX}}== |
=={{header|REXX}}== |
||
This version isn't limited to summing integers, any form of number that REXX supports can be used. |
This version isn't limited to summing integers, any form of number that REXX supports can be used. |
||
< |
<syntaxhighlight lang="rexx">/*REXX pgm reads a number (from the CL), reads that number of pairs, & writes their sum.*/ |
||
/*all input is from the Command Line. */ |
/*all input is from the Command Line. */ |
||
do linein() /*read the number of pairs to be add*ed*/ |
do linein() /*read the number of pairs to be add*ed*/ |
||
Line 788: | Line 962: | ||
say word($, 1) + word($, 2) /*display the sum of a pair of numbers.*/ |
say word($, 1) + word($, 2) /*display the sum of a pair of numbers.*/ |
||
end /*linein() */ |
end /*linein() */ |
||
/*stick a fork in it, we're all done. */</ |
/*stick a fork in it, we're all done. */</syntaxhighlight> |
||
=={{header|Ring}}== |
=={{header|Ring}}== |
||
< |
<syntaxhighlight lang="ring"> |
||
# Project : Input/Output for Pairs of Numbers |
# Project : Input/Output for Pairs of Numbers |
||
Line 809: | Line 983: | ||
ok |
ok |
||
next |
next |
||
</syntaxhighlight> |
|||
</lang> |
|||
Output: |
Output: |
||
<pre> |
<pre> |
||
Line 820: | Line 994: | ||
===Ring: Alternative=== |
===Ring: Alternative=== |
||
< |
<syntaxhighlight lang="ring"> |
||
# Project : Input/Output for Pairs of Numbers (Alternative) |
# Project : Input/Output for Pairs of Numbers (Alternative) |
||
Line 837: | Line 1,011: | ||
ok |
ok |
||
next |
next |
||
>>> </ |
>>> </syntaxhighlight> |
||
<pre> |
<pre> |
||
3 |
3 |
||
Line 844: | Line 1,018: | ||
102 |
102 |
||
10 |
10 |
||
</pre> |
|||
=={{header|RPL}}== |
|||
« 1 "How many pairs" "" INPUT STR→ '''FOR''' j |
|||
"Enter pair #" j + "" INPUT STR→ + |
|||
'''NEXT''' |
|||
» '<span style=color:blue">TASK</span>' STO |
|||
{{out}} |
|||
<pre> |
|||
5: 3 |
|||
4: 30 |
|||
3: 2 |
|||
2: 102 |
|||
1: 10 |
|||
</pre> |
</pre> |
||
=={{header|Ruby}}== |
=={{header|Ruby}}== |
||
< |
<syntaxhighlight lang="ruby">n = gets.to_i |
||
n.times do |
n.times do |
||
a, b = gets.split.map(&:to_i) |
a, b = gets.split.map(&:to_i) |
||
puts a + b |
puts a + b |
||
end</ |
end</syntaxhighlight> |
||
=={{header|Scala}}== |
=={{header|Scala}}== |
||
< |
<syntaxhighlight lang="scala">object IOPairs extends App { |
||
private val in = scala.io.StdIn |
private val in = scala.io.StdIn |
||
private val n = in.readInt() |
private val n = in.readInt() |
||
Line 867: | Line 1,055: | ||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Tcl}}== |
=={{header|Tcl}}== |
||
< |
<syntaxhighlight lang="tcl">gets stdin n |
||
while {$n > 0} { |
while {$n > 0} { |
||
if {[scan [gets stdin] "%d %d" a b] == 2} { |
if {[scan [gets stdin] "%d %d" a b] == 2} { |
||
Line 876: | Line 1,064: | ||
} |
} |
||
incr n -1 |
incr n -1 |
||
}</ |
}</syntaxhighlight> |
||
=={{header|UNIX Shell}}== |
=={{header|UNIX Shell}}== |
||
Line 882: | Line 1,070: | ||
{{works with|Bourne Again SHell}} |
{{works with|Bourne Again SHell}} |
||
< |
<syntaxhighlight lang="bash">read n |
||
while (( n > 0 )); do |
while (( n > 0 )); do |
||
read a b |
read a b |
||
echo $((a+b)) |
echo $((a+b)) |
||
((n--)) |
((n--)) |
||
done</ |
done</syntaxhighlight> |
||
=={{header|Ursa}}== |
=={{header|Ursa}}== |
||
< |
<syntaxhighlight lang="ursa">decl int amount |
||
set amount (in int console) |
set amount (in int console) |
||
Line 904: | Line 1,092: | ||
for (set i 0) (< i (size ints)) (set i (int (+ 2 i))) |
for (set i 0) (< i (size ints)) (set i (int (+ 2 i))) |
||
out (int (+ ints<i> ints<(int (+ i 1))>)) endl console |
out (int (+ ints<i> ints<(int (+ i 1))>)) endl console |
||
end for</ |
end for</syntaxhighlight> |
||
Networked version. Runs on port 20000. |
Networked version. Runs on port 20000. |
||
< |
<syntaxhighlight lang="ursa">decl serverport sp |
||
decl port p |
decl port p |
||
sp.attach 20000 |
sp.attach 20000 |
||
Line 925: | Line 1,113: | ||
for (set i 0) (< i (size ints)) (set i (int (+ 2 i))) |
for (set i 0) (< i (size ints)) (set i (int (+ 2 i))) |
||
out (int (+ ints<i> ints<(int (+ i 1))>)) endl p |
out (int (+ ints<i> ints<(int (+ i 1))>)) endl p |
||
end for</ |
end for</syntaxhighlight> |
||
=={{header|Wren}}== |
=={{header|Wren}}== |
||
This assumes that both Stdin and Stdout are connected to a terminal. |
This assumes that both Stdin and Stdout are connected to a terminal. |
||
< |
<syntaxhighlight lang="wren">import "io" for Stdin |
||
var output = Fn.new { |pairs| pairs.each { |p| System.print(p[0] + p[1]) } } |
var output = Fn.new { |pairs| pairs.each { |p| System.print(p[0] + p[1]) } } |
||
Line 947: | Line 1,135: | ||
} |
} |
||
System.print() |
System.print() |
||
output.call(pairs)</ |
output.call(pairs)</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 968: | Line 1,156: | ||
=={{header|XPL0}}== |
=={{header|XPL0}}== |
||
The input file must be redirected on the command line, for example: iopair <iopair.txt |
The input file must be redirected on the command line, for example: iopair <iopair.txt |
||
< |
<syntaxhighlight lang="xpl0">int N; |
||
for N:= 1 to IntIn(1) do |
for N:= 1 to IntIn(1) do |
||
[IntOut(0, IntIn(1) + IntIn(1)); |
[IntOut(0, IntIn(1) + IntIn(1)); |
||
CrLf(0); |
CrLf(0); |
||
]</ |
]</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 985: | Line 1,173: | ||
=={{header|zkl}}== |
=={{header|zkl}}== |
||
Using the console as the input stream: |
Using the console as the input stream: |
||
< |
<syntaxhighlight lang="zkl">fcn pairs{ |
||
n:=ask("num pairs: ").toInt(); |
n:=ask("num pairs: ").toInt(); |
||
do(n){ask("1 pair: ").split(" ").sum().println()} |
do(n){ask("1 pair: ").split(" ").sum().println()} |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
Latest revision as of 19:05, 20 April 2024
From lines of input starting with a line containing the numbers of pairs to follows, followed by that number of pairs of integers separated by a space on separate lines from STDIN, output the sum of each pair to STDOUT.
- Sample input with corresponding output
Input
5 1 2 10 20 -3 5 100 2 5 5
Output
3 30 2 102 10
11l
F do_stuff(a, b)
R a + b
V t = Int(input())
L 1..t
V (a, b) = input().split(‘ ’).map(Int)
print(do_stuff(a, b))
Action!
INT FUNC CalcSum(CHAR ARRAY s)
INT sum,i
CHAR ARRAY tmp(100)
sum=ValI(s)
FOR i=1 TO s(0)
DO
IF s(i)=32 THEN EXIT FI
OD
SCopyS(tmp,s,i,s(0))
sum==+ValI(tmp)
RETURN (sum)
PROC Main()
BYTE i,nLines
INT ARRAY sums(256)
CHAR ARRAY line(256)
nLines=InputB()
IF nLines=0 THEN RETURN FI
FOR i=0 TO nLines-1
DO
InputS(line)
sums(i)=CalcSum(line)
OD
PutE()
FOR i=0 TO nLines-1
DO
PrintIE(sums(i))
OD
RETURN
- Output:
Screenshot from Atari 8-bit computer
5 1 2 10 20 -3 5 100 2 5 5 3 30 2 102 10
Ada
There can be newlines before or between numbers. The pairs may be on separate lines or the same line.
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;
procedure Main is
count : Integer;
First : Integer;
Second : Integer;
begin
Get (count);
for I in 1 .. count loop
Get (First);
Get (Second);
Put (Item => First + Second, Width => 1);
New_Line;
end loop;
end Main;
- Output:
Output using the example input:
3 30 2 102 10
ALGOL 68
Simple version - there can be newlines before or between the numbers
# read a number from stand in then read and add that many pairs of numbers from stand in #
# and write the sum to stand out. If non integer data is supplied, a runtime error will occur #
TO ( INT n; read( ( n, newline ) ); n ) DO
INT a, b;
read( ( a, b, newline ) );
print( ( a + b, newline ) )
OD
Strict version - the pairs of numbers must appear on the same line.
# read a number from stand in then read and add that many pairs of numbers from stand in #
# and write the sum to stand out. If non integer data is supplied, a runtime error will occur #
# This version does not allow the pairs of numbers to be spread over several lines #
STRING line;
FILE numbers;
associate( numbers, line );
TO ( INT n
; read( ( line, newline ) )
; reset( numbers )
; get( numbers, ( n ) )
; n
)
DO
INT a, b;
read( ( line, newline ) );
reset( numbers );
get( numbers, ( a, b ) );
print( ( a + b, newline ) )
OD
- Output:
+3 +30 +2 +102 +10
Applesoft BASIC
100 GOSUB 230"INPUT LINE"
110 LET N = VAL (L$) - 1
120 IF N < 0 THEN END
130 DIM SUM(N)
140 FOR I = 0 TO N
150 GOSUB 330"SUM PAIR FROM INPUT LINE"
160 LET SUM(I) = S
170 NEXT I
190 FOR I = 0 TO N
200 PRINT SUM(I)
210 NEXT
220 END
230 LET L$ = ""
240 LET C$ = ""
250 FOR C = 0 TO 1 STEP 0
260 LET L$ = L$ + C$
270 GET C$
280 PRINT CHR$ (0)C$;
290 LET C = C$ = CHR$ (13)
300 NEXT C
310 LET C = FRE (0)
320 RETURN
330 GOSUB 230"INPUT LINE"
340 FOR C = 1 TO LEN(L$)
350 IF MID$(L$, C, 1) <> " " THEN NEXT C
360 S = VAL(MID$(L$, 1, C - 1)) + VAL(MID$(L$, C + 1))
370 RETURN
Input
5 1 2 10 20 -3 5 100 2 5 5
- Output:
3 30 2 102 10
Arturo
printNumbers: function [num]->
print [num\0 "+" num\1 "=" num\0 + num\1]
lineCount: to :integer strip input ""
do.times:lineCount [
numbers: to [:integer] split.words input ""
printNumbers numbers
]
- Output:
3 2 10 2 + 10 = 12 4 5 4 + 5 = 9 -123 45 -123 + 45 = -78
AWK
NR == 1 {n=$1; next}
NR > n+1 {exit}
{print $1+$2}
Batch File
@echo off
setlocal enabledelayedexpansion
set /p pairs=
for /l %%i in (1,1,%pairs%) do set /p pair%%i=
for /l %%i in (1,1,%pairs%) do (
for %%j in (!pair%%i!) do (
set /a sum%%i+=%%j
)
)
for /l %%i in (1,1,%pairs%) do echo !sum%%i!
pause>nul
- Input:
5 10 10 5 6 -3 2 -6 -8 111 2
- Output:
20 11 -1 -14 113
BBC BASIC
The specification is a bit ambiguous, but I understood it as wanting us to read all the numbers in first and then print all the sums. This program does that. It could be a couple of lines shorter if we were allowed to use a comma instead of a space as separator.
INPUT n%
DIM pairs%(n% - 1, 1)
FOR i% = 0 TO n% - 1
INPUT s$
pairs%(i%, 0) = VAL(LEFT$(s$, INSTR(s$, " ")))
pairs%(i%, 1) = VAL(MID$(s$, INSTR(s$, " ")))
NEXT
FOR i% = 0 TO n% - 1
PRINT pairs%(i%, 0) + pairs%(i%, 1)
NEXT
With the sample inputs:
?5 ?1 2 ?10 20 ?-3 5 ?100 2 ?5 5 3 30 2 102 10
C
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int i, n, a, b, *f;
scanf("%d", &n);
f = malloc(sizeof(*f) * n);
for (i = 0; i < n; i++) {
if (2 != scanf("%d %d", &a, &b))
abort();
f[i] = a + b;
}
for (i = 0; i < n; i++)
printf("%d\n", f[i]);
return 0;
}
Output for example input
3 30 2 102 10
C#
using System;
using static System.Linq.Enumerable;
public class Program
{
static void Main(string[] args)
{
int count = Convert.ToInt32(Console.ReadLine());
for (int line = 0; line < count; line++) {
Console.WriteLine(Console.ReadLine().Split(' ').Sum(i => Convert.ToInt32(i)));
}
}
}
- Output:
3 30 2 102 10
C++
#include <iostream>
#include <vector>
using namespace std;
int doStuff(int a, int b) {
return a + b;
}
int main() {
int t;
cin >> t;
vector<pair<int, int>> list(t);
for(int j=0; j<t; j++){
cin >> list[j].first >> list[j].second;
}
cout << endl;
for(int j=0;j<t;j++){
cout << doStuff(list[j].first, list[j].second) << endl;;
}
}
Run as per given input
5 1 2 10 20 -3 5 100 2 5 5 3 30 2 102 10
D
This works with any number of integers on lines.
void main() {
import std.stdio, std.string, std.conv, std.algorithm;
foreach (immutable _; 0 .. readln.strip.to!uint)
readln.split.to!(int[]).sum.writeln;
}
EasyLang
n = number input
for i to n
a[] = number strsplit input " "
print a[1] + a[2]
.
input_data
5
1 2
10 20
-3 5
100 2
5 5
- Output:
3 30 2 102 10
Factor
USING: io math.parser prettyprint sequences splitting ;
IN: rosetta-code.pair-output
: process-line ( str -- n )
" " split [ string>number ] map-sum ;
: main ( -- ) lines 1 tail [ process-line ] map [ . ] each ;
MAIN: main
- Output:
3 30 2 102 10
Fortran
program i_o_pairs
implicit none
integer :: npairs
integer :: i
integer, allocatable :: pairs(:,:)
read(*,*) npairs
allocate(pairs(npairs,2))
do i = 1, npairs
read(*,*) pairs(i,:)
end do
write(*, "(i0)") sum(pairs, 2)
end program
FreeBASIC
' FB 1.05.0 Win64
Dim As UInteger n
Dim As Integer x, y
Input "", n
Dim sums(1 To n) As Integer
For i As Integer = 1 To n
Input "", x, y
sums(i) = x + y
Next
Print
For i As Integer = 1 To n
Print Str(sums(i))
Next
Sleep
- Output:
5 1 2 10 20 -3 5 100 2 5 5 3 30 2 102 10
Free Pascal
See Pascal
Go
package main
import (
"fmt"
"log"
)
func main() {
var lines int
n, err := fmt.Scanln(&lines)
if n != 1 || err != nil {
log.Fatal(err)
}
var a, b int
for ; lines > 0; lines-- {
n, err = fmt.Scanln(&a, &b)
if n != 2 || err != nil {
log.Fatal(err)
}
fmt.Println(a + b)
}
}
Haskell
This solution will actually add any number of integers placed on each line. Additionally, after removing the bits of code that cut out the specified number of lines, the solution will sum any number of lines of integers.
main = do
contents <- getContents
let numberOfLines = read.head.lines$ contents
nums = map (map read.words).take numberOfLines.tail.lines$ contents
sums = map sum nums
mapM_ print sums
J
$ cat <<EOF | jconsole -js '([: exit 0: [: smoutput [: ,. [: ({. {. }.) [: (+/"1) [: (0&".;._2) (1!:1)) 3'
> 5
> 1 2
> 10 20
> -3 5
> 100 2
> 5 5
> EOF
3
30
2
102
10
Considerably simpler than [explanation] output for lines of text, this sentence is a single fork. J pads the numeric arrays of 0&".;._2 (numbers cut) with 0 . We form the +/"1 (row sums), then take the sum of the first row of the beheaded sums ({. {. }.) for display. ,. (raveled items) reshapes the vector into a column-vector shaped matrix. And the [: (cap) causes the monadic form of the verb to cap's right.
Java
import java.util.Scanner;
public class Main {
public static int doStuff(int a, int b){
int sum = a+b;
return sum;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
for(int i=0; i<n; i++){
int a = in.nextInt();
int b= in.nextInt();
int result = doStuff(a, b);
System.out.println(result);
}
}
}
jq
Works with gojq, the Go implementation of jq
The solution below assumes the input is in a file named input.txt, and is quite lenient about the presentation of the numbers. For example, it does not require that each pair of numbers be presented on the same line.
< input.txt jq -n '
input as $n
| if $n | (type != "number" or . < 0)
then "Number of pairs must be non-negative." | error
else range(0; $n)
| [input,input] | add
end'
- Output:
3 30 2 102 10
Julia
parseints() = (a = split(strip(readline()), r"\s+"); map(x -> parse(Int, x), a))
const lines = parseints()[1]
for _ in 1:lines
println(sum(parseints()))
end
- Output:
3 5 6 11 8 2 10 9 23 32
Kotlin
// version 1.0.6
import java.util.Scanner
fun main(args: Array<String>) {
val sc = Scanner(System.`in`) // note: backticks required as 'in' is a Kotlin keyword
val n = sc.nextInt()
val x = IntArray(n)
val y = IntArray(n)
for (i in 0 until n) {
x[i] = sc.nextInt()
y[i] = sc.nextInt()
}
println()
for (i in 0 until n) println(x[i] + y[i])
}
Sample input/output:
- Output:
5 1 2 10 20 -3 5 100 2 5 5 3 30 2 102 10
Lua
This solution will sum any number of space-separated numbers per input line, assuming the user won't input too many to store in the available RAM.
local intTab, numLines, sum = {}, io.read()
for i = 1, numLines do
sum = 0
for number in io.read():gmatch("%S+") do sum = sum + number end
table.insert(intTab, sum)
end
for _, result in pairs(intTab) do print(result) end
Nim
import sequtils, strutils
let lineCount = stdin.readLine.parseInt()
for _ in 1..lineCount:
let line = stdin.readLine()
let fields = line.splitWhitespace()
assert fields.len == 2
let pair = fields.map(parseInt)
echo pair[0] + pair[1]
- Output:
For the sample input:
3 30 2 102 10
OCaml
let () =
let n = int_of_string (input_line stdin) in
for i = 1 to n do
let line = input_line stdin in
match String.split_on_char ' ' line with
| a::b::[] ->
let x = int_of_string a + int_of_string b in
print_int x;
print_newline ()
| _ ->
raise (Invalid_argument "wrong input")
done
- Output:
$ cat input.txt 5 1 2 10 20 -3 5 100 2 5 5 $ cat input.txt | ocaml pairs.ml 3 30 2 102 10
PARI/GP
Interestingly, this task is not possible to implement directly in GP, since input()
, like the gp REPL itself, ignores spaces. One must use PARI:
#include <stdio.h>
#include <stdlib.h>
#include <pari/pari.h>
int main(void);
int
main()
{
int i, n, a, b;
GEN f, sum;
pari_sp ltop;
// 1 MB stack, not using prime table
pari_init(1000000, 0);
scanf("%d", &n);
GEN f = cgetg(n+1, t_VEC);
for (i = 1; i <= n; i++) {
if (2 != scanf("%d %d", &a, &b)) abort();
ltop = avma;
// Add a and b in PARI
sum = addii(stoi(a), stoi(b));
// Store the sum in a vector, collecting garbage as you go.
gel(f, i) = gerepileupto(ltop, sum);
}
pari_printf("%Ps", f);
return 0;
}
Of course for such a simple task this has very little advantage over C, but it does demonstrate the general principle.
Pascal
program inputOutputForPairsOfNumbers(input, output);
var
lines: integer;
x: integer;
y: integer;
begin
readLn(lines);
for lines := 1 to lines do
begin
readLn(x, y);
writeLn(x + y)
end
end.
- Output:
3 30 2 102 10
Perl
Reads from STDIN, added any pair of numbers.
$n = scalar <>;
for (1..$n) {
($a,$b) = split ' ', <>;
print $a + $b . "\n";
}
Phix
without js -- (file i/o) string line = gets(0) sequence r = scanf(trim(line),"%d"), s = {} if length(r)!=1 then crash("input not a number") end if puts(1,"\n") for i=1 to r[1][1] do line = gets(0) r = scanf(trim(line),"%d %d") if length(r)!=1 then crash("input not a pair of numbers") end if s &= sum(r[1]) puts(1,"\n") end for puts(1,"===\n") pp(s)
- Output:
(or more accurately the final state of the console)
5 1 2 10 20 -3 5 100 2 5 5 === {3,30,2,102,10}
avoiding file i/o
And hence runnable in a browser, as well as on the desktop.
User input would need to be a proper GUI rather than a console prompt, perhaps like Arithmetic/Integer#Phix or the much prettier/more polished Morse_code#Phix.
with javascript_semantics sequence lines = split(""" 5 1 2 10 20 -3 5 100 2 5 5""","\n") string line = lines[1] sequence r = scanf(trim(line),"%d"), s = {} if length(r)!=1 then crash("input not a number") end if puts(1,"\n") for i=1 to r[1][1] do line = lines[i+1] r = scanf(trim(line),"%d %d") if length(r)!=1 then crash("input not a pair of numbers") end if s &= sum(r[1]) end for pp(s)
Output same as the last line of the above.
PowerShell
# script.ps1
$in, $line = (Get-Content $args[0]), 0
$nb = $in[$line++]
1..$nb | foreach {
$sum = 0
$in[$line++].Split() | foreach{ $sum += $_}
$sum
}
# ./script file.txt
Python
def do_stuff(a, b):
return a + b
t = input()
for x in range(0, t):
a, b = raw_input().strip().split()
print do_stuff(int(a), int(b))
Python: Alternative
Or without the function do_stuff() and that works for Python 3 and Python 2:
>>> try: raw_input
except NameError: raw_input = input
>>> for i in range(int(raw_input())):
print(sum(int(numberstring)
for numberstring
in raw_input().strip().split()))
5
1 2
3
10 20
30
-3 5
2
100 2
102
5 5
10
>>>
(All but the first line of single numbers, (the 5), is output from the program).
Python: With prompts
More than is asked for by the task, but if working interactively then the following version adds prompts.
>>> for i in range(int(raw_input('lines: '))):
print(sum(int(numberstring)
for numberstring in raw_input('two numbers: ').strip().split()))
lines: 5
two numbers: 1 2
3
two numbers: 10 20
30
two numbers: -3 5
2
two numbers: 100 2
102
two numbers: 5 5
10
>>>
Quackery
[]
$ "How many pairs? " input
quackery times
[ $ "Pair "
i^ 1+ number$ join
$ ": " join input
join
$ " + echo cr " join ]
quackery
- Output:
How many pairs? 5 Pair 1: 1 2 Pair 2: 10 20 Pair 3: -3 5 Pair 4: 100 2 Pair 5: 5 5 3 30 2 102 10
Racket
#lang racket
;(define line-number (read)) ;reads all kind of things
;(for ([i (in-range line-number)])
; (displayln (+ (read) (read))))
(define line-count (string->number ;only reads numbers
(string-trim (read-line))))
(for ([i (in-range line-count)])
(displayln (apply +
(map string->number
(string-split (read-line))))))
Raku
(formerly Perl 6)
for ^get() { say [+] get.words }
This does more than the task asks. It will sum as many numbers as you care to put on each line, and the numbers need not be integers, but may also be a mix of rational, floating-point, or complex numbers. More subtly, get can read from a file specified as a command-line argument, but defaults to taking STDIN if no filename is specified.
REXX
This version isn't limited to summing integers, any form of number that REXX supports can be used.
/*REXX pgm reads a number (from the CL), reads that number of pairs, & writes their sum.*/
/*all input is from the Command Line. */
do linein() /*read the number of pairs to be add*ed*/
$=linein() /*read a line (a record) from the C.L. */
say word($, 1) + word($, 2) /*display the sum of a pair of numbers.*/
end /*linein() */
/*stick a fork in it, we're all done. */
Ring
# Project : Input/Output for Pairs of Numbers
pairs = ["5", "1 2", "10 20", "-3 5", "100 2", "5 5"]
for n = 1 to len(pairs)
nr = 0
for p = 1 to len(pairs[n])
if substr(pairs[n], p, 1) = " "
nr = p
ok
next
if nr > 0
n1 = number(left(pairs[n], nr - 1))
n2 = number(right(pairs[n], len(pairs[n]) - nr + 1))
n3 = n1 + n2
see n3 + nl
ok
next
Output:
3 30 2 102 10
Ring: Alternative
# Project : Input/Output for Pairs of Numbers (Alternative)
pairs = ["5", "1 2", "10 20", "5 -3", "100 2", "5 5"]
for n = 1 to len(pairs)
nr = 0
for p = 1 to len(pairs[n])
if substr(pairs[n], p, 1) = " "
pairs[n] = substr(pairs[n], " ", "+")
nr = p
ok
next
if nr > 0
eval("ev = " + pairs[n])
see ev + nl
ok
next
>>>
3 30 2 102 10
RPL
« 1 "How many pairs" "" INPUT STR→ FOR j
"Enter pair #" j + "" INPUT STR→ +
NEXT
» 'TASK' STO
- Output:
5: 3 4: 30 3: 2 2: 102 1: 10
Ruby
n = gets.to_i
n.times do
a, b = gets.split.map(&:to_i)
puts a + b
end
Scala
object IOPairs extends App {
private val in = scala.io.StdIn
private val n = in.readInt()
for (_ <- 0 until n) {
val Array(a, b) = in.readLine().split(" ").map(_.toInt)
def doStuff(a: Long, b: Long): Long = a + b
println(doStuff(a, b))
}
}
Tcl
gets stdin n
while {$n > 0} {
if {[scan [gets stdin] "%d %d" a b] == 2} {
puts [expr {$a + $b}]
}
incr n -1
}
UNIX Shell
read n
while (( n > 0 )); do
read a b
echo $((a+b))
((n--))
done
Ursa
decl int amount
set amount (in int console)
decl int<> ints
for (decl int i) (< i amount) (inc i)
decl string input
set input (in string console)
append (int (split input " ")<0>) (int (split input " ")<1>) ints
end for
out endl console
for (set i 0) (< i (size ints)) (set i (int (+ 2 i)))
out (int (+ ints<i> ints<(int (+ i 1))>)) endl console
end for
Networked version. Runs on port 20000.
decl serverport sp
decl port p
sp.attach 20000
set p (sp.getconn)
decl int amount
set amount (in int p)
decl int<> ints
for (decl int i) (< i amount) (inc i)
decl string input
set input (in string p)
append (int (split input " ")<0>) (int (split input " ")<1>) ints
end for
out endl p
for (set i 0) (< i (size ints)) (set i (int (+ 2 i)))
out (int (+ ints<i> ints<(int (+ i 1))>)) endl p
end for
Wren
This assumes that both Stdin and Stdout are connected to a terminal.
import "io" for Stdin
var output = Fn.new { |pairs| pairs.each { |p| System.print(p[0] + p[1]) } }
var n = Num.fromString(Stdin.readLine())
if (!n || !n.isInteger || n < 1) Fiber.abort("Number of pairs must be a positive integer.")
var pairs = []
for (i in 0...n) {
var line = Stdin.readLine()
var sp = line.split(" ")
if (sp.count != 2) Fiber.abort("Each line must contain 2 integers, separated by a space.")
var p1 = Num.fromString(sp[0])
if (!p1 || !p1.isInteger) Fiber.abort("First value is not an integer.")
var p2 = Num.fromString(sp[1])
if (!p2 || !p2.isInteger) Fiber.abort("Second value is not an integer.")
pairs.add([p1, p2])
}
System.print()
output.call(pairs)
- Output:
Sample input/output:
5 1 2 10 20 -3 5 100 2 5 5 3 30 2 102 10
XPL0
The input file must be redirected on the command line, for example: iopair <iopair.txt
int N;
for N:= 1 to IntIn(1) do
[IntOut(0, IntIn(1) + IntIn(1));
CrLf(0);
]
- Output:
3 30 2 102 10
zkl
Using the console as the input stream:
fcn pairs{
n:=ask("num pairs: ").toInt();
do(n){ask("1 pair: ").split(" ").sum().println()}
}
- Output:
pairs() num pairs: 5 1 pair: 1 2 3 1 pair: 10 20 30 1 pair: -3 5 2 1 pair: 100 2 102 1 pair: 5 5 10