Go math programs turn the numbers you read from the user into real answers, such as a total bill, an area or the interest on a loan. In this post, you will write fourteen short programs with their exact output, from adding two numbers to compound interest. Then you will practice the number questions that catch many people out in interviews.
You already know how to print values from our Go print programs and how to read them from Go user input programs. Here we use fixed values, so you can run every program in the Go Playground too. All programs were tested on Go 1.27.
What are Go Math Programs?
Go math programs are programs that calculate something with numbers. They use arithmetic operators like +, -, *, / and %, plus the math package for things like square roots and powers.
Think of Go as a calculator that is very strict about types. An int holds whole numbers, and a float64 holds decimals. Go will not mix them for you, so you must say clearly which kind of number you want.
Why Go Math Programs Matter
Every real app does some maths, so Go math programs are worth practising early. A shopping cart adds prices, a fitness app works out BMI, and a bank app calculates interest. Interviewers also use small math programs to check whether you understand integer division, rounding and overflow.
- Billing: totals, tax and discounts all need careful decimal handling.
- Geometry: areas and distances use
math.Pi,math.Sqrtandmath.Hypot. - Interviews: questions like “what is 7 / 2 in Go?” test your type knowledge.
How Go Math Programs Work
All Go math programs follow the same three steps. First, you store the input values in variables of the right type. Next, you apply operators or math functions. Finally, you print the result with the format you need.

