Input, output and data types

Video lessonComing soon

1 Two ways a program gets its input

On oneby7 and on LeetCode, we write a function. The input arrives as its parameters, and we return the answer.

Many placement online assessments work differently. A HackerRank-style test gives an almost empty editor, and we write the whole program. It reads the input as text from standard input and prints the answer to standard output.

Students who have only written functions often lose marks here. They read the input too slowly, or they print extra words around a right answer. The first half of this lesson fixes that. The second half is about the values: which type holds them, and what goes wrong when a type is too small.

2 Reading input and printing the answer

Here is a typical task. The first line holds a count n, and the second line holds n integers. We print their sum.

5
8 3 -4 10 6

We read n, then read the numbers one at a time and add each one to total. At the end we print total once. For this input it prints 23. total is a 64-bit integer, and the section on overflow shows why.

Most versions skip spaces and newlines alike, so the numbers can be spread over any lines. Java and C# read one line at a time, so they expect the count on line one and all the numbers on line two.

3 Fast input and exact output

With 10⁵ or more numbers, a slow way of reading can turn an Accepted into a TLE. Each language has an easy way that is slow, and a way that keeps up:

C++

cin. It is slow until we add the two lines at the top of main, as the code does. After them, we do not mix cin with scanf.

Scanner. It is easy to use but slow. We read lines with BufferedReader and split them with StringTokenizer, as the code does.

input(). Calling it once per number is slow. We read everything at once with sys.stdin.read(), as the code does.

Reading line by line. The readline module hands over one line at a time, which is slower. We read everything at once with fs.readFileSync(0), as the code does.

fmt.Scan on its own. It reads the input with no buffer, so it is slow. We wrap the input in bufio.NewReader and read with fmt.Fscan, as the code does.

read_line in a loop. Each call goes back to the input again. We read everything at once with read_to_string and split it, as the code does.

Printing line by line. Reading whole lines with Console.ReadLine, as the code does, keeps up. But many Console.WriteLine calls are slow, so for a long output we build it first and print it once.

The output must be exactly what the problem asks for. A prompt such as Enter n: or a label such as Sum = 23 makes the output wrong, even when the number is right.

4 Types and how much they hold

Every value in a program has a type. The type decides which values it can hold. Three number types cover almost every problem in this course: a 32-bit integer, a 64-bit integer and a decimal.

A 32-bit integer holds values up to 2,147,483,647, a little over 2 × 10⁹. A 64-bit integer holds up to about 9.2 × 10¹⁸.

C++

int, long long and double. Use long long, not long. A long is only 32 bits on some systems.

int, long and double.

int, long and double.

int32, int64 and float64. A plain int is 64 bits on the machines we use.

i32, i64 and f64.

int and float. An int grows as needed, so it never overflows.

One type, number. Every number is a double, and it holds integers exactly only up to about 9 × 10¹⁵. Past that we use a BigInt, written with an n at the end, such as 12n.

5 What overflow looks like

Input values up to about 10⁹ each fit in an int. The danger is in what we calculate from them: a sum of 10⁵ of them reaches 10¹⁴, and it needs 64 bits.

When a result does not fit, the program does not stop with an error. The value overflows: it wraps round from the top of the range to the bottom. Now we change total in section 2 to an int and run it on this input:

3
1000000000 1000000000 1000000000

The true sum is 3,000,000,000, past the 32-bit limit. The program prints −1,294,967,296 with no warning, and it gets Wrong Answer.

what an int can hold−2.1 × 10⁹02.1 × 10⁹true sumprinted
Past the top of the range, the count wraps round to the bottom

One overflow hides in a line that looks safe. Here a and b are both int:

long long area = a * b               // overflows
long long area = (long long) a * b   // correct

The type of area does not change how a * b is calculated. Both sides are int, so the product overflows before it is stored. Converting one side first makes the whole product 64-bit. In Java and C# the fix is (long) a * b.

6 Division and decimal numbers

Dividing one integer by another is whole-number division in most languages: the fraction is thrown away. To keep the fraction, at least one side must be a decimal.

C++

7 / 2 is 3, and 7 / 2.0 is 3.5. The fraction is cut toward zero, so -7 / 2 is −3.

7 / 2 is 3, and 7 / 2.0 is 3.5. The fraction is cut toward zero, so -7 / 2 is −3.

7 / 2 is 3, and 7 / 2.0 is 3.5. The fraction is cut toward zero, so -7 / 2 is −3.

7 / 2 is 3. For 3.5, convert first. Go never mixes an integer and a decimal on its own, so we write float64(total) / 2.

7 / 2 is 3. For 3.5, convert first. Rust never mixes an integer and a decimal on its own, so we write total as f64 / 2.0.

7 / 2 is 3.5, and 7 // 2 is 3. // rounds down instead of cutting toward zero, so -7 // 2 is −4, not −3.

7 / 2 is 3.5. For the whole part, Math.trunc(7 / 2) gives 3.

  • Converting too late. In (double) (7 / 2), the division runs first and gives 3, so the result is 3.0. (double) 7 / 2 gives 3.5.
  • Doubles are close, not exact. A double keeps about 15 digits, so 0.1 + 0.2 == 0.3 is false. We compare two doubles by checking that their difference is tiny, such as below 10⁻⁹.

7 Choosing a type from the constraints

The constraints tell us which types to use before we write any code:

  1. Find the largest input values in the constraints. They are often around 10⁹.
  2. Work out the largest sum or product the code makes from them.
  3. If it can pass about 2 × 10⁹, use the 64-bit type, and convert before the + or *, not after.
  4. If the answer needs a fraction, use a double, and make sure the division is a decimal division.
  5. In JavaScript, if an integer can pass about 9 × 10¹⁵, use BigInt.

For the sum in section 2, the constraints might say n ≤ 10⁵ and each value is at most 10⁹ in size. The sum can then reach 10¹⁴, so total is 64-bit, while each x stays an int.

The habit to keep: whenever code adds or multiplies, work out the largest result from the constraints before choosing its type. It takes ten seconds and prevents a silent Wrong Answer.

Practice it

Finished this lesson?

Mark it read and it is ticked on the roadmap and in the list.

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.