For working professionals
For fresh graduates
More
5. Array in C
13. Boolean in C
18. Operators in C
33. Comments in C
38. Constants in C
41. Data Types in C
49. Double In C
58. For Loop in C
60. Functions in C
70. Identifiers in C
81. Linked list in C
83. Macros in C
86. Nested Loop in C
97. Pseudo-Code In C
100. Recursion in C
103. Square Root in C
104. Stack in C
106. Static function in C
107. Stdio.h in C
108. Storage Classes in C
109. strcat() in C
110. Strcmp in C
111. Strcpy in C
114. String Length in C
115. String Pointer in C
116. strlen() in C
117. Structures in C
119. Switch Case in C
120. C Ternary Operator
121. Tokens in C
125. Type Casting in C
126. Types of Error in C
127. Unary Operator in C
128. Use of C Language
The for loop in C is one of the most essential control structures used for iteration. It allows programmers to execute a block of code repeatedly, with a well-defined start and end point. Whether you want to print a sequence of numbers, iterate through an array, or perform complex calculations, the for loop in C is often the best tool for the job.
In this article, we will explore everything you need to know about the for loop in C programming. We will cover its syntax, working mechanism, and practical use cases. You will also see basic, intermediate, and advanced examples, along with detailed explanations and outputs. Besides all this, we will discuss nested and infinite for loops, common mistakes to avoid, and frequently asked questions to clear your doubts.
You should explore our software development courses to understand programming concepts in a more efficient way.
In C programming, a for loop is a control structure used to execute a block of code repeatedly. It works best when the number of iterations is already known. The loop relies on a loop control variable that changes with each iteration until a certain condition is met.
The for loop in C is especially useful when you want to run a block of code a fixed number of times. Unlike the while loop, which is condition-based, the for loop is ideal for count-controlled repetition. Programmers often use it for tasks like printing sequences, iterating through arrays, or performing repetitive calculations.
Boost your career journey with the following online courses:
Let’s now look at the basic syntax of the for loop in C, which shows how it is structured and how each part works together.
Here is the standard syntax of a for loop in C:
for (initialization; condition; increment/decrement) {
// Code block to be executed
}
Explanation of Syntax:
Let’s understand the for loop in c with a simple example.
Task: We want to print numbers from 1 to 5 using a for loop.
Before writing the code: We will create a loop that starts with i = 1 and runs until i becomes 5. After printing each number, we will increase the value of i by 1.
#include <stdio.h>
int main() {
// Loop from 1 to 5
for (int i = 1; i <= 5; i++) {
printf("%d\n", i); // Print the current value of i
}
return 0;
}
Output:
1
2
3
4
5
Explanation:
Interested in learning about Do While Loop in C? If so, read the Understanding Do While Loop in C article!
The for loop in C works by repeating a set of instructions based on a specific condition. It has three main parts: initialization, condition checking, and increment or decrement. These parts work together to control the flow of the loop.
When a for loop starts, it first sets the initial value of the loop variable. Then it checks whether the loop condition is true. If the condition is true, the code inside the loop runs. After each loop iteration, the loop variable updates. This process repeats until the condition becomes false.
Let’s now see a simple example that shows the full working process of the for loop in C step by step.
Before writing the code: We will write a loop that prints numbers from 1 to 3. This example will help you understand how initialization, condition checking, and increment work in each loop cycle.
#include <stdio.h>
int main() {
// Start the loop with i = 1, run till i <= 3, and increment i by 1 each time
for (int i = 1; i <= 3; i++) {
printf("Current number: %d\n", i); // Print the current number
}
return 0;
}
Output:
Current number: 1
Current number: 2
Current number: 3
Explanation:
Flow Recap:
Iteration | i Value Before Loop | Condition (i <= 3) | Output Printed | i After Increment |
1 | 1 | True | Current number: 1 | 2 |
2 | 2 | True | Current number: 2 | 3 |
3 | 3 | True | Current number: 3 | 4 |
4 | 4 | False | (No output, loop ends) | - |
The for loop in C is ideal when you need to execute a block of code a specific number of times. It is preferred in situations where the number of iterations is known in advance.
Below are the key cases where using a for loop in C programming is the best choice:
Must Explore: Python’s do-while Loop
Let’s now explore practical examples of the for loop in C, divided into basic, intermediate, and advanced levels. Each example will help you understand how the for loop works in different scenarios, from simple counting to more complex logic.
In this example, we will print the multiplication table of 2 up to 10 using a simple for loop. This helps beginners understand how to work with loops that involve calculations.
Before writing the code: We will run a loop from 1 to 10. In each iteration, we will multiply 2 by the current number and print the result.
#include <stdio.h>
int main() {
// Loop to print the multiplication table of 2
for (int i = 1; i <= 10; i++) {
printf("2 x %d = %d\n", i, 2 * i); // Print the result
}
return 0;
}
Output:
2 x 1 = 2
2 x 2 = 4
2 x 3 = 6
2 x 4 = 8
2 x 5 = 10
2 x 6 = 12
2 x 7 = 14
2 x 8 = 16
2 x 9 = 18
2 x 10 = 20
Explanation:
In this intermediate example, we will calculate the sum of the first 10 natural numbers using a for loop. This will help you understand how to accumulate values inside the loop.
Before writing the code: We will declare a sum variable and run a loop from 1 to 10. In each loop, we will add the current number to the sum.
#include <stdio.h>
int main() {
int sum = 0; // Variable to store the total sum
// Loop to add numbers from 1 to 10
for (int i = 1; i <= 10; i++) {
sum += i; // Add the current value of i to sum
}
printf("Sum of first 10 natural numbers is: %d\n", sum);
return 0;
}
Output:
Sum of first 10 natural numbers is: 55
Explanation:
In this advanced example, we will print a right-angled triangle pattern using a nested for loop in C. This demonstrates how nested loops work together to create patterns.
Before writing the code: We will use two for loops. The outer loop controls the rows, and the inner loop prints stars in each row.
#include <stdio.h>
int main() {
int sum = 0; // Variable to store the total sum
// Loop to add numbers from 1 to 10
for (int i = 1; i <= 10; i++) {
sum += i; // Add the current value of i to sum
}
printf("Sum of first 10 natural numbers is: %d\n", sum);
return 0;
}
Output:
*
* *
* * *
* * * *
* * * * *
Explanation:
A nested for loop in C is a loop inside another loop. It allows you to perform repetitive tasks in a multi-dimensional space. In most cases, nested loops are used for working with multi-dimensional arrays, printing patterns, or other complex tasks where you need to loop through multiple dimensions.
Explanation of Nested For Loop:
In the following example, we will print a pattern of stars to better understand how nested for loops work.
Example: Printing a Square Pattern of Stars
#include <stdio.h>
int main() {
int rows = 5; // Define the number of rows
// Outer loop for rows
for (int i = 1; i <= rows; i++) {
// Inner loop for columns (printing stars)
for (int j = 1; j <= rows; j++) {
printf("* "); // Print a star
}
printf("\n"); // Move to the next line after each row
}
return 0;
}
Output:
* * * * *
* * * * *
* * * * *
* * * * *
* * * * *
Explanation:
Also read: Looping Statements in Java: Types, Syntax, Examples & Best Practices article.
Nested for loops are useful when:
An infinite for loop in C is a loop that runs endlessly without stopping. It occurs when the loop’s termination condition is never met. In most cases, this happens when the loop's condition is set in such a way that it always evaluates to true.
Explanation of Infinite For Loop
In the following example, we’ll demonstrate an infinite for loop.
Before writing the code: We will set up a loop where the condition always evaluates to true. This ensures that the loop never exits.
#include <stdio.h>
int main() {
// Infinite loop
for (;;) {
printf("Hello, World!\n"); // This will keep printing forever
}
return 0;
}
Output:
Hello, World!
Hello, World!
Hello, World!
...
Note: The program will keep printing "Hello, World!" indefinitely until you stop the program manually (e.g., using Ctrl+C in the terminal).
Explanation:
Use of Infinite Loops:
Note: Infinite loops should be used cautiously. They can cause a program to hang or consume excessive system resources. It is important to ensure that an infinite loop is necessary for the task and that there is a way to terminate or exit the loop if needed.
When using for loops in C, beginners and even experienced programmers can sometimes make common mistakes. These errors can lead to unexpected behavior or inefficient code.
Let’s look at some of these errors and how to avoid them.
The for loop in C is one of the most powerful and flexible tools for controlling repetitive tasks. It allows programmers to run a block of code a specific number of times, making it ideal for scenarios where the number of iterations is known in advance. By understanding its syntax, working mechanism, and practical use cases, you can write efficient and clean code.
Always remember to test your code carefully and watch out for common errors like incorrect conditions or off-by-one mistakes. With practice, using the for loop in C will become second nature, helping you build more robust programs.
What is a for loop in C used for?
The for loop in C is used to execute a block of code repeatedly for a fixed number of times. It is ideal when you know beforehand how many times the loop should run, making it efficient for tasks like counting or iterating over arrays.
Can we use multiple variables in a for loop in C?
Yes, you can use multiple variables in a for loop in C by separating them with commas in the initialization and update sections. However, the loop condition can only include one condition that determines when the loop should stop.
What happens if the condition in a for loop is always true?
If the condition in a for loop is always true, the loop becomes infinite. This means it keeps running endlessly unless a break statement is used inside the loop to stop it manually when a certain condition is met.
Can the for loop in C be replaced by a while loop?
Yes, any for loop in C can technically be rewritten using a while loop. However, the for loop is more compact and readable when you know the exact number of iterations needed, whereas the while loop suits unknown iteration counts.
What is the syntax of a for loop in C?
The basic syntax of a for loop in C is:
for (initialization; condition; update) { // code block }
It starts with initialization, checks the condition before each iteration, and updates the loop variable after each loop cycle.
What is an off-by-one error in a for loop?
An off-by-one error occurs when your loop runs one time too many or too few. This usually happens due to incorrect use of comparison operators in the condition. Careful planning of loop bounds helps avoid this mistake.
Can we omit any part of the for loop syntax in C?
Yes, in C, the initialization, condition, and update parts of a for loop are optional. If you omit the condition, it becomes an infinite loop. However, leaving out sections should be done cautiously to maintain readability.
How does a nested for loop work in C?
A nested for loop in C means placing one for loop inside another. The inner loop completes all its iterations for every single iteration of the outer loop. This is useful for working with multi-dimensional arrays or complex pattern printing.
What is the difference between a for loop and a do-while loop in C?
The key difference is that a for loop checks the condition before executing the code block, while a do-while loop runs the code block at least once before checking the condition. This makes do-while loops useful when one execution is guaranteed.
How do you stop a for loop in C before it finishes?
You can stop a for loop before it completes by using the break statement. When break is encountered inside the loop, it immediately exits the loop, skipping any remaining iterations, and continues with the next part of the program.
Is it possible to create an infinite for loop in C intentionally?
Yes, you can create an infinite for loop in C by writing the loop without a condition or by setting the condition to always be true. This is often used in embedded systems or programs that need to run continuously until manually stopped.
Take a Free C Programming Quiz
Answer quick questions and assess your C programming knowledge
Author
Start Learning For Free
Explore Our Free Software Tutorials and Elevate your Career.
Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)
Indian Nationals
1800 210 2020
Foreign Nationals
+918068792934
1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.
2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.