For Loop - Basic
Part of the Fundamentals section of Coddy's GO journey — lesson 45 of 109.
Let's learn about the basic for loop in Go, focusing on the initialization part. A for loop helps us repeat code multiple times.
First, let's create a simple loop that counts from 1 to 3:
for i := 1; i <= 3; i++ {
fmt.Println(i)
}After executing this code, the numbers 1, 2, and 3 will show on the screen one after another:
1
2
3The initialization part i := 1 happens only once before the loop starts. It creates a variable i and sets it to 1. This variable i is only available inside the loop.
The middle part i <= 3 is the condition that checks if we should continue looping. The last part i++ increases the value of i by 1 after each loop.
Challenge
BeginnerThe for loop should:
1. Initialize a variable
i to 12. Continue as long as
i is less than or equal to 53. Increment
i by 1 after each iterationCheat sheet
A for loop in Go repeats code multiple times with three parts: initialization, condition, and increment:
for i := 1; i <= 3; i++ {
fmt.Println(i)
}The initialization i := 1 creates a variable and sets its initial value (happens only once). The condition i <= 3 checks if the loop should continue. The increment i++ increases the variable by 1 after each iteration.
The loop variable i is only available inside the loop scope.
Try it yourself
package main
import "fmt"
func main() {
// TODO: Complete the for loop to print numbers from 1 to 5
// Use the initialization, condition, and post statement format
for /* Your code here */ {
fmt.Println(i)
}
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Comparison & Logical Operators
Comparison Operators - Part 1Comparison Operators - Part 2Logical AND OperatorLogical OR OperatorLogical NOT OperatorOperator Precedence BasicsRecap - Making Comparisons7Control Flow: Loops
What The `for` Loop ExplainedFor Loop - BasicFor Loop - Condition OnlyThe `break` KeywordThe `continue` KeywordNested LoopsRecap - Repeating Actions2Variables and Basic Data Types
What is a variableType Inference with `:=`Integers (int)Floating-Point NumbersBooleansStringsZero ValuesConstantsNaming ConventionsRecap - Variables and Types5Basic Input/Output
Formatted OutputFormat VerbsPrinting TypesGetting Basic User InputRecap - Input and Output8Functions
Understanding FunctionsDeclaring a FunctionCalling FunctionsFunction ParametersReturning a Single ValueReturning Multiple ValuesNamed Return ValuesFunction Scope BasicsRecap - Creating Reusable Code3Basic Operators
Arithmetic OperatorsDivision OperatorThe Modulo OperatorAssignment OperatorAugmented Assignment OperatorsIncrement and DecrementRecap - Calculations6Control Flow: Conditionals
The `if` StatementThe `else` KeywordThe `else if` KeywordVariable Shadowing in `if`Initializing VariablesThe `switch` StatementSwitch with ExpressionsSwitch without ExpressionThe `fallthrough` KeywordRecap - Making Decisions