Exercise 3: Functions in Go

In this exercise, you will learn how to create and use functions in Go.

Check Your Go Installation

If you already have Go installed, you can proceed with the exercise. Otherwise, follow this guide to install Go: Install Go

Instructions:

  • 1️⃣ Create a file named functions.go in your Go project folder.
  • 2️⃣ Declare a function that takes two numbers as arguments and returns their sum.
  • 3️⃣ Call the function inside the main() function and print the result using fmt.Println().

🚀 Ready to code? Let's go! 😃

package main

import "fmt"

// Function to add two numbers
func add(a int, b int) int {
    return a + b
}

func main() {
    result := add(5, 3) // Calling the function
    fmt.Println("The sum is:", result) // Displaying the result
}
  • 4️⃣ Run the program using the command: go run functions.go

Code Explanation:

1️⃣ func add(a int, b int) int : Declares a function add that takes two integers as input and returns an integer.

2️⃣ return a + b : The function returns the sum of the two provided numbers.

3️⃣ result := add(5, 3) : Calls the add function with arguments 5 and 3 and stores the result in the variable result.

4️⃣ fmt.Println() : Prints the result to the console.

✅ If your program is correct, running it should display the following output:

The sum is: 8

← Previous Exercise Next Exercise →

🚀 Thanks for using these exercises! If you find this content helpful and want to support my work, buying me a coffee would be greatly appreciated! ☕😊


☕ Buy me a coffee