How to Display Alphabets (A to Z) using a loop in Golang?


In this tutorial, we are going to print the alphabet from A to Z. The logic we are going to use to print the alphabet is ASCII values. Every symbol, alphabet, or number has a unique ASCII value using which we can print the Alphabets using a loop.

The ASCII value of A is 65 and the ASCII value of Z is 90.

A = 65
B =66
C = 67
.
.
.
.
.
Z = 90

Algorithm

  • STEP 1 − First we are declaring an integer with the ASCII number of A i.e 65.

  • STEP 2 − Then we are running a for loop from 0 to 26 to print all the Alphabets.

  • STEP 3 − Inside the loop, we are converting the ASCII value by adding the current iterator to the ASCII value of A that will become the ASCII value of the Alphabet at that position.

For example −

ASCII value of B = ASCII value of A + 1
ASCII value of c = ASCII value of A + 2
  • STEP 4 − Now we are first converting the ASCII value into rune which is an alias of int32 representing the Unicode character. Then we convert that rune into a string.

  • STEP 5 − In the end, we are printing the Alphabet.

Example

package main // fmt package provides the function to print anything import "fmt" func main() { // declaring the variable which is an ASCII value of A var startingASCIINumber int = 65 fmt.Println("Printing the alphabets from A to Z using a loop.") // printing the Alphabet from A to Z using for loop and // ASCII value concept for i := 0; i < 26; i++ { fmt.Print(string(rune(startingASCIINumber+i)), " ") } }

In the above code first, we are declaring the integer variable and initializing it with the ASCII value of A. Then we are running a for loop from 0 to less than 26. Inside the for loop, we are converting the ASCII value by adding the current iterator to the ASCII value of A that will become the ASCII value of the Alphabet at that position. In the next step, we are first converting the ASCII value into rune which is an alias of int32 representing the Unicode character. Then we convert that rune into a string. Lastly, we are printing the Alphabet.

Output

Printing the alphabets from A to Z using a loop.
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z

In this way, we can print the alphabets from A to Z using a for a loop. To learn more about Golang you can explore this tutorials.

Updated on: 26-Aug-2022

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements