For Loop
This Go code demonstrates various usage of the for
loop, including basic loop structure, loop with a condition, an infinite loop with a break
statement, and using continue
to skip certain iterations. Let's go through each part of the code:
Output
Explanation:
for i <= 3 {...}
: A basicfor
loop with a condition. It initializesi
to 1 and continues looping as long asi
is less than or equal to 3. It prints the value ofi
in each iteration and incrementsi
by 1.for j := 7; j <= 9; j++ {...}
: Anotherfor
loop with an initialization statement (j := 7
), a condition (j <= 9
), and a post statement (j++
). It initializesj
to 7, continues looping as long asj
is less than or equal to 9, prints the value ofj
in each iteration, and incrementsj
by 1.for {...}
: An infinite loop. It continually prints "loop" and breaks out of the loop using thebreak
statement after the first iteration.for n := 0; n <= 5; n++ {...}
: Afor
loop with an initialization statement, a condition, and a post statement. It initializesn
to 0, continues looping as long asn
is less than or equal to 5, incrementsn
by 1 in each iteration, and prints the value ofn
only if it's an odd number (usingif n%2 == 0 { continue }
to skip even numbers).
Last updated
Was this helpful?