Home >Backend Development >C++ >Loops in C: A Simple Guide with Examples
Loops are essential tools in programming that allow us to execute a block of code repeatedly. They can perform a variety of tasks, from simple calculations to complex data processing.
In C programming, we have three main types of loops: for, while, and do-while. Let's explore each of them with examples.
The for loop is the default choice when we know exactly how many times we want to repeat a block of code. It's like setting a timer for our code to run a specific number of times.
// syntax for (initialization; condition; increment/decrement) { // Code to be executed in each iteration } // example #include <stdio.h> int main() { for (int i = 1; i <= 5; i++) { printf("%d ", i); } printf("\n"); // Output: 1 2 3 4 5 return 0; }
In this example, the for loop prints the numbers from 1 to 5 . The initialization ( int i = 1; ) sets the starting value of the counter variable i . The condition ( i <= 5; ) specifies that the loop should continue as long as i is less than or equal to 5 . The increment ( i ) increases the value of i by 1 after each iteration.
The while loop is like a conditional loop. It keeps spinning (executing the code block) as long as the condition remains true.
// syntax while (condition) { // Code to be executed repeatedly } // example #include <stdio.h> int main() { int i = 1; while (i <= 5) { printf("%d ", i); i++; } printf("\n"); // Output: 1 2 3 4 5 return 0; }
This while loop achieves the same result as the for loop above. It prints the numbers from 1 to 5 , but the counter variable i is initialized and incremented outside the loop structure.
The do-while loop insists on executing the code block at least once, even if the condition is initially false.
// syntax do { // Code to be executed repeatedly } while (condition); // example #include <stdio.h> int main() { int i = 6; // Notice i is initialized to 6 do { printf("%d ", i); i++; } while (i <= 5); printf("\n"); // Output: 6 return 0; }
Even though the condition i <= 5 is false from the start, the do-while loop still executes the code block once, printing the value of i (which is 6).
Loops are incredibly versatile and have a wide range of applications in programming:
Lastly, since loops are fundamental in programming, understanding them in C will prepare you to learn other languages like Python, JavaScript, and Java.
The above is the detailed content of Loops in C: A Simple Guide with Examples. For more information, please follow other related articles on the PHP Chinese website!