×

Golang Tutorial

Golang Reference

Golang Programs

Golang Practice

Golang Miscellaneous

Golang program to add two integer numbers

Last Updated : April 20, 2025

Adding Two Integer Numbers in Golang

In this program, we will add two integer numbers and print the result on the console screen.

Golang Code to Add Two Integer Numbers

The source code to add two integer numbers is given below. The given program is compiled and executed successfully.

package main
import "fmt"

func main() {
    // Declare 3 integer type variables
    var num1 int = 10
    var num2 int = 20
    var num3 int = 0

    // Add num1, num2 and assign result to num3
    num3 = num1 + num2

    fmt.Println("Addition is: ", num3)
}

When executed, this program outputs:

Addition is:  30

Approach 1: Using Simple Variable Addition

You can add two numbers by directly assigning their sum to another variable.

Example

The following example demonstrates adding two integer variables and printing the result:

package main
import "fmt"

func main() {
    var num1 int = 10
    var num2 int = 20
    var num3 int = num1 + num2

    fmt.Println("Addition is: ", num3)
}

The output of the above code is:

Addition is:  30

Approach 2: Using Functions for Addition

You can add two numbers by using a function to perform the addition and return the result.

Example

The following example demonstrates adding two numbers using a function:

package main
import "fmt"

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

func main() {
    num1 := 10
    num2 := 20
    result := addNumbers(num1, num2)

    fmt.Println("Addition is: ", result)
}

The output of the above code is:

Addition is:  30

Approach 3: Using Pointers for Integer Addition

You can also add two numbers by passing them as pointers to a function. This allows you to manipulate the values directly in memory, which can be useful in certain scenarios.

Example

The following example demonstrates using pointers to add two integer values:

package main
import "fmt"

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

func main() {
    num1 := 10
    num2 := 20
    result := addNumbers(&num1, &num2)

    fmt.Println("Addition is: ", result)
}

The output of the above code is:

Addition is:  30

Golang Basic Programs »



Related Programs

Advertisement
Advertisement


Comments and Discussions!

Load comments ↻


Advertisement
Advertisement
Advertisement

Copyright © 2025 www.includehelp.com. All rights reserved.