A function gives a name to a small calculation so you can reuse it.
What to build
A program that finds the largest of three numbers on each line, using a function.
Requirements
- Write a function
max3(a, b, c int) int. - Read n, then n lines with three whole numbers, and print the largest of each line.
Input
Line 1: n. Then n lines with three whole numbers.
Output
n lines.
Constraints
1 ≤ n ≤ 50; each number is between -100000 and 100000.
Example
Input:
3
1 2 3
9 4 6
-5 -2 -9
Output:
3
9
-2
Why it works
max3 holds the comparison logic once; main only reads and prints. The same function works for every line.
Examples
Example 1 · Input
3 1 2 3 9 4 6 -5 -2 -9
Expected output
3 9 -2
Example 2 · Input
2 5 5 5 0 -1 0
Expected output
5 0
Hints
Hint 1
Write func max3(a, b, c int) int and call it for each line.
Hint 2
Start with m := a, then compare with b and c.
Solution
Show one correct solution (try it yourself first)
package main
import "fmt"
func max3(a, b, c int) int {
m := a
if b > m {
m = b
}
if c > m {
m = c
}
return m
}
func main() {
var n int
fmt.Scan(&n)
for i := 0; i < n; i++ {
var a, b, c int
fmt.Scan(&a, &b, &c)
fmt.Println(max3(a, b, c))
}
}