The table below lists the arithmetic operators and what each one gives for 17 and 5.
| Operator | Meaning | 17 and 5 as int | 17.0 and 5.0 as float64 |
|---|---|---|---|
| + | Add | 22 | 22 |
| – | Subtract | 12 | 12 |
| * | Multiply | 85 | 85 |
| / | Divide | 3 | 3.4 |
| % | Remainder | 2 | Not allowed |
If you want the theory behind each operator, read Go operators explained with examples.
Basic Go Math Programs
These first Go math programs use only the five arithmetic operators.
Program 1: Add Two Numbers
This is the easiest program in the post. It stores two numbers, adds them and prints the answer.
package main
import "fmt" // fmt is the package for printing
func main() {
// Step 1: store the two numbers
// := creates a new variable and gives it a value
firstNumber := 25
secondNumber := 17
// Step 2: add them and keep the answer in a new variable
sum := firstNumber + secondNumber
// Step 3: print the answer
fmt.Println("First number:", firstNumber)
fmt.Println("Second number:", secondNumber)
fmt.Println("Sum:", sum)
}
First number: 25
Second number: 17
Sum: 42
The := sign creates a variable and sets its value in one go. Go sees whole numbers, so it makes both variables int. Then + adds them, and fmt.Println prints each label with its value.
Program 2: Arithmetic on Two Numbers
This program shows all five operators on two whole numbers.
package main
import "fmt"
func main() {
// Two whole numbers (Go makes them int)
first := 17
second := 5
fmt.Println("Sum:", first+second)
fmt.Println("Difference:", first-second)
fmt.Println("Product:", first*second)
fmt.Println("Quotient:", first/second) // int division drops the decimal part
fmt.Println("Remainder:", first%second) // % gives what is left over
}
Sum: 22
Difference: 12
Product: 85
Quotient: 3
Remainder: 2
Each line does one operation and prints it straight away. Because both numbers are ints, 17 / 5 gives 3, not 3.4. The % operator gives the part left over, which is 2.
Program 3: Swap Two Numbers Three Ways
Swapping is a classic interview task. Go makes it very short with multiple assignment.
package main
import "fmt"
func main() {
// Way 1: Go multiple assignment
first, second := 10, 20
first, second = second, first // Go reads both right side values first, then assigns
fmt.Println("Way 1:", first, second)
// Way 2: use a temporary variable to hold one value
left, right := 10, 20
temp := left // remember the old left value
left = right
right = temp
fmt.Println("Way 2:", left, right)
// Way 3: without a third variable, using + and -
top, bottom := 10, 20
top = top + bottom // top is now 30
bottom = top - bottom // bottom is now 10
top = top - bottom // top is now 20
fmt.Println("Way 3:", top, bottom)
}
Way 1: 20 10
Way 2: 20 10
Way 3: 20 10
first, second = second, first works because Go reads both values on the right before it assigns them. Way 2 parks one value in temp, so nothing is lost. Way 3 uses a sum to swap, which interviewers like to ask about. The first way is the normal way to swap in Go.
Program 4: Average of Five Numbers
To get a decimal average, convert the total to float64 before you divide.
package main
import "fmt"
func main() {
// A slice is a list of values of the same type
marks := []int{78, 85, 92, 66, 81}
// Step 1: add up all the marks
total := 0
for _, mark := range marks { // range gives each item; _ skips the position
total += mark // same as total = total + mark
}
// Step 2: convert to float64 so the decimal part is kept
average := float64(total) / float64(len(marks)) // len gives the number of items
// Step 3: print the results
fmt.Println("Total:", total)
fmt.Printf("Average: %.2f\n", average) // %.2f prints 2 decimal places, \n is a new line
}
Total: 402
Average: 80.40
The loop visits each mark and adds it to total. Then the program converts both numbers to float64 and divides. If we wrote total / len(marks), Go would give 80, because both are ints.
Go Math Programs with Formulas
Now let’s write Go math programs with real formulas from school maths and finance.
Program 5: Area and Perimeter of a Rectangle and Circle
The math package gives you math.Pi, so you do not have to type 3.14159 yourself.
package main
import (
"fmt"
"math" // math has Pi, Sqrt, Pow and many more
)
func main() {
// Rectangle sizes with decimals (Go makes them float64)
length := 12.5
width := 4.0
rectangleArea := length * width
rectanglePerimeter := 2 * (length + width)
fmt.Printf("Rectangle area: %.2f\n", rectangleArea)
fmt.Printf("Rectangle perimeter: %.2f\n", rectanglePerimeter)
// Circle size
radius := 7.0
circleArea := math.Pi * radius * radius
circumference := 2 * math.Pi * radius
fmt.Printf("Circle area: %.2f\n", circleArea)
fmt.Printf("Circle circumference: %.2f\n", circumference)
}
Rectangle area: 50.00
Rectangle perimeter: 33.00
Circle area: 153.94
Circle circumference: 43.98
Each formula gets its own named variable, so you can read it like school maths. We stored the sizes as float64, so the results keep their decimals. Then %.2f rounds the output to two places.
Program 6: Simple Interest
Simple interest uses the formula P x R x T / 100.
package main
import "fmt"
func main() {
principal := 50000.0 // the loan amount
rate := 7.5 // percent per year
years := 3.0
// Formula: principal x rate x years / 100
interest := principal * rate * years / 100
totalAmount := principal + interest
fmt.Printf("Interest: %.2f\n", interest)
fmt.Printf("Total amount: %.2f\n", totalAmount)
}
Interest: 11250.00
Total amount: 61250.00
The program multiplies the three values and divides by 100 to get the interest. Next, it adds the interest to the loan to get the total. We wrote 50000.0 with a decimal point, so all values are float64.
Program 7: Compound Interest with math.Pow
Compound interest grows on itself, so we need a power. math.Pow(x, y) gives x to the power y.
package main
import (
"fmt"
"math"
)
func main() {
principal := 50000.0
rate := 7.5 // percent per year
years := 3.0
// Step 1: growth for one year, for example 1.075
yearlyGrowth := 1 + rate/100
// Step 2: apply that growth once per year
amount := principal * math.Pow(yearlyGrowth, years)
// Step 3: the interest is the extra money on top of the loan
compoundInterest := amount - principal
fmt.Printf("Amount: %.2f\n", amount)
fmt.Printf("Compound interest: %.2f\n", compoundInterest)
}
Amount: 62114.84
Compound interest: 12114.84
First, the program works out how much the money grows in one year. Then math.Pow repeats that growth for 3 years. Compare this with Program 6. The same loan costs about 865 more with yearly compounding.
Program 8: Celsius to Fahrenheit
The formula is F = C x 9 / 5 + 32. Here we convert four temperatures in a loop.
package main
import "fmt"
func main() {
celsiusValues := []float64{-10, 0, 37, 100}
for _, celsius := range celsiusValues {
fahrenheit := celsius*9/5 + 32
// %6.1f means: use 6 characters wide, with 1 decimal place
fmt.Printf("%6.1f C = %6.1f F\n", celsius, fahrenheit)
}
}
-10.0 C = 14.0 F
0.0 C = 32.0 F
37.0 C = 98.6 F
100.0 C = 212.0 F
The loop takes one Celsius value at a time. It applies the formula and prints both values side by side. The width 6 in %6.1f lines the numbers up in neat columns.
Program 9: BMI Calculator
BMI is weight in kg divided by height in metres squared.
package main
import "fmt"
func main() {
weight := 68.0 // kg
height := 1.72 // metres
// Formula: weight / (height x height)
bmi := weight / (height * height)
fmt.Printf("BMI: %.1f\n", bmi) // %.1f prints 1 decimal place
}
BMI: 23.0
The brackets make Go square the height first. Then the weight is divided by that value. Finally, %.1f shows the BMI with one decimal place.
Program 10: Shopping Bill with Discount and Tax
This everyday example works out a final bill. It applies a discount first and then adds tax.
package main
import "fmt"
func main() {
price := 1200.0 // price of one item in rupees
quantity := 3.0 // number of items
discountPercent := 10.0
taxPercent := 18.0
// Step 1: cost before discount
subtotal := price * quantity
// Step 2: take away the discount
discount := subtotal * discountPercent / 100
afterDiscount := subtotal - discount
// Step 3: add tax on the discounted amount
tax := afterDiscount * taxPercent / 100
finalBill := afterDiscount + tax
fmt.Printf("Subtotal: %.2f\n", subtotal)
fmt.Printf("Discount: %.2f\n", discount)
fmt.Printf("Tax: %.2f\n", tax)
fmt.Printf("Final bill: %.2f\n", finalBill)
}
Subtotal: 3600.00
Discount: 360.00
Tax: 583.20
Final bill: 3823.20
The program builds the bill in small steps, just like a shop does. First it multiplies price by quantity. Next it removes 10 percent and then adds 18 percent tax on what is left.
Go Math Programs with the math Package
The math package has ready-made functions for most needs. These programs show the ones you will use most.
Program 11: Square Root, Cube Root and Power
package main
import (
"fmt"
"math"
)
func main() {
fmt.Println("Square root of 144:", math.Sqrt(144))
fmt.Println("Cube root of 27:", math.Cbrt(27))
fmt.Println("2 to the power 10:", math.Pow(2, 10))
fmt.Println("Absolute of -8.5:", math.Abs(-8.5)) // Abs removes the minus sign
fmt.Println("Max of 3 and 9:", max(3, 9)) // max is built into Go, no import needed
}
Square root of 144: 12
Cube root of 27: 3
2 to the power 10: 1024
Absolute of -8.5: 8.5
Max of 3 and 9: 9
Each line calls one function and prints its answer. max and min are built into Go since version 1.21, so they work on ints without the math package. The math functions use float64.
Program 12: Rounding Numbers
Go has four rounding functions. Each one treats the decimal part differently.
package main
import (
"fmt"
"math"
)
func main() {
values := []float64{2.5, 2.4, -2.5}
for _, value := range values {
rounded := math.Round(value) // nearest whole number
floor := math.Floor(value) // always goes down
ceiling := math.Ceil(value) // always goes up
truncated := math.Trunc(value) // cuts off the decimals
fmt.Println(value, "Round:", rounded, "Floor:", floor,
"Ceil:", ceiling, "Trunc:", truncated)
}
}
2.5 Round: 3 Floor: 2 Ceil: 3 Trunc: 2
2.4 Round: 2 Floor: 2 Ceil: 3 Trunc: 2
-2.5 Round: -3 Floor: -3 Ceil: -2 Trunc: -2
The loop tries all four functions on each value. Round goes to the nearest whole number and moves halves away from zero. Floor always goes down, Ceil always goes up, and Trunc just cuts off the decimals.
Program 13: Distance Between Two Points
math.Hypot finds the length of the long side of a right triangle, which is the distance between two points.
package main
import (
"fmt"
"math"
)
func main() {
// Point A is (1, 2) and point B is (4, 6)
startX, startY := 1.0, 2.0
endX, endY := 4.0, 6.0
// Step 1: how far apart the points are on each axis
across := endX - startX // 3
up := endY - startY // 4
// Step 2: Hypot gives the square root of (across x across + up x up)
distance := math.Hypot(across, up)
fmt.Println("Distance:", distance)
}
Distance: 5
First, the program finds the gap on the x axis and the y axis. These two gaps are the short sides of a triangle. Then math.Hypot gives the long side, which is 5.
Program 14: Integer Limits and Overflow
Every int type has a limit. If you go past it at run time, the value wraps around without any error.
package main
import (
"fmt"
"math"
)
func main() {
// int8 can only hold values from -128 to 127
var small int8 = 127
small++ // add 1, which goes past the limit
fmt.Println("int8 after 127 + 1:", small)
// The math package has the limits as constants
fmt.Println("Max int64:", math.MaxInt64)
fmt.Println("Max uint8:", math.MaxUint8)
}
int8 after 127 + 1: -128
Max int64: 9223372036854775807
Max uint8: 255
An int8 holds -128 to 127, so 127 + 1 wraps to -128. The math package stores each limit as a ready constant. Choose a type that is big enough for your data.
int vs float64 in Go Math Programs
Picking the right number type is the most important choice in Go math programs. The diagram and table below compare the two most common types.

