Beginner · I/O basics
Sum of Two Numbers
Read two integers from input and print their sum. The "Hello World" of problem solving — the point is to master the read-compute-print cycle.
At a glanceRead two integers from one line and print a + b — the smallest complete program here: read, add, print, with negatives as the only edge case.
Problem
Input: one line with two integers a and b, separated by a space (−10⁹ ≤ a, b ≤ 10⁹).
Output: a single line with a + b.
Sample:
| Input | Output |
|---|---|
3 4 | 7 |
Your solution
Custom input for "Run my input"
Judging runs in your browser against hidden tests. A runaway loop is cut off after 3 seconds — still, make sure every loop has an exit. Your code is saved in this browser as you type.
Stuck? Hints
Hint 1 — the reading part
cin >> a >> b; reads both numbers in one line — >> skips the space between them automatically.
Hint 2 — the printing part
cout << a + b << endl; — you can compute inside the output statement, no extra variable needed.
Solution (try it first!)
#include <iostream>
using namespace std;
int main() {
int a, b;
cin >> a >> b;
cout << a + b << endl;
return 0;
}
The whole problem is one cycle of the main pattern: read → compute → print. Next, make it a loop problem.
Deep dive
Why this works
The whole program is one pipeline: read, compute, print. Every harder problem on this site is this same pipeline with a loop inserted in the middle — learn to see the three parts and the rest is detail.
The cost
O(1) time, O(1) space. Two ints in, one out; nothing scales with input size.
Where it goes wrong
- Reading with
cin >> a >> bin the wrong order still compiles and still prints a number — just the wrong one. Trace values, not syntax. - Two billion plus two billion overflows int to a negative number. The test data here is small, but
long longis the habit that survives.
Next step
The same pipeline with a loop in the middle: Sum from 1 to N.
Two things to remember
- Every program is read → compute → print. Name the three parts before writing code.
- Overflow is silent: int stops at 2,147,483,647 and wraps around.
🐞 This version fails — open it and try
Prints sum = 7 — the judge wants the bare number
#include <iostream>
using namespace std;
int main() {
int a, b;
cin >> a >> b;
cout << "sum = " << a + b << endl;
return 0;
}