Skip to main content

Most Common Golang Coding Round Interview Question: Print 1-100 Even and Odd Numbers Using Goroutines and Channels



In many Golang interviews, candidates are often asked to demonstrate their understanding of concurrency, particularly through the use of goroutines and channels. Let's explore a classic example where we sequentially print even and odd numbers from 1 to 100 using two goroutines.

Problem Statement

We need to create two goroutines:

  1. Goroutine A: Prints odd numbers from 1 to 100.
  2. Goroutine B: Prints even numbers from 2 to 100.

Both goroutines should print numbers in sequence, alternating between odd and even, using channels to coordinate their execution.

Solution

Explanation:

  1. WaitGroup (sync.WaitGroup):

    • Used to wait for a collection of goroutines to finish.
    • wg.Add(2) adds two to the WaitGroup counter since there are two goroutines.
  2. Channel (chan int):

    • Used to synchronize the printing of odd and even numbers between the two goroutines.
    • signalChannel := make(chan int) creates an unbuffered channel for signaling.
  3. Goroutine for Odd Numbers:

    • Prints odd numbers from 1 to 100.
    • After printing an odd number, it sends a signal to the even number goroutine (signalChannel <- 1).
    • Waits for a signal from the even number goroutine before printing the next odd number (<-signalChannel).
  4. Goroutine for Even Numbers:

    • Prints even numbers from 2 to 100.
    • Waits for a signal from the odd number goroutine before printing an even number (<-signalChannel).
    • After printing an even number, it sends a signal to the odd number goroutine (signalChannel <- 1).
  5. Synchronization:

    • The WaitGroup ensures that the main function waits for both goroutines to complete before exiting.
    • The channel is used to coordinate the printing order between the two goroutines, ensuring that odd and even numbers are printed in the correct sequence.

This problem showcases how goroutines and channels can effectively handle concurrent tasks and synchronization in Golang, which is crucial for understanding and optimizing performance in concurrent applications.

Comments