0
0
Goprogramming~15 mins

For loop as while in Go - Mini Project: Build & Apply

Choose your learning style9 modes available
Using For Loop as While in Go
๐Ÿ“– Scenario: Imagine you want to count how many times you can subtract 3 from a number until it becomes less than or equal to 0. This is like checking repeatedly with a condition, similar to a while loop.
๐ŸŽฏ Goal: You will write a Go program that uses a for loop as a while loop to count how many times 3 can be subtracted from a starting number.
๐Ÿ“‹ What You'll Learn
Create a variable number with the value 20
Create a variable count initialized to 0
Use a for loop with a condition to subtract 3 from number until it is less than or equal to 0
Increase count by 1 each time inside the loop
Print the final value of count
๐Ÿ’ก Why This Matters
๐ŸŒ Real World
Using loops with conditions is common when you want to repeat actions until something changes, like counting down time or processing items until none are left.
๐Ÿ’ผ Career
Understanding how to use loops as conditions is important for writing efficient and clear code in many programming jobs, especially when working with Go.
Progress0 / 4 steps
1
Create the starting number variable
Create a variable called number and set it to 20.
Go
Need a hint?

Use number := 20 to create the variable.

2
Add a counter variable
Add a variable called count and set it to 0 below the number variable.
Go
Need a hint?

Use count := 0 to create the counter variable.

3
Use a for loop as a while loop
Write a for loop with the condition number > 0. Inside the loop, subtract 3 from number and add 1 to count.
Go
Need a hint?

The for loop in Go can be used like a while loop by giving only a condition.

4
Print the count
Add a fmt.Println(count) statement to print the value of count. Remember to import the fmt package at the top.
Go
Need a hint?

Use fmt.Println(count) to show the final count.