Introduction
The Grade Calculator program is a simple utility that takes student scores as input and calculates their grade based on predefined score ranges. This program is written in the Go programming language (Golang), known for its simplicity and efficiency.
Objective
The main objective of this program is to demonstrate how to take input from a user, process that input, and display a corresponding grade based on a score. This will help in understanding input-output operations and conditional statements in Go.
Go Code for Grade Calculator
package main
import (
"fmt"
)
func main() {
// Declare a variable to store the score
var score float64
// Prompt the user to enter their score
fmt.Println("Enter your score (0-100):")
fmt.Scan(&score)
// Check the score range and display corresponding grade
var grade string
if score >= 90 && score <= 100 { grade = "A" } else if score >= 80 && score < 90 { grade = "B" } else if score >= 70 && score < 80 { grade = "C" } else if score >= 60 && score < 70 { grade = "D" } else if score >= 0 && score < 60 {
grade = "F"
} else {
fmt.Println("Invalid score entered. Please enter a score between 0 and 100.")
return
}
// Display the grade
fmt.Printf("Your grade is: %s\n", grade)
}
Explanation of the Program Structure
The program follows a straightforward structure:
- Import the fmt package: The
fmt
package is used for input and output operations such as printing text and reading user input. - Declare the score variable: The
score
variable is used to store the score entered by the user, which is of typefloat64</> to handle decimal values.
- Take user input: The program prompts the user to enter their score, which is then captured by
fmt.Scan(&score)
. - Conditional logic: Based on the value of the input score, the program checks which grade the score falls into using
if-else if
statements. The ranges are:- A: 90 – 100
- B: 80 – 89
- C: 70 – 79
- D: 60 – 69
- F: 0 – 59
- Display the result: The grade is printed using
fmt.Printf()</
. - Error handling: If the score entered is outside the valid range (0 to 100), the program will notify the user of the invalid input.
How to Run the Program
To run this Go program, follow the steps below:
-
- Ensure that Go is installed on your computer. You can download it from here.
- Save the provided code in a file with a
.go
extension, for example,grade_calculator.go
. - Open a terminal or command prompt, navigate to the directory where the file is saved, and type the following command to run the program:
go run grade_calculator.go
- The program will prompt you to enter a score. After entering a score, it will display the corresponding grade.