This guide demonstrates how to implement a simple sequential program in Go that calculates the squares of numbers from 1 to 10,000. This example illustrates basic programming concepts such as function calls, time measurement, and paves the way for understanding concurrency with Goroutines in future topics.Documentation Index
Fetch the complete documentation index at: https://notes.kodekloud.com/llms.txt
Use this file to discover all available pages before exploring further.
Overview
The program begins by declaring the package and defining the main function. Inside the main function, afor loop iterates from 1 to 10,000. For each iteration, the program calls the calculateSquare function, passing in the current loop variable as an argument.
The calculateSquare function has two primary responsibilities:
- Delay Execution: It uses the
Sleepfunction from thetimepackage to pause execution for one second. While such delays are uncommon in production, they are useful here to visibly demonstrate the performance gains when switching to Goroutines. - Calculate and Print Square: It calculates the square of the given number and prints the result.
time.Now() before entering the loop and computes the elapsed time with time.Since(start) after the loop completes. Given the one-second delay per calculation, the sequential execution takes roughly 10,000 seconds.
This example is designed for educational purposes. In practical applications, avoid artificial delays unless necessary.