- What is a for loop and why it is used in C programming
- The syntax of for loop with initialization, condition, and update
- How the for loop works with step-by-step flowchart explanation
- How to write programs using standard for loop
- How to use infinite for loop (for;;) with break statement
Introduction to For Loop in C
The for loop in C programming is used to execute a block of code repeatedly for a known number of times until a specified condition is met. It is a fundamental control structure commonly used for iteration in C programs.
A for loop is especially useful when you need to repeat a task a specific number of times. It helps in writing efficient, clean, and organized code.
Common Use Cases of For Loop
- Generating number series — Even numbers, Fibonacci series, etc.
- Traversing arrays — Accessing elements in arrays, linked lists, or other data structures
- Processing student records — Looping through records to calculate grades
- Game development — Implementing repetitive tasks in games
- Searching — Searching for a value in an array
- Sorting — Sorting, searching, and traversing array elements
- CAPTCHA generation — Generating CAPTCHA codes for user verification
- Password validation — Validating password attempts within limited tries
- E-commerce — Calculating the total number of products and price in a shopping cart
💡 Key Point: Using the for loop efficiently can improve both performance and readability of your C programs.
For Loop Syntax in C
for (initialization; test_condition; update_expression) {
/* statements or body of the loop */
}
Let's break down each part:
🔹 Initialization: The initialization step is used to declare and initialize variables in the for loop. These variables have local scope and are accessible only within the loop body. This step is executed only once, before the loop starts. Multiple variables can be declared and initialized in the initialization section. It defines the starting point of the loop.
🔹 Test Condition: This condition determines whether the loop should continue executing. It is a boolean expression that evaluates to either true or false. If true, the loop body is executed. If false, the loop terminates, and control passes to the next statement after the loop. The body of the loop continues to execute as long as the test condition is true.
🔹 Update Expression: This is the final part of the loop definition. It is executed after each iteration and typically updates the loop control variable. The update expression helps control the number of iterations. If not handled correctly, the loop may become infinite.
Infinite For Loop Syntax
If the initialization, test condition, and update expression are all omitted, the loop becomes an infinite loop.
for ( ; ; ) {
/* statements or body of the loop */
}
⚠️ Note: The above loop will run infinitely because no initialization, test condition, or update expression is specified. To stop it, you need to use a break statement inside the loop body.
For Loop Flowchart
The diagram below shows the step-by-step control flow of a for loop in C programming.
Control Flow of a For Loop in C:
- Initialization (Declaration): This step executes only once, before the loop starts. In this section, the loop control variable is declared and initialized (e.g.,
int i = 0;). These variables have local scope within the loop. - Test Expression (Condition Check): The test condition is evaluated. If it returns
true, the loop continues to the next step. If it returnsfalse, the loop terminates, and control moves to the statement following the loop. - Loop Body Execution: If the test condition is satisfied, the statements inside the loop body are executed.
- Update Expression: After the loop body executes, the control variable is updated (e.g.,
i++;). This step is crucial for progressing toward the loop termination condition. - Repeat: Control returns to step 2 (test expression). This cycle continues until the test condition evaluates to
false.
⚠️ Important: If the initialization, test condition, or update expression is omitted, the loop may become an infinite loop. Always ensure the update expression eventually makes the condition false.
C Program to Demonstrate Standard For Loop
The program below prints numbers from 1 to 10 using a standard for loop.
/* This C program prints the numbers from 1 to 10 using a for loop */
#include <stdio.h>
int main() {
int i;
printf("\nFor loop to display numbers from 1 to 10\n");
for(i = 1; i <= 10; i++) {
printf(" %d", i);
}
return 0;
}
Sample Output:
For loop to display numbers from 1 to 10 1 2 3 4 5 6 7 8 9 10
Explanation:
- The variable
iis declared as an integer. - The program first prints the message: For loop to display numbers from 1 to 10.
- The for loop begins:
- The loop starts by setting
i = 1. - It checks if
i <= 10. Since 1 is less than or equal to 10, the loop body executes, printing the current value ofi. - After printing,
iincrements by 1 (i++). - The condition is checked again with the updated value of
i. - This process repeats, printing numbers from 1 through 10.
- When
ibecomes 11, the conditioni <= 10fails, and the loop stops.
- The loop starts by setting
- The program then ends, having displayed the numbers 1 to 10 on the screen.
C Program to Illustrate Infinite For Loop (for;;)
The program below displays numbers from 1 to 10 using a for(;;) infinite loop with a break statement.
/* C program to display numbers from 1 to 10 using for(;;) loop */
#include <stdio.h>
int main() {
int i = 1;
for(;;) {
printf(" %d", i);
i++;
if(i > 10)
break;
}
return 0;
}
Sample Output:
1 2 3 4 5 6 7 8 9 10
Explanation:
- We first declare and initialize
i = 1. - The control enters the
for(;;)loop. Since there is no initialization, condition, or update inside the loop header, the loop doesn't check any condition and directly enters the body. - The statement
printf(" %d", i);is executed, which prints the value ofi— in the first iteration, it's 1. - Then,
i++;increments the value ofiby 1. Now,ibecomes 2. - The
if(i > 10)condition is checked. Sincei = 2, the condition is false, so thebreakstatement is skipped. - Control goes back to the top of the loop. Again, since the loop header doesn't have any test condition, it continues and enters the loop body again.
- This process repeats:
iis printed, incremented, and then checked against the conditionif(i > 10). - When
ibecomes 11, the conditionif(i > 10)becomes true. So, thebreakstatement executes, which stops the loop. - The control comes out of the loop, and since there are no more statements in the program, it ends.
📝 Note: Even though for(;;) is an infinite loop, we've controlled its execution using the if and break statements. This pattern is sometimes used when the exit condition is complex or needs to be checked in the middle of the loop.
💻 Practice Exercise
Challenge: Write a program that prints the sum of all even numbers from 1 to 100 using a for loop.
🔍 Click to Show Solution
#include <stdio.h>
int main() {
int i, sum = 0;
for(i = 2; i <= 100; i += 2) {
sum = sum + i;
}
printf("Sum of even numbers from 1 to 100: %d\n", sum);
return 0;
}
/* Output: Sum of even numbers from 1 to 100: 2550 */
📝 Summary
- The for loop is used for known number of iterations
- It has three parts: initialization, condition, and update
- The initialization runs only once at the beginning
- The condition is checked before each iteration
- The update runs after each iteration
for(;;)creates an infinite loop that must be stopped withbreak- For loops are commonly used for array traversal, number series, and counting
Frequently Asked Questions About For Loop in C
1. What is a for loop in C?
A for loop is a control flow statement that allows you to execute a block of code repeatedly for a specific number of times. It consists of initialization, condition, and update expressions.
2. When should I use a for loop?
Use a for loop when you know the exact number of iterations in advance. For example, when traversing arrays, printing series, or performing calculations with a known count.
3. What happens if I omit the condition in for loop?
If you omit the condition, the loop becomes an infinite loop. For example, for(;;) will run forever unless you use a break statement inside the loop.
4. Can I declare variables inside the for loop initialization?
Yes, you can declare variables inside the initialization part. For example, for(int i = 0; i < 10; i++). These variables are local to the loop and cannot be accessed outside.
5. What is the difference between for loop and while loop?
A for loop is used when the number of iterations is known. A while loop is used when the number of iterations is unknown and depends on a condition. Both can achieve the same result, but for loop is more concise for counting.
💡 Tip: Always make sure the update expression eventually makes the condition false. Otherwise, you might create an infinite loop.