Variable Scope in nested For Loop in Golang 1.20
In this video we are going to generate source code for the GoLang Program, Variable Scope in nested For Loops using chatGPT.
After generating we will verify and run the generated code.
IMPORTANT NOTE on SOURCE CODE: only source code that are acceptable by the youtube description box will be displayed.
In this program I have replaced the angled brackets with > or <. once you copy the source code to editor replace it with greater than or less than symbols respectively.
##############SOURCE CODE#########################
package main
import "fmt"
func main() {
for i := 1; i <= 3; i++ {
fmt.Printf("Outer loop iteration %d\n", i)
for j := 1; j <= 2; j++ {
fmt.Printf("Inner loop iteration %d\n", j)
k := i + j
fmt.Printf("k = %d\n", k)
}
// fmt.Printf("k = %d\n", k) // Uncommenting this line would result in a compilation error
}
}
##############END OF SOURCE CODE#########################
Below is the explanation for the program:
In this program, we have an outer loop that iterates from 1 to 3, and an inner loop that iterates from 1 to 2.
Inside the inner loop, we declare a variable k and assign it the value of the sum of the loop variables i and j.
Because k is declared inside the inner loop, its scope is limited to the inner loop.
This means that k cannot be accessed outside of the inner loop, and attempting to do so would result in a compilation error.
To demonstrate this, we have commented out a line that attempts to print the value of k outside of the inner loop.
If you uncomment this line, the program will fail to compile with an error message like the following:
.\main.go:11:23: undefined: k
#go #goprogramming #golang #golangtutorial #golanguage