CodeGym /행동 /Go SELF /read → parse → compute → print template

read → parse → compute → print template

Go SELF
레벨 2, 레슨 5
사용 가능

1. Introduction

When you are just starting to solve problems, it is very easy to turn main() into a mess: half the lines read input, a quarter of it computes something, a little more prints, and in the middle there is suddenly string concatenation and an attempt to multiply text by a number. Spoiler: Go will not appreciate that. The read → parse → compute → print template is needed so that your code is predictable: you always know exactly which stage you are in, and where to look for an error if the result is wrong.

The nicest thing about this template is that it fits almost all standard input/output problems. Even if the problem is simple, the habit of “breaking it into stages” saves nerves. And nerves, as we know, are a consumable in programming, but it is better if the consumption stays moderate.

General scheme: what each step means

If you describe the template in human language, it is literally “read → understand → compute → output the result.” It sounds like an ordinary conversation, and that is good: programming for a beginner should feel as conversational as possible, without the sense that you are summoning ancient spirits.

Below is a scheme that is useful to keep in mind (and sometimes even write as comments in the code):

flowchart LR
    A[read: read input] --> B[parse: convert types if needed]
    B --> C[compute: calculate the result]
    C --> D[print: print exactly as needed]

And a small table of what usually belongs to each stage:

Stage What we do Typical stage result
read
read data into variables a, b, s, n have received values
parse
convert a string to a number (or vice versa) n := atoi(s) or text := itoa(n)
compute
perform calculations sum, area, change, result
print
print in the required format one line / one number / several values

Important: the parse step is not always needed. If the input is already a number and we read it into int, then there is nothing to parse. But if the number comes “as text,” then you cannot do without Atoi.

2. Step read: read input so that the next steps are convenient

At the read stage, we do the most typical work: declare variables, then read values into them. Here it is easy to fall for the temptation to “calculate something right inside Scan,” but it is better not to rush: first get the data, then think.

The simplest option is to read numbers directly into int:

package main

import "fmt"

func main() {
	var a, b int
	fmt.Scan(&a, &b)     // read
	fmt.Println(a + b)   // compute+print (for now in one line)
}

This example works, but the stages are fused together. For practice with the template, it is better to separate them, even if it feels like “come on, it is only 2 lines.”

Here is the same idea, but cleaner:

package main

import "fmt"

func main() {
	// read
	var a, b int
	fmt.Scan(&a, &b)

	// compute
	sum := a + b

	// print
	fmt.Println(sum)
}

Blank lines and comments here are not decoration. They are visual boundaries: later you will thank yourself when you start making mistakes in longer problems. That is, roughly tomorrow... or rather, “at some point.”

3. Step parse: when the input is text but you need to compute numbers

At the parse stage, we convert one data type into another. And here it is important to accept Go’s philosophy: “nothing converts by itself.” At first this is annoying, but later it suddenly becomes clear why it is safer: you cannot accidentally add “12” and 3 and get “123” or 15 — you must make the choice explicitly.

Suppose the problem statement gives you a number as a string (this happens more often than it seems: codes, identifiers, sometimes “0012”, etc.). Then read will read a string, and parse will turn it into int:

package main

import (
	"fmt"
	"strconv"
)

func main() {
	// read
	var s string
	fmt.Scan(&s)

	// parse
	n, _ := strconv.Atoi(s)

	// compute
	double := n * 2

	// print
	fmt.Println(double)
}

Here we used _ to ignore the error. In educational tasks, this is sometimes acceptable because the input format is guaranteed: if it says “an integer is provided as input,” then it is. But it is important to understand that Atoi returns (int, error), and error is just an ordinary value that can be checked and handled. In Go, it is customary to work with errors explicitly, as values.

If you want at least to see whether there was an error, without branching that we are not using yet, you can simply print err:

package main

import (
	"fmt"
	"strconv"
)

func main() {
	var s string
	fmt.Scan(&s)

	n, err := strconv.Atoi(s)
	fmt.Println(n)    // if there is an error, n will be 0
	fmt.Println(err)  // <nil> if everything is OK
}

