Introduction to the For Loop in C
The for loop in C is a powerful way to repeat a block of code a specific number of times. Its structure is compact and especially useful for counting and iterating over a range of values.
The anatomy of a for loop consists of three main parts: initialization, condition, and increment. These parts are placed inside the parentheses following the for keyword, separated by semicolons. Each plays an essential role in controlling the loop's execution.
main.c
12345678910#include <stdio.h> int main() { // Print the first 10 even numbers using a for loop int i; for (i = 1; i <= 10; i++) { // initialization: i = 1; condition: i <= 10; increment: i++ printf("%d\n", i * 2); } return 0; }
In the example above, the initialization (i = 1) sets up the loop variable before the loop starts. The condition (i <= 10) is checked before each iteration; as long as it remains true, the loop continues.
The increment (i++) updates the loop variable after every iteration. This pattern lets you control the number of times the loop runs. The loop variable changes with each repetition, and when the condition becomes false, the loop stops. This makes for loops ideal for tasks where you know in advance how many times you need to repeat an action.
Use a for loop when you know exactly how many times you want to repeat a block of code.
Bedankt voor je feedback!
Vraag AI
Vraag AI
Vraag wat u wilt of probeer een van de voorgestelde vragen om onze chat te starten.
Geweldig!
Completion tarief verbeterd naar 9.09
Introduction to the For Loop in C
Veeg om het menu te tonen
The for loop in C is a powerful way to repeat a block of code a specific number of times. Its structure is compact and especially useful for counting and iterating over a range of values.
The anatomy of a for loop consists of three main parts: initialization, condition, and increment. These parts are placed inside the parentheses following the for keyword, separated by semicolons. Each plays an essential role in controlling the loop's execution.
main.c
12345678910#include <stdio.h> int main() { // Print the first 10 even numbers using a for loop int i; for (i = 1; i <= 10; i++) { // initialization: i = 1; condition: i <= 10; increment: i++ printf("%d\n", i * 2); } return 0; }
In the example above, the initialization (i = 1) sets up the loop variable before the loop starts. The condition (i <= 10) is checked before each iteration; as long as it remains true, the loop continues.
The increment (i++) updates the loop variable after every iteration. This pattern lets you control the number of times the loop runs. The loop variable changes with each repetition, and when the condition becomes false, the loop stops. This makes for loops ideal for tasks where you know in advance how many times you need to repeat an action.
Use a for loop when you know exactly how many times you want to repeat a block of code.
Bedankt voor je feedback!