Write a Go program to find Sum of Even Numbers from 1 to n. It uses the for loop to iterate between 1 and n. Inside the loop, if statement filters the even numbers and adds total even to total.

package main import "fmt" func main() { var evnum, eventotal int fmt.Print("Enter the Number to find Even Sum = ") fmt.Scanln(&evnum) eventotal = 0 fmt.Println("List of Even Numbers from 1 to ", evnum, " are = ") for x := 1; x <= evnum; x++ { if x%2 == 0 { fmt.Print(x, "\t") eventotal = eventotal + x } } fmt.Println("\nSum of Even Numbers from 1 to ", evnum, " = ", eventotal) }

## Golang Program to find Sum of Even Numbers

In this Golang program, we altered the for loop and calculating the sum of even numbers.

package main import "fmt" func main() { var evnum, eventotal int fmt.Print("Enter the Number to find Even Sum = ") fmt.Scanln(&evnum) eventotal = 0 fmt.Println("List of Even Numbers from 1 to ", evnum, " are = ") for x := 2; x <= evnum; x = x + 2 { fmt.Print(x, "\t") eventotal = eventotal + x } fmt.Println("\nSum of Even Numbers from 1 to ", evnum, " = ", eventotal) }

This Go program calculates the sum of even numbers from minimum to maximum. Here, we used an extra if statement to ensure that the user entered value is an even number by incrementing the odd values.

package main import "fmt" func main() { var evenmin, evenmax, eventotal int fmt.Print("Enter the Minimum Even Number = ") fmt.Scanln(&evenmin) fmt.Print("Enter the Maximum Even Number = ") fmt.Scanln(&evenmax) if evenmin%2 != 0 { evenmin++ } eventotal = 0 fmt.Println("Even Numbers from ", evenmin, " to ", evenmax, " = ") for x := evenmin; x <= evenmax; x = x + 2 { fmt.Print(x, "\t") eventotal = eventotal + x } fmt.Println("\nSum of Even Numbers from ", evenmin, " to ", evenmax, " = ", eventotal) }

It is the same as the first Sum of Even Numbers example. However, this go example calculates the sum between the min and max limit.

package main import "fmt" func main() { var evenmin, evenmax, eventotal int fmt.Print("Enter the Minimum Even Number = ") fmt.Scanln(&evenmin) fmt.Print("Enter the Maximum Even Number = ") fmt.Scanln(&evenmax) eventotal = 0 fmt.Println("Even Numbers from ", evenmin, " to ", evenmax, " = ") for x := evenmin; x <= evenmax; x++ { if x%2 == 0 { fmt.Print(x, "\t") eventotal = eventotal + x } } fmt.Println("\nSum of Even Numbers from ", evenmin, " to ", evenmax, " = ", eventotal) }