Yes, this is not “beautiful handling,” but for understanding the mechanics it is excellent.

4. Step compute: calculate the result and do not mix up string responsibilities

The compute stage is where you solve the problem. Here it is very useful to stick to the rule: “one variable — one idea.” Beginners often put a huge formula directly inside Println, and then get lost trying to find the mistake: in arithmetic, in operator precedence, or in the fact that the input was wrong altogether.

Instead, do this: put intermediate values into variables with sensible names.

For example, suppose we have a task: given the width and height of a rectangle, output the area and the perimeter.

package main

import "fmt"

func main() {
	// read
	var width, height int
	fmt.Scan(&width, &height)

	// compute
	area := width * height
	perimeter := 2*width + 2*height

	// print
	fmt.Println(area, perimeter)
}

Notice that perimeter := 2*width + 2*height is easy to read because we are not trying to do “math on the clock.” If you want even more clarity, you can add parentheses, even if they are not necessary. Sometimes that is a fair trade for readability.

5. Step print: output is part of the solution, not “we will handle it later somehow”

Output in programming exercises is tricky. You can calculate the answer perfectly, but print “Answer: 42” instead of “42” and get a wrong solution. A program is not required to be polite. It needs to be exact.

At the print stage, it is useful to remember a few things.

fmt.Println prints arguments separated by spaces and adds a newline. fmt.Print prints without a newline. If you are outputting several numbers, Println is the simplest path.

package main

import "fmt"

func main() {
	x := 5
	y := 7
	fmt.Println(x, y) // 5 7
}

If you need to build a string manually (for example, the task requires “x=5”), then either print arguments directly or use strconv.Itoa. Concatenating strings and numbers directly is not allowed.

package main

import (
	"fmt"
	"strconv"
)

func main() {
	x := 5
	line := "x=" + strconv.Itoa(x)
	fmt.Println(line) // x=5
}

6. Mini-example: “Cash register”

Now let us put together a small application that fits the template perfectly: a mini “cash register.” The idea is simple: the input gives the price and the payment amount (in cents), and the output is the change, also in cents, then split into dollars and cents. We are not using conditions yet, so we assume the payment is always at least the price.

Let us start with the version where the input is already numbers (int). That is straightforward and nice.

package main

import "fmt"

func main() {
	// read
	var priceCents, paidCents int
	fmt.Scan(&priceCents, &paidCents)

	// compute
	changeCents := paidCents - priceCents
	changeDollars := changeCents / 100
	changeRestCents := changeCents % 100

	// print
	fmt.Println(changeDollars, changeRestCents)
}

Now let us make life a little more complicated: suppose the price and payment come as strings. This is a common situation when data “looks like a number” but is stored as text.

package main

import (
	"fmt"
	"strconv"
)

func main() {
	// read
	var priceStr, paidStr string
	fmt.Scan(&priceStr, &paidStr)

	// parse
	priceCents, _ := strconv.Atoi(priceStr)
	paidCents, _ := strconv.Atoi(paidStr)

	// compute
	changeCents := paidCents - priceCents
	dollars := changeCents / 100
	cents := changeCents % 100

	// print
	fmt.Println(dollars, cents)
}

Notice how predictably this reads: you can literally see with your eyes where the input is, where the parsing is, where the math is, and where the output is. That is the main value of the template.

7. How to name variables so you do not get confused

Good variable names are when you can read the code like a story. Bad ones are when the code turns into “x1, x2, tmp, res2,” and you start wondering: is tmp temporary or permanent? Why res2, where is res1? And is x the width or the cat’s age?

A convention that works well in input/output tasks is this: name input variables by meaning (what they are), and output variables by role (what result they represent).

For example, compare the two options below. Formally both work, but they feel very different to the brain.

package main

import "fmt"

func main() {
	var a, b int
	fmt.Scan(&a, &b)
	c := a*b + a + b
	fmt.Println(c)
}

And now like this:

