Curriculum
The for
loop in C programming is a control flow statement that allows code to be executed repeatedly based on a given condition. It is particularly useful when the number of iterations is known before entering the loop. This tutorial will guide you through the basics and advanced usage of for
loops in C.
for
LoopThe for
loop has the following syntax:
for (initialization; condition; increment) { // Code to execute on each iteration }
Let’s start with a simple example that prints numbers from 1 to 5.
#include <stdio.h> int main() { for (int i = 1; i <= 5; i++) { printf("%dn", i); } return 0; }
In this example, the loop starts with i
initialized to 1. The condition i <= 5
is checked before each iteration, and i
is incremented by 1 after each iteration using i++
.
for
Loop for Array Processingfor
loops are particularly handy for iterating over arrays.
#include <stdio.h> int main() { int numbers[] = {2, 4, 6, 8, 10}; int length = sizeof(numbers) / sizeof(numbers[0]); for (int i = 0; i < length; i++) { printf("%dn", numbers[i]); } return 0; }
This code snippet iterates through an array of integers, printing each element to the console.
for
Loop VariantsYou can omit initialization and increment parts if they are not needed, but remember to maintain the semicolons.
#include <stdio.h> int main() { int i = 0; for (; i < 5;) { printf("%dn", ++i); // Use pre-increment to print from 1 to 5 } return 0; }
for
LoopYou can create an infinite loop by omitting the condition.
for (;;) { // This loop will run forever until broken out of or interrupted }
The for
loop is a versatile control structure in C that simplifies the process of writing loops that have a predetermined number of iterations. It is especially useful for iterating over arrays and performing repeated actions with a clear start and end point. Understanding how to effectively use for
loops will greatly enhance your ability to write efficient and readable C programs. Remember to watch out for common pitfalls, such as infinite loops and off-by-one errors, to ensure your loops function as intended.