Introduction
Currency conversion is a widely used application that helps in converting an amount from one currency to another based on exchange rates.
This program demonstrates how to create a simple console-based currency converter in Go.
Objective
The objective of this project is to create a program that allows users to convert amounts between different currencies using predefined exchange rates.
This helps learners understand concepts like mapping, user input, and arithmetic operations in Go.
Code
package main
import (
"fmt"
)
// Predefined exchange rates
var exchangeRates = map[string]float64{
"USD_TO_EUR": 0.92,
"USD_TO_INR": 82.50,
"EUR_TO_USD": 1.09,
"EUR_TO_INR": 89.50,
"INR_TO_USD": 0.012,
"INR_TO_EUR": 0.011,
}
func main() {
fmt.Println("Welcome to the Currency Converter!")
// Display available options
fmt.Println("Available Conversions:")
fmt.Println("1. USD to EUR")
fmt.Println("2. USD to INR")
fmt.Println("3. EUR to USD")
fmt.Println("4. EUR to INR")
fmt.Println("5. INR to USD")
fmt.Println("6. INR to EUR")
fmt.Print("Enter your choice (1-6): ")
var choice int
fmt.Scanln(&choice)
var amount float64
fmt.Print("Enter the amount to convert: ")
fmt.Scanln(&amount)
// Determine the conversion type and perform the conversion
var result float64
var conversionType string
switch choice {
case 1:
conversionType = "USD_TO_EUR"
case 2:
conversionType = "USD_TO_INR"
case 3:
conversionType = "EUR_TO_USD"
case 4:
conversionType = "EUR_TO_INR"
case 5:
conversionType = "INR_TO_USD"
case 6:
conversionType = "INR_TO_EUR"
default:
fmt.Println("Invalid choice. Please restart the program and try again.")
return
}
rate, exists := exchangeRates[conversionType]
if !exists {
fmt.Println("Conversion type not found. Please restart the program.")
return
}
result = amount * rate
fmt.Printf("Converted amount: %.2f\n", result)
}
Explanation
The program structure is as follows:
- Exchange Rates: A map is used to store predefined exchange rates between currencies. The keys represent conversion types (e.g., “USD_TO_EUR”).
- User Input: The program prompts the user to select a conversion type and enter an amount.
- Conversion Logic: Based on the user’s choice, the corresponding conversion type is retrieved from the map, and the conversion is performed.
- Error Handling: The program checks for invalid inputs and provides appropriate error messages.
How to Run the Program
- Ensure you have Go installed on your system. You can download it from
Go’s official website. - Save the code in a file named
currency_converter.go
. - Open a terminal and navigate to the directory containing the file.
- Run the program with the following command:
go run currency_converter.go
- Follow the on-screen instructions to convert amounts between currencies.
Copyright © Learn Programming. All rights reserved.