package main

import "fmt"

func main() {
	var width, height int
	fmt.Scan(&width, &height)

	area := width * height
	perimeter := 2*width + 2*height

	fmt.Println(area, perimeter)
}

In the second case, even a person who did not write the program understands what is happening. And that is more important than it seems: a few hours later, you yourself are already “not the same person who wrote the code” — memory likes to take a vacation.

Below is a small hint table showing how it is often convenient to name variables in educational tasks:

Meaning Example names
dimensions
width, height, length
quantity
n, count, total
sum
sum, totalSum
answer
result, answer
input string
s, text, priceStr
number after parsing
n, value, priceCents

Notice that sometimes n is a perfectly fine name. But only when it really means “quantity” or “size,” and not “I am tired of thinking of names.”

8. Micro-diagnostics: printing intermediate values

When you solve a problem and get “the wrong answer,” it is very tempting to immediately get mystical: “the computer is broken,” “there is a bug in Go,” “the universe is against me.” In practice, the problem is usually in one of the stages: read it wrong, parsed it wrong, computed it wrong, or printed it wrong.

While we are not using conditions yet, the best debugging method is to temporarily print intermediate values. And print them in a way that is easy to remove later.

For example, in the “cash register”:

package main

import "fmt"

func main() {
	var priceCents, paidCents int
	fmt.Scan(&priceCents, &paidCents)

	changeCents := paidCents - priceCents

	fmt.Println(priceCents, paidCents, changeCents) // temporary debug

	dollars := changeCents / 100
	cents := changeCents % 100
	fmt.Println(dollars, cents)
}

Yes, this breaks the output format for the platform. But debugging and the “final version” are different states of the code. The important thing is simply not to forget to remove the debug lines before submitting. That is a timeless classic.

9. Common mistakes

Mistake #1: mixing stages until it becomes “unclear what is where.”
A beginner often writes: fmt.Scan(&a); fmt.Println("ans", a+something) — and so on throughout the program. It seems to work while the task is small. But as soon as string parsing, several inputs, or a couple of intermediate computations appear, the code turns into a knot. The cure is discipline: first read, then (if needed) parse, then compute, then print, and put blank lines between them.

Mistake #2: trying to “glue a string and a number” with the + operator.
In Go, the + operator either adds numbers or concatenates strings. It does not do “both, depending on the mood.” Therefore "age=" + age will not compile. If you need to output them together, print them as arguments (fmt.Println("age=", age)) or convert the number to a string using strconv.Itoa.

Mistake #3: parsing is done “just in case,” even when it is not needed.
Sometimes a student learns Atoi and starts using it everywhere: reads int through Scan, then thinks “should I parse it again?” That is unnecessary and confusing. If the input is a number, read it into int and calculate right away. parse is needed only when the input type does not match the type you want to work with.

Mistake #4: variable names like x, x1, x2, tmp when the meaning matters.
Short names are allowed, but they should not turn the problem into a cipher. If the quantity is a width, let it be width. If it is a price in cents, let it be priceCents. Such names reduce the number of logic errors: you are less likely to mix values up because they look different.

Mistake #5: wrong output because of “friendly words.”
It is very tempting to write fmt.Println("Answer:", result) — the program looks smarter. But the judging system usually expects exactly result, without prefixes. Therefore, at the print stage, keep in mind the rule: output only what the statement asks for, and exactly in the format the statement asks for.

1
과제
Go SELF, 레벨 2, 레슨 5
잠금
책의 페이지 수
책의 페이지 수
1
과제
Go SELF, 레벨 2, 레슨 5
잠금
코드 트리플러
코드 트리플러
1
과제
Go SELF, 레벨 2, 레슨 5
잠금
거스름돈 계산
거스름돈 계산
1
과제
Go SELF, 레벨 2, 레슨 5
잠금
창고 포장
창고 포장
1
설문조사/퀴즈
정수 처리, 레벨 2, 레슨 5
사용 불가능
정수 처리
정수 처리
코멘트
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION