In this shot, we’ll learn about the for
loop in the D programming language. Loops are code blocks that repeat a particular logic until a condition is satisfied.
for ( init; condition; increment ) { statement(s); }
init
: This initializes the loop counter value.condition
: This evaluates each for
loop iteration. The loop ends once evaluated false
.increment
: This increases the loop counter value.import std.stdio; int main () { /* for loop execution */ for( int a = 1; a < 20; a = a + 2 ) { writefln("Increasing by 2: %d", a); } return 0; }
Line 5: We initiate the for
loop.
The first argument in our for
loop is to declare our counter variable int i = 1
. The counter variable is used to know the number of iterations made by the for
loop.
The second argument in the for
loop is a condition. We use the condition to tell the for
loop when to start and stop.
The third argument in the for
loop is the increment. It increases the value of the counter variable, enabling us to keep track of the iterations made by the for
loop.
Line 6: We print the counter variable to the screen to illustrate the number of iterations made by the for
loop.
RELATED TAGS
CONTRIBUTOR
View all Courses