1. Introduction
Determining if a number is even or odd is a basic computational task and an introduction to conditional structures in programming. In this article, we'll take a closer look at how to create a program in Golang that evaluates the parity of a number given by the user.
2. Program Overview
The primary objectives of our Go program are to:
1. Prompt the user to provide a number.
2. Evaluate if the entered number is even or odd.
3. Display the assessment to the user.
3. Code Program
// The entry point of our application is denoted by the main package declaration.
package main
// The fmt package is harnessed for managing input and output operations.
import "fmt"
// Execution of our program begins with the main function.
func main() {
// We declare an int variable to store the user's input.
var number int
// The user is requested to input a number, which is then stored in the number variable.
fmt.Print("Enter a number: ")
fmt.Scan(&number)
// A conditional statement checks the remainder when the number is divided by 2.
if number % 2 == 0 {
fmt.Println("The number is even.")
} else {
fmt.Println("The number is odd.")
}
}
Output:
If the user enters the number 5, the program's output will be: The number is odd. However, if the user provides 4 as input, the display would read: The number is even.
4. Step By Step Explanation
1. Package and Import Directives: We start with the package main to signify our program's initiation point. For handling inputs and outputs, the fmt package is integrated.
2. Variable Declaration: Using the var keyword, an integer variable named number is initialized to store the number provided by the user.
3. Receiving User Input: With fmt.Print, we provide a prompt to the user, and with fmt.Scan, the user's input is stored in the number variable.
4. Even-Odd Evaluation: To determine the number's parity, the remainder of the number when divided by 2 is checked. If the remainder is 0, the number is even; otherwise, it's odd.
5. Displaying the Result: Based on the evaluation, an appropriate message is printed, informing the user whether the number is even or odd.
Continue Learning with Java Guides
Want to take your programming skills to the next level? Explore my practical Udemy courses on Java, Spring Boot, Microservices, Full-Stack Development, Docker, and Generative AI. You can also follow my structured learning roadmaps to become a professional developer.
By Ramesh Fadatare - Udemy Instructor Partner
Comments
Post a Comment
Leave Comment