Go Arithmetic Operators

1. Introduction

Arithmetic operators are a fundamental part of programming, allowing us to perform mathematical calculations. In Go, these operators are straightforward and similar to those found in many other programming languages. This post will explore the basic arithmetic operators available in Go with relevant examples.

Definition

Arithmetic operators in Go are used to perform basic mathematical operations such as addition, subtraction, multiplication, division, and modulus. The operators include + for addition, - for subtraction, * for multiplication, / for division, and % for modulus.

2. Program Steps

1. Perform addition using the + operator.

2. Perform subtraction using the - operator.

3. Perform multiplication using the * operator.

4. Perform division using the / operator.

5. Perform modulus operation using the % operator to find the remainder of division.

3. Code Program

package main

import "fmt"

func main() {
	// Step 1: Addition
	a := 10
	b := 5
	addResult := a + b // Adds a and b

	// Step 2: Subtraction
	subResult := a - b // Subtracts b from a

	// Step 3: Multiplication
	mulResult := a * b // Multiplies a and b

	// Step 4: Division
	divResult := a / b // Divides a by b

	// Step 5: Modulus
	modResult := a % b // Modulus of a by b

	// Printing the results
	fmt.Printf("Addition: %d + %d = %d\n", a, b, addResult)
	fmt.Printf("Subtraction: %d - %d = %d\n", a, b, subResult)
	fmt.Printf("Multiplication: %d * %d = %d\n", a, b, mulResult)
	fmt.Printf("Division: %d / %d = %d\n", a, b, divResult)
	fmt.Printf("Modulus: %d %% %d = %d\n", a, b, modResult) // Escape % with %%
}

Output:

Addition: 10 + 5 = 15
Subtraction: 10 - 5 = 5
Multiplication: 10 * 5 = 50
Division: 10 / 5 = 2
Modulus: 10 % 5 = 0

Explanation:

1. package main - The package declaration for the Go program.

2. import "fmt" - Importing the format package for formatted output.

3. Variables a and b are initialized with the values 10 and 5, respectively.

4. addResult is calculated using the + operator to add a and b.

5. subResult is calculated using the - operator to subtract b from a.

6. mulResult is calculated using the * operator to multiply a by b.

7. divResult is calculated using the / operator to divide a by b.

8. modResult is calculated using the % operator to find the remainder when a is divided by b.

9. The fmt.Printf statements are used to print the results of each operation. Note that to print a literal %, it is escaped as %%.

10. The output shows the results of each arithmetic operation using the given values of a and b.


Comments