Nandakumar Edamana
Share on:
@ R t f

Simple Interest Calculator in Go


Go is a relatively new programming language that is adored for its simplicity, compilation speed, and ease of network and concurrent programming. If you've successfully written and run your Hello World program in Go, here is the next step. It's a simple interest calculator that shows how basic I/O, variable declaration and calculations work in Go.

package main

import "fmt"

func main() {
  var p, r, n float64

  fmt.Printf("Enter the principal amount (P): ")
  fmt.Scanf("%f", &p)

  fmt.Printf("Enter the rate of interest (R%%): ")
  fmt.Scanf("%f", &r)

  fmt.Printf("Enter the no. of years (N): ")
  fmt.Scanf("%f", &n)

  intrst := p * r/100 * n

  fmt.Printf("The total interest amount is %.2f\n", intrst)
}

You can save the above code using any basic text editor. I hope you've installed Go. Assuming you chose the name main.go, you can run this program using the command go run main.go. Of course I'm not getting into the details of building a Go package. That's not the point of this article.

Let's see what's in the code. The logic is pretty straightforward. You read some basic parameters for calculating simple interest and run a basic formula. But what are some interesting facts related to this code, especially if you are new to Go?

  • Semicolons for statement termination are optional.
  • float64 is 64-bit floating point data type, usually similar to C's double.
  • The variable intrst is declared and initialized using the := operator, which helps avoid manually specifying the data type because it uses Go's type inference capability.
  • Unlike in C, Printf and Scanf start with uppercase letter, because they are public functions from the package fmt. Public members of containers like packages and structs start with uppercase letters in Go.
  • In case you are not familiar with C, %% in Printf prints a literal % and %.2f prints a floating point number upto two decimal points. \n prints a newline, or in other words, ends the current line.
  • Again, if you are not familiar with C, & is used before the variables in Scanf because you are passing the address of the variable to Scanf so that it can fill the variable.

Click here to read more like this. Click here to send a comment or query.