Add and subtract
- Go course
- Beginner
- Lesson 26/90
- 6 min
Write the add and subtract functions.
Addition and subtraction
The first two operations are the simplest; each takes two float64 values and returns a float64. Parameters of the same type can be shortened to a, b float64:
func topla(a, b float64) float64 { return a + b }
func cikar(a, b float64) float64 { return a - b }
fmt.Println(topla(10, 4), cikar(10, 4)) // 14 6Trying the functions
Trying each function with a few inputs right after writing it catches mistakes early. Try edge cases too: negative numbers, zero, decimals.
fmt.Println(topla(-2, 2)) // 0
fmt.Println(cikar(0.5, 0.25)) // 0.25Later these checks turn into real test functions.
Practice Two operations
Write the topla and cikar functions. Print the results of topla(10, 4) and cikar(10, 4) with one fmt.Println.
Starter code
package main
import "fmt"
func main() {
// buraya yaz
}Sample solution
package main
import "fmt"
func topla(a, b float64) float64 { return a + b }
func cikar(a, b float64) float64 { return a - b }
func main() {
fmt.Println(topla(10, 4), cikar(10, 4))
}Expected output
14 6
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does <code>cikar(4, 10)</code> return?
- -6 Correct answer
- 6
- 14
- An error
Explanation: Order matters: a - b = 4 - 10 = -6.
2 Subtraction
func cikar(a, b float64) float64 {
return a ____ b
}
func cikar(a, b float64) float64 {
return a - b
}
Explanation: The subtraction function returns a - b.
3 Call and result
| Term | Meaning |
|---|---|
topla(10, 4) |
14 |
cikar(10, 4) |
6 |
cikar(4, 10) |
-6 |
topla(-2, 2) |
0 |