How to create and use loops (for and while) in Go?

In Go, you can use both for and while loops for iterative tasks. Here's how you can create and use these loops:

  1. FOR Loop: The for loop in Go has a variety of formats to suit different use cases. Here are two common ways to use it:
  • FOR loop with a counter:
for i := 0; i < 5; i++ { // Code to be executed repeatedly fmt.Println(i) }

This loop starts with initializing a counter variable (i in this case), specifies the condition under which the loop will run (i < 5), and defines how the counter should be incremented after each iteration (i++).

  • FOR loop without a counter (range-based):
arr := [3]string{"Apple", "Banana", "Cherry"} for index, value := range arr { // Code to be executed repeatedly fmt.Printf("Index: %d, Value: %s\n", index, value) }

Here, the loop iterates over the elements of the arr array using the range keyword. On each iteration, it assigns the index and the value of the current element to the respective variables (index and value in this example).

  1. WHILE Loop: Unlike some other programming languages, Go doesn't have a direct while loop construct. However, you can achieve the same functionality using a for loop with a single condition:
i := 0 for i < 5 { // Code to be executed repeatedly fmt.Println(i) // Increment the counter i++ }

This loop runs until the condition (i < 5) is false. You can place any conditional statement that evaluates to a boolean value inside the loop condition.

These are the basic ways to create and use loops in Go using for and while concepts. Feel free to adapt them as per your specific requirements.