Monday, December 17, 2018

Golang Example - Print/Display Lower/Upper Characters using rune and ASCII

This post covers two programs, the First program is to print lowercase a to z using for loop, the Second program is to display uppercase A to Z using for loop.

To understand this example, You should have following features in Go language
Like other programming languages, There is no specific data type for Character representation. We can use rune data type. rune is a primitive data type which contains ASCII code of type integer, meaning rune is an alias for int65
Each character has ASCII code.

Example Program 1- Print Lowercase a to z using for loop and 

The below program has two ways to display lowercase letters using for loop
  • First is using ASCII code
  • Second is using character rune type
Inside each iteration of the character, printed character to console using Printf  with %c option
package main

import "fmt"

func main() {
 // This is to print a to z using ascii code
 for char := 97; char <= 122; char++ {
  fmt.Printf("%c", char)
 }
 fmt.Println("")

 // Second example to print a to z using character
 for char := 'a'; char <= 'z'; char++ {
  fmt.Printf("%c", char)
 }

}

When the above program is compiled and executed, Output is
abcdefghijklmnopqrstuvwxyz
abcdefghijklmnopqrstuvwxyz

Example Program 2 - Display Uppercase A to Z using rune and for loop

The below program has two ways to display Upper letters using for loop
  • First is using ASCII code
  • Second is using character rune type
Inside each iteration of the character, Display character to console using Printf with %c option
package main
import "fmt"

func main() {
 // This is to print A to Z using ascii code
 for char := 65; char <= 90; char++ {
  fmt.Printf("%c", char)
 }
 fmt.Println("")

 // Second example to print A to Z using character
 for char := 'A'; char <= 'Z'; char++ {
  fmt.Printf("%c", char)
 }

}

When the above program is compiled and executed, Output is
ABCDEFGHIJKLMNOPQRSTUVWXYZ
ABCDEFGHIJKLMNOPQRSTUVWXYZ

Related article


EmoticonEmoticon