| Feature | int | float64 |
|---|---|---|
| Holds | Whole numbers | Numbers with decimals |
| 7 / 2 gives | 3 | 3.5 |
| % operator | Allowed | Not allowed, use math.Mod |
| Exact results | Yes, within range | Small rounding errors |
| Divide by zero | Panic at run time | Gives +Inf |
| Good for | Counts, IDs, loops | Prices, sizes, science |
For money, many teams store paise or cents as an int to avoid rounding errors. Use float64 for measurements and science.
Common Mistakes in Go Math Programs
- Integer division by accident:
7 / 2is 3. Convert tofloat64when you need decimals. - Mixing types:
count + pricewith an int and a float64 does not compile. Convert one of them first. - Trusting float equality:
0.1 + 0.2 == 0.3is false. Compare with a small tolerance instead. - Ignoring overflow: small int types wrap around silently, so pick
intorint64for big values. - Dividing by a zero variable: an int divided by zero panics, so check the divisor first.
Best Practices for Go Math Programs
- Pick the type first, because it decides how every operator behaves.
- Use math.Pi and math functions instead of typing magic numbers.
- Format output with %.2f, so users see clean results.
- Store money as whole paise or cents, to avoid float rounding errors.
- Check divisors before dividing, so the program never crashes.
Go Math Programs Interview Questions and Answers
These Go math programs come up often in coding rounds. Each answer has a complete program and its real output from Go 1.27.
Division Questions in Go Math Programs
Q1. What does this program print?
package main
import "fmt"
func main() {
// Line 1: int division, then float division
fmt.Println(7/2, 7.0/2, 7/2.0)
// Line 2: division and remainder with negative numbers
fmt.Println(-7/2, -7%3, 7%-3)
}
3 3.5 3.5
-3 -1 1
If both numbers are ints, Go does int division. If either one has a decimal point, you get a float answer. Int division cuts toward zero, so -7 / 2 is -3. The remainder takes the sign of the first number, so -7 % 3 is -1 and 7 % -3 is 1.
Q2. What happens when you divide an int by zero?
package main
import "fmt"
func main() {
total := 10
divisor := 0
fmt.Println(total / divisor) // crashes while the program runs
}
panic: runtime error: integer divide by zero
The program crashes with a panic, followed by a stack trace. If you write 10 / 0 with constants, Go refuses to compile it and reports “division by zero” instead.
Q3. What happens when you divide a float by zero?
package main
import "fmt"
func main() {
zero := 0.0 // a float64 zero
fmt.Println(1/zero, -1/zero, zero/zero)
}
+Inf -Inf NaN
Floats follow the IEEE 754 standard, so there is no panic. You get positive infinity, negative infinity or NaN, which means “not a number”.
Q4. How do you get the remainder of two floats?
The % operator only works on integers. For floats, use math.Mod(7.5, 2), which returns 1.5.
Type Questions in Go Math Programs
Q5. Why does this program not compile?
package main
import "fmt"
func main() {
count := 3 // int
price := 2.5 // float64
fmt.Println(count * price)
}
invalid operation: count * price (mismatched types int and float64)
Go never converts number types for you. Write float64(count) * price to make both sides the same type.
Q6. What does this program print?
package main
import "fmt"
func main() {
price := 9.99
fmt.Println(int(price), int(-price)) // int(...) converts a float to an int
}
9 -9
Converting a float to an int drops the decimal part. It does not round, so 9.99 becomes 9.
Q7. What does this program print?
package main
import "fmt"
func main() {
// Constants: Go does exact maths while compiling
fmt.Println(0.1+0.2 == 0.3)
// Variables: real float64 values with tiny rounding errors
first := 0.1
second := 0.2
fmt.Println(first+second == 0.3)
fmt.Println(first + second)
}
true
false
0.30000000000000004
This is a great trick question. With constants, Go does exact maths at compile time, so the first line is true. With float64 variables, the tiny binary rounding error appears, so the second line is false.
Q8. Why does this not compile?
package main
import "fmt"
func main() {
var value byte = 256 // a byte can only hold 0 to 255
fmt.Println(value)
}
cannot use 256 (untyped int constant) as byte value in variable declaration (overflows)
A byte holds 0 to 255. Go checks constants at compile time, so it catches this overflow before the program runs.
Q9. What does this program print?
package main
import "fmt"
func main() {
var counter uint8 = 0 // uint8 holds 0 to 255, never negative
counter-- // subtract 1
fmt.Println(counter)
}
255
Unsigned types cannot be negative. So 0 minus 1 wraps around to the largest value, 255.
Operator Questions
Q10. Can you write fmt.Println(count++) in Go?
package main
import "fmt"
func main() {
count := 5
fmt.Println(count++)
}
syntax error: unexpected ++ in argument list; possibly missing comma or )
No. In Go, count++ is a statement, not an expression, so it cannot sit inside another call. Also, Go has no ++count form at all.
Q11. What does this program print?
package main
import "fmt"
func main() {
// & is AND, | is OR, ^ is XOR, << and >> shift the bits
fmt.Println(5&3, 5|3, 5^3, 1<<3, 16>>2)
}
1 7 6 8 4
These are bitwise operators. & is AND, | is OR, ^ is XOR, and the shifts move bits left or right. 1 << 3 is the same as 1 times 2 three times.
Q12. What does this program print?
package main
import "fmt"
func main() {
score := 10
score += 5 // score = score + 5
score *= 2 // score = score * 2
score -= 4 // score = score - 4
score /= 3 // score = score / 3 (int division)
score %= 5 // score = score % 5
fmt.Println(score)
}
3
Step by step, score becomes 15, 30, 26, 8 and finally 3. Work through each line slowly, because interviewers like these chains.
Q13. What does this program print?
package main
import "fmt"
func main() {
fmt.Println(2+3*4, (2+3)*4, 10-4-3, 2*3%4)
}
14 20 3 2
* and % come before + and -. Operators with the same priority run from left to right, so 2*3%4 is 6 % 4, which is 2.
math Package Questions
Q14. What does this program print?
package main
import (
"fmt"
"math"
)
func main() {
root := math.Sqrt(-1) // square root of a negative number
fmt.Println(root, math.IsNaN(root))
nan := math.NaN() // NaN means "not a number"
fmt.Println(nan == nan)
}
NaN true
false
The square root of a negative number is NaN. NaN is never equal to anything, not even itself, so use math.IsNaN to test for it.
Q15. What does this program print?
package main
import "fmt"
func main() {
// %.0f prints with no decimal places
fmt.Printf("%.0f %.0f %.0f\n", 0.5, 1.5, 2.5)
}
0 2 2
Printf rounds a half to the nearest even digit. So 0.5 becomes 0 and 2.5 becomes 2. If you need halves to round up, use math.Round before printing.
Q16. How do you find the maximum of many numbers?
Since Go 1.21, the built-in max takes any number of values, such as max(4, 9, 2). For a slice, use slices.Max(numbers) from the slices package.
Q17. What does this program print?
package main
import (
"fmt"
"math"
)
func main() {
number := 2.0
fmt.Println(math.Pow(number, 0.5), math.Sqrt(number))
fmt.Printf("%.4f\n", math.Sqrt(number)) // keep 4 decimal places
}
1.4142135623730951 1.4142135623730951
1.4142
A power of 0.5 is the same as a square root. Println shows all the digits, while %.4f keeps four decimal places.
Q18. How do you check if a number is even?
Use the remainder: number%2 == 0 means even. We use this a lot in the next post on if/else programs.
Practice Task
This task uses ideas from several Go math programs above. Write a program that splits a restaurant bill of 2,450 rupees between 4 friends, adds a 10% tip, and prints each share with two decimal places. Hint: convert to float64 before you divide.
Official Resources
Quick Recap
- Go math programs use
+,-,*,/and%, plus themathpackage. - Int division drops the decimal part, so convert to
float64for exact averages. - Go never mixes number types, so you must convert them yourself.
- Small int types wrap around on overflow, and floats can have tiny rounding errors.
math.Round,Floor,CeilandTrunceach round in a different way.
What’s Next?
Next, your programs start making decisions. Read Go if else programs with output. To revise the theory of numbers first, see Go variables, constants and data types.


