GO Program to Calculate Sum of Natural Numbers Using for.....Loop
In this example, using simple for........ loop to calculate the sum of natural numbers(the positive numbers 1, 2, 3... are known as natural numbers) from 1 to n (entered by the user).
Example
// Sum of n natural number (the positive numbers 1, 2, 3... are known as natural numbers)
package main
import "fmt"
func main(){
var n,sum int
fmt.Print("Enter a positive integer : ")
fmt.Scan(&n)
for i:=1; i<=n; i++ { // assigning 1 to i
sum += i // sum = sum + i
}
fmt.Print("Sum : ",sum)
}
for init; condition; post { } Like a C for
for condition { } Like a while
for { } Endless loop
Most Helpful This Week
Illustration of the dining philosophers problem in Golang
What is JSX?
How to create an empty Slice in Golang?
Go program to find Forward(A) record of a domain
Example of Interface with Type Embedding and Method Overriding in GO language
How to convert Struct fields into Map String?
GO Program to Find LCM and GCD of given two numbers
Undefined <variable/function> error in Golang
How do you create an HTTP server in Go?
Golang program for implementation of Merge Sort