How to calculate sum of all odd numbers from 1 to 100 in Golang 1.20
In this video we are going to generate source code for the GoLang Program, How to calculate sum of all odd numbers from 1 to 100 using chatGPT.
After generating we will verify and run the generated code.
IMPORTANT NOTE on SOURCE CODE: only source code that are acceptable by the youtube description box will be displayed.
##############SOURCE CODE#########################
package main
import "fmt"
func main() {
// Initialize sum variable to 0
sum := 0
// Loop from 1 to 100
for i := 1; i <= 100; i++ {
// Check if the current number is odd
if i % 2 != 0 {
// If it's odd, add it to the sum
sum += i
}
}
// Print the sum of odd numbers
fmt.Printf("The sum of odd numbers from 1 to 100 is %d\n", sum)
}
##############END OF SOURCE CODE#########################
Below is the explanation for the program:
In this program, we initialize a sum variable to 0, and then use a for loop to iterate from 1 to 100. For each number in the loop, we check if it is odd by using the modulus operator % to check if the remainder when divided by 2 is not 0. If the remainder is not 0, then the number is odd and we add it to the sum variable.
#go #goprogramming #golang #golangtutorial #golanguage