C Tutorial

Loops in C - for, while, and do-while


Introduction

Loops are essential in C programming for repeating a block of code multiple times. They allow you to automate tasks and perform operations with varying data. In this tutorial, we will explore three primary types of loops in C: for, while, and do-while. We'll cover their usage with sample code to illustrate their functionality.

for Loop

The for loop allows you to repeatedly execute a block of code for a specific number of times:

#include <stdio.h> int main() { int i; for (i = 1; i <= 5; i++) { printf(`Iteration %d\n`, i); } return 0; }

In this example, the for loop runs five iterations and prints `Iteration 1` to `Iteration 5.`

while Loop

The while loop allows you to repeatedly execute a block of code as long as a condition is true:

#include <stdio.h> int main() { int count = 0; while (count < 5) { printf(`Count: %d\n`, count); count++; } return 0; }

In this example, the while loop runs until count becomes greater than or equal to 5. It prints `Count: 0` to `Count: 4.`

do-while Loop

The do-while loop is similar to the while loop but guarantees at least one execution of the code block:

#include <stdio.h> int main() { int number = 0; do { printf(`Number: %d\n`, number); number++; } while (number < 5); return 0; }

In this example, the do-while loop runs at least once, and then it continues executing as long as number is less than 5. It prints `Number: 0` to `Number: 4.`

Conclusion

Loops are powerful tools in C programming for repetitive tasks and automation. You've learned how to use for, while, and do-while loops with sample code. Understanding and mastering loops is crucial for building efficient and dynamic programs in C.

Written by Surfside Media

Senior Full Stack Developer specializing in Web Technologies.