0
0
Goprogramming~15 mins

Why loops are needed in Go - See It in Action

Choose your learning style9 modes available
Why loops are needed
๐Ÿ“– Scenario: Imagine you have a list of fruits and you want to say hello to each fruit. Doing this one by one is slow and boring. Loops help us say hello to all fruits quickly and easily.
๐ŸŽฏ Goal: You will create a list of fruits, set up a counter, use a loop to greet each fruit, and finally print all greetings.
๐Ÿ“‹ What You'll Learn
Create a slice called fruits with these exact values: "apple", "banana", "cherry"
Create an empty slice of strings called greetings
Use a for loop with index i to go through fruits
Inside the loop, add a greeting like "Hello, apple!" to greetings
Print each greeting from greetings using a for loop
๐Ÿ’ก Why This Matters
๐ŸŒ Real World
Loops are used in many programs to handle lists of items, like showing all messages, processing orders, or checking data.
๐Ÿ’ผ Career
Understanding loops is essential for any programming job because they help automate repetitive tasks efficiently.
Progress0 / 4 steps
1
Create the list of fruits
Create a slice called fruits with these exact values: "apple", "banana", "cherry"
Go
Need a hint?

Use fruits := []string{"apple", "banana", "cherry"} to create the slice.

2
Create an empty greetings slice
Create an empty slice of strings called greetings to store greetings
Go
Need a hint?

Use greetings := []string{} to create an empty slice.

3
Use a loop to create greetings
Use a for loop with index i to go through fruits. Inside the loop, add a greeting like "Hello, apple!" to greetings
Go
Need a hint?

Use for i := 0; i < len(fruits); i++ and inside the loop use append with fmt.Sprintf to add greetings.

4
Print all greetings
Use a for loop with variable _, greeting to go through greetings and print each greeting
Go
Need a hint?

Use for _, greeting := range greetings and fmt.Println(greeting) to print each greeting.