Go Program To Print Even Numbers From 1 To N

In this post we are going to learn how to print even numbers from 1 to N using Go Programming language.

Hello coders, in this post we are going to learn how to print even numbers from 1 to N using Go Programming language.

Go Program To Print Even Numbers From 1 To N

Any number which can be exactly divisible by 2 is known as Even Numbers. For example: 2, 8, 64, 512, 1810, . . . , etc.

This program will take maximum value from the user as input and displays even numbers from 1 to maximum value.

So, without further delay, let's begin this tutorial.

Table Of Contents 👊

Go Program To Print Even Numbers From 1 To N

package main
import "fmt"

func main(){
  var num, i int
  
  // Asking for Input
  fmt.Print("Enter the Maximum Value: ")
  fmt.Scan(&num)
  
  // Logic
  fmt.Println("Even Numbers from 1 to", num, "are:")
  for i = 2; i <= num; i = i + 2{
    fmt.Println(i)    
  }
}

Output

Enter the Maximum Value: 31
Even Numbers from 1 to 31 are:
2
4
6
8
10
12
14
16
18
20
22
24
26
28
30

How Does This Program Work ?

  var num, i int

In this program, we have declared two int data type variables named as i and num.

  // Asking for Input
  fmt.Print("Enter the Maximum Value: ")
  fmt.Scan(&num)

Then, the user is asked to enter the maximum value up to which user want to display even numbers. 

  fmt.Println("Even Numbers from 1 to", num, "are:")
  for i = 2; i <= num; i = i + 2{
    fmt.Println(i)    
  }

Finally, the even numbers from 1 to maximum value is find out using for loop and printed to the screen using fmt.Println() function.

Some of the used terms in this program are as follows:- 

package main - packages are a collection of Go source files that reside in the same directory. The line package main specifies that this file belongs to the main package.

Every Executable Go Application must contain the main function.

fmt.Println() - The fmt.Println() function in Go language is used to display output.

fmt.Scan() - The fmt.Scan() function is used to take input from the user in Go Programming language.

:= - The := syntax is shorthand for declaring and initializing a variable.

// - Used for Commenting in Go

Conclusion

I hope after reading this post, you understood how to print even numbers from 1 To N using Go Programming language.

If you have any doubt regarding the topic, feel free to contact in the comment section.

Sloth Coders is a Learning Platform for Coders, Programmers and Developers to learn from the basics to advance of Coding of different langauges(python, Java, Javascript and many more).

Post a Comment