1. Introduction
When learning a new programming language, one of the first tasks often undertaken is writing a program to add two numbers. It's a simple yet effective way to familiarize oneself with a language's syntax and structure. In this post, we'll cover how to write a program in Go (or Golang, as it's commonly known) to perform this basic arithmetic operation.
2. Program Overview
The primary objective of our program will be to:
1. Prompt the user to input two numbers.
2. Calculate the sum of the provided numbers.
3. Display the resultant sum to the user.
3. Code Program
// Start by declaring the main package, the entry point for our application.
package main
// Import the fmt package, essential for formatted I/O operations.
import "fmt"
// Define the main function which will be executed when the program runs.
func main() {
// Declare three variables of type float64 to store the two numbers and their sum.
var num1, num2, sum float64
// Prompt the user for the first number and read it into the num1 variable.
fmt.Print("Enter the first number: ")
fmt.Scan(&num1)
// Repeat the process for the second number, storing it in the num2 variable.
fmt.Print("Enter the second number: ")
fmt.Scan(&num2)
// Compute the sum of the two numbers.
sum = num1 + num2
// Display the result to the user using formatted printing.
fmt.Printf("The sum of %v and %v is: %v\n", num1, num2, sum)
}
Output:
Enter the first number: 10 Enter the second number: 20 The sum of 10 and 20 is: 30
4. Step By Step Explanation
1. Package and Import Declarations: We begin with the package main, which indicates our program's entry point. The fmt package is imported next, giving us access to input-output functions.
// Start by declaring the main package, the entry point for our application.
package main
// Import the fmt package, essential for formatted I/O operations.
import "fmt"
2. Variable Declaration: Using the var keyword, we declare three variables of type float64 to store our numbers and their sum.
// Declare three variables of type float64 to store the two numbers and their sum.
var num1, num2, sum float64
3. User Input: fmt.Print provides a prompt for the user, while fmt.Scan reads the user's input, storing it in the specified variable.
// Prompt the user for the first number and read it into the num1 variable.
fmt.Print("Enter the first number: ")
fmt.Scan(&num1)
// Repeat the process for the second number, storing it in the num2 variable.
fmt.Print("Enter the second number: ")
fmt.Scan(&num2)
4. Summation: We then add num1 and num2, storing the result in the sum variable.
// Compute the sum of the two numbers.
sum = num1 + num2
5. Displaying the Result: Lastly, fmt.Printf is used to format and display the summation result to the user.
// Display the result to the user using formatted printing.
fmt.Printf("The sum of %v and %v is: %v\n", num1, num2, sum)
Comments
Post a Comment
Leave Comment