Welcome to our comprehensive guide on C's For Loop! In this lesson, we'll explore one of the most fundamental control structures in C programming, and understand its practical applications with real-world examples. Let's get started!
A For Loop is a control structure used to iterate a specific number of times in C programming. It's a handy tool when you want to repeat a set of instructions, making it a crucial part of any C developer's arsenal.
for (initialization; condition; increment/decrement) {
// code to be executed
}The above syntax consists of three components:
Let's print numbers from 1 to 10 using a For Loop:
#include <stdio.h>
int main() {
int i;
for (i = 1; i <= 10; i++) {
printf("Number: %d\n", i);
}
return 0;
}In this example, i is our loop variable. The loop will run as long as i is less than or equal to 10, and after each iteration, i will increment by 1.
For Loops are incredibly useful when working with arrays. Let's display all the elements of an array using a For Loop:
#include <stdio.h>
int main() {
int arr[] = {1, 2, 3, 4, 5};
int i;
int arrSize = sizeof(arr) / sizeof(arr[0]);
for (i = 0; i < arrSize; i++) {
printf("Element: %d\n", arr[i]);
}
return 0;
}In this example, we use the For Loop to iterate over every element of an array. We first calculate the size of the array, then loop through it using the arrSize and arr[i].
We hope you enjoyed this comprehensive guide on C's For Loop! Stay tuned for more engaging lessons on C programming. Happy coding! 💻🚀