×

Golang Tutorial

Golang Reference

Golang Programs

Golang Practice

Golang Miscellaneous

Golang program to create a function with the variable number of arguments to calculate the sum of all arguments

Here, we are going to learn how to create a function with the variable number of arguments to calculate the sum of all arguments in Golang (Go Language)?
Submitted by Nidhi, on March 26, 2021 [Last updated : March 03, 2023]

Creating a function with the variable number of arguments to calculate the sum of all arguments in Golang

Problem Solution:

In this program, we will create a variadic function that will accept the variable number of arguments in a function and return the sum of given arguments.

Program/Source Code:

The source code to create a function with the variable number of arguments to calculate the sum of all arguments is given below. The given program is compiled and executed successfully.

Golang code to create a function with the variable number of arguments to calculate the sum of all arguments

// Golang program to create a function with the variable number
// of arguments to calculate the sum of all arguments

package main

import "fmt"

func calculateSum(vals ...int) int {
	var sum int = 0
	for _, val := range vals {
		sum = sum + val
	}
	return sum
}

func main() {
	fmt.Println("Sum of 2 arguments: ", calculateSum(10, 20))
	fmt.Println("Sum of 3 arguments: ", calculateSum(10, 20, 30))
	fmt.Println("Sum of 4 arguments: ", calculateSum(10, 20, 30, 40))
}

Output:

Sum of 2 arguments:  30
Sum of 3 arguments:  60
Sum of 4 arguments:  100

Explanation:

In the above program, we declare the package main. The main package is used to tell the Go language compiler that the package must be compiled and produced the executable file. Here, we imported the fmt package to formatting related functions.

In this program, we created a variadic function calculateSum() to accept variable number of arguments.

func calculateSum(vals ...int) int {
    var sum int =0;
    for _, val := range vals {
      sum=sum+val
    }
    return sum
}

In the main() function, we called the calculateSum() function with different number of arguments. The calculateSum() function returns the sum of given arguments to the calling function. Then we printed the result on the console screen.

Golang Variadic Function Programs »





Comments and Discussions!

Load comments ↻





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