Go Program to Count the Number of Vowels in a String

1. Introduction

 In this guide, we'll walk through the steps to create a Go program capable of counting the vowels in any given string.

2. Program Overview

The structure of our Go program:

1. Gathers a string input from the user.

2. Provide the string for vowels, both lowercase and uppercase.

3. Outputs the number of vowels encountered.

3. Code Program

// The saga begins with the introduction of the main package.
package main

// We recruit the fmt package for its prowess in input and output operations.
import "fmt"

// Function to calculate the number of vowels in a string.
func countVowels(s string) int {
    count := 0
    for _, char := range s {
        switch char {
        case 'a', 'A', 'e', 'E', 'i', 'I', 'o', 'O', 'u', 'U':
            count++
        }
    }
    return count
}

// The cornerstone of our program, the main function.
func main() {
    var inputString string

    // Prompting the user to input their desired string.
    fmt.Print("Enter your string: ")
    fmt.Scanln(&inputString)

    // Revealing the number of vowels in the provided string.
    fmt.Printf("The number of vowels in \"%s\" is: %d\n", inputString, countVowels(inputString))
}

Output:

As a case in point, if the user submits the string Hello World, the program's response will be:
The number of vowels in "Hello World" is: 3

4. Step By Step Explanation

1. Package and Import: Our journey embarks with the package main statement, signifying the program's start. The fmt package is enlisted for smooth input-output handling.

2. Vowel Counting Function: The countVowels function serves as the mainstay for vowel counting. By iterating through each character in the string, the function checks if the character is a vowel (taking into account both lower and upper cases) and subsequently increments a counter.

3. User Interaction & Result Exhibition: The variable inputString is reserved for the user's string. Post fetching the input, the program computes the number of vowels using the countVowels function and then parades the result to the user.

Comments