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

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 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




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.