C Iteration statements for, while, do-while

Control flow statements are one of the basics of fundamental programming. In control flow statements, iterations are one of the most useful statements.

C loop statements like for, while, do-while, etc… are to execute a set of statements iteratively to do a specific objective multiple times.

for loop

For loop contains an initialization, condition, and assignment statements in it.

// Prototype of for loop.
for(initialisation; condition; assignment) {...}

This loop starts with one initialization and checks condition followed by executing all statements in its block and the assignment as the last statement in the loop. This loop ends once the condition fails (which returns false).

for loop control flow diagram.

Let’s see below example for better understanding of for loops.

int i;
int arr[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int len = sizeof(arr)/sizeof(arr[0]);
for(i=0; i<len; i++) {
    arr[i] = arr[i] * 5;
}

In the above example for loop multiplies each an every item in the array with value 5 until the end of the array.

while loop

Similar to for loop, while runs until a particular condition meets. Whereas here initialization and assignment are at user hands. It need not be part of while.

while(condition) { … }

Let’s try to understand same for loop example writing with while loop.

int i;
int arr[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int len = sizeof(arr)/sizeof(arr[0]);
i=0; // Initialisation out of while loop.
while(i<len) {
    arr[i] = 5 * arr[i];
    i++;  // Assignment here.
}

This program does the same behavior as it does in for loop. Every item in array replaces with its multiple of 5.

do-while loop

As every keyword has its purpose in C programming, the do-while loop has its purpose to do. Here in the do-while loop first run always happens irrespective of condition. All the rest of the executions are based on condition.

do { … } while(condition);

.

Lets write the same example program again using do-while loop.

int i;
int arr[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int len = sizeof(arr)/sizeof(arr[0]);
i=0; // Initialisation out of while loop.
do {
    arr[i] = 5 * arr[i];
    i++;  // Assignment here.
}while(i<len);

Here this gives the same output as earlier. Above are some most used iterative statements in C programming. If you find anything missing here, please help readers understand by commenting below.