Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Last Updated: Apr 2, 2024
Difficulty: Easy

For Loop in C

Leveraging ChatGPT - GenAI as a Microsoft Data Expert
Speaker
Prerita Agarwal
Data Specialist @
23 Jul, 2024 @ 01:30 PM

Introduction

For loops in C are like repeat commands that help in running a piece of code multiple times. This is very useful when you need to do the same action again & again, like counting numbers or going through a list of items. 

For Loop in C

In this article, we're going to learn how for loops work, their structure, and how to write them. We'll also look into some examples, understand nested for loops, and discuss their pros & cons. 

For Loop in C

A for loop in C is a control flow statement, which allows code to be executed repeatedly based on a condition. This loop is used when the number of iterations is known before the loop starts. Here's how it looks in a simple form:

for (initialization; condition; increment) {
    // Code to execute
}

 

  • Initialization: Here, we set a starting point. It's where we initialize our counter variables, and it's executed only once at the beginning.
     
  • Condition: This is the loop's test statement. As long as this condition remains true, the loop will keep running. When it turns false, the loop stops.
     
  • Increment: After each iteration of the loop, this part is executed. It's usually where we update the loop counter, moving closer to ending the loop.
     

Let's look at an example to understand better:

  • C

C

#include <stdio.h>

int main() {

   for (int i = 0; i < 5; i++) {

       printf("i is now %d\n", i);

   }

   return 0;

}

Output

i is now 0
i is now 1
i is now 2
i is now 3
i is now 4


In this example, the loop starts with i set to 0. The condition i < 5 is checked. If i is less than 5, the code inside the loop runs, and then i is increased by 1. This process repeats until i equals 5, at which point the loop stops.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Syntax of for Loop

The syntax of a for loop in C programming is straightforward and follows a specific pattern. Here’s the general structure:

for (initialization; condition; update) {
    // Statements to execute repeatedly
}

 

  • Initialization: This is where you declare and set your loop control variable. It’s executed only once, right before the loop starts.
     
  • Condition: This is a boolean expression that is checked before each iteration of the loop. If it evaluates to true, the loop continues; if false, the loop stops.
     
  • Update: This part is executed after each iteration of the loop. It’s typically used to update the loop control variable, which moves the loop towards its end condition.
     

Let’s break down a simple example to clarify:

for (int i = 0; i < 3; i++) {
    printf("%d ", i);
}


In this example:

  • Initialization: int i = 0; sets the starting point of the loop with i initialized to 0.
     
  • Condition: i < 3; is the condition checked before every loop iteration. The loop runs as long as i is less than 3.
     
  • Update: i++ increments the value of i by 1 after each loop iteration.
     

When this code runs, it prints out 0 1 2 , showing how the loop iterates three times with i taking values 0, 1, and 2 before the condition i < 3 becomes false, causing the loop to end.

Structure of For Loop

  • Initialization: This is the starting point. You declare your loop variable here and set an initial value. This part is executed only once at the beginning of the loop.
     
  • Condition: This is the heart of the loop. The loop will continue to run as long as this condition evaluates to true. Once the condition is false, the loop stops. This condition is checked before each iteration of the loop.
     
  • Increment/Decrement: After each loop iteration, this part is executed. It's used to update the loop variable, which could involve incrementing or decrementing it. This step is crucial for progressing the loop towards its stopping condition.
     

Here's what the structure looks like in a simple for loop:

for (int i = 0; i < 10; i++) {
    // Loop body: This code is executed repeatedly
    printf("Value of i: %d\n", i);
}


In this example:

  • Initialization: int i = 0; sets up a loop variable i and starts it at 0.
     
  • Condition: i < 10; determines the loop will run as long as i is less than 10.
     
  • Increment: i++ increases the value of i by 1 after each iteration.
     

The loop body, where printf is used, is the code executed with each loop iteration. This structure allows for repeated execution of code blocks, making tasks like iterating over arrays or generating repeated output straightforward.

How For Loop works?

Start with Initialization

The loop kicks off by setting an initial value for the loop variable. This happens just once, setting the stage for the first iteration.

Check the Condition

Before each iteration, the loop checks if the condition is true. This condition usually involves the loop variable. If the condition is true, the loop continues; if false, the loop ends, and the program moves on to the code that follows.

Execute Loop Body

If the condition is true, the loop executes the block of code within its body. This is where the actions you want to repeat are placed.

Update Loop Variable

After executing the loop body, the loop updates the variable according to the increment/decrement part. This step is crucial for moving towards the condition becoming false and thus preventing an infinite loop.

Repeat

The process from step 2 to 4 repeats until the condition becomes false.

Here's a simple example to illustrate this:

for (int num = 1; num <= 5; num++) {
    printf("Number: %d\n", num);
}


In this example:

  • Initialization: num starts at 1.
     
  • Condition: Check if num is less than or equal to 5.
     
  • Loop Body: Print the current value of num.
     
  • Increment: Increase num by 1.
     

The loop goes back to checking the condition with the new value of num, repeating until num is greater than 5.

Flowchart of For Loop

Flowchart of For Loop

Start

This is where the loop begins. We have an entry point in the flowchart.

Initialization

Set up the loop counter to its starting value. This happens only once.

Condition Check

Evaluate the loop's condition. If it's true, move forward; if false, exit the loop.

Loop Body

Execute the statements inside the loop.

Increment/Decrement

Update the loop counter.

Back to Condition Check

Return to step 3 to evaluate the condition again with the updated loop counter.

End

If the condition is false, the loop ends, and we move out of the loop in the flowchart.

Examples of For Loop

Example 1: Basic Counter

A simple use of a for loop is to create a counter that prints numbers from 1 to 5.

  • C

C

#include <stdio.h>

int main() {
for (int i = 1; i <= 5; i++) {
printf("%d\n", i);
}
return 0;
}

Output

1
2
3
4
5


In this code, i starts at 1 and increases by 1 each time the loop runs, stopping after printing 5.

Example 2: Sum of Numbers

We can use a for loop to calculate the sum of the first 10 natural numbers.

  • C

C

#include <stdio.h>

int main() {
int sum = 0;
for (int i = 1; i <= 10; i++) {
sum += i; // Adds i to sum
}
printf("Sum = %d\n", sum);
return 0;
}

Output

Sum = 55

Here, sum is initially 0. With each iteration, the current value of i is added to sum. After the loop, sum contains the total sum.

Example 3: Multiplication Table

For loops can also be used to print a multiplication table for a number.

  • C

C

#include <stdio.h>

int main() {
int num = 3;
for (int i = 1; i <= 10; i++) {
printf("%d x %d = %d\n", num, i, num*i);
}
return 0;
}

Output

3 x 1 = 3
3 x 2 = 6
3 x 3 = 9
3 x 4 = 12
3 x 5 = 15
3 x 6 = 18
3 x 7 = 21
3 x 8 = 24
3 x 9 = 27
3 x 10 = 30


This loop will print the multiplication table for 3, from 3 x 1 up to 3 x 10.

Nested for Loop in C

A nested for loop means putting one for loop inside another for loop. This can be useful for tasks that require working with items in a grid-like structure, such as tables or matrices.

Here's a simple example to illustrate how a nested for loop works:

  • C

C

#include <stdio.h>

int main() {
for (int i = 1; i <= 3; i++) { // Outer loop
for (int j = 1; j <= 3; j++) { // Inner loop
printf("(%d, %d) ", i, j);
}
printf("\n"); // Moves to the next line after each inner loop
}
return 0;
}

Output

(1, 1) (1, 2) (1, 3)
(2, 1) (2, 2) (2, 3) 
(3, 1) (3, 2) (3, 3) 


In this code, the outer loop uses i as its counter, and the inner loop uses j. For each value of i in the outer loop, the inner loop runs completely, going through all its j values. This creates a pair of (i, j) values for each iteration of the inner loop.

This kind of loop is very powerful for dealing with multi-dimensional data or when you need to perform repetitive tasks within repetitive tasks.

Advantages of For Loop

Clarity

For loops make it clear that you're performing a repetitive action. This can make your code easier to read and understand, especially for others looking at your work.

Control

They give you precise control over how many times a block of code is executed. This is particularly useful when the number of iterations is known before the loop starts.

Simplicity

For loops can make your code more concise. Instead of writing several lines of similar code, you can condense it into a few lines within a loop.

Flexibility

You can easily adjust the starting point, ending point, and step size of your loop. This makes for loops versatile for a range of tasks, from simple counting to more complex calculations.

Efficiency

In many cases, for loops can be more efficient than other looping constructs, especially when dealing with fixed-size data structures like arrays.

Nested Looping

For loops can be nested within each other to handle multi-dimensional data structures or perform complex tasks that require multiple levels of looping.

Disadvantages of For Loop

Fixed Iterations

For loops work best when you know in advance how many times you need to iterate. If the number of iterations is dynamic or unknown, a for loop might not be the most efficient choice.

Complexity

Nested for loops can make your code more complex and harder to read, especially if there are multiple levels of nesting. This can lead to errors that are difficult to debug.

Resource Use

For loops that involve complex calculations or operations can be resource-intensive, especially if the loop runs a large number of times. This can affect the performance of your program.

Limited Use

While for loops are great for iteration, they might not be suitable for scenarios where tasks need to be repeated based on a condition rather than a fixed number of times. In such cases, while or do-while loops might be more appropriate.

Overhead

The initialization and increment/decrement steps in a for loop create a small overhead, which, though minimal, can add up in very performance-sensitive applications.

Accidental Infinite Loops

If the condition in a for loop is incorrectly set or the increment/decrement step doesn't effectively move towards completing the condition, it can lead to an infinite loop, causing the program to hang or crash.

Frequently Asked Questions

Can a for loop be used for infinite loops?

Yes, a for loop can be used for infinite loops by omitting the condition, like for (;;) which will loop indefinitely. However, this should be used with caution to avoid unintended infinite loops.

Is it possible to break out of a for loop before the condition is false?

Absolutely. You can use the break statement within the loop. When executed, break will immediately exit the loop, regardless of the condition.

Can for loops only increment by 1 each time?

No, you can increment (or decrement) by any amount in the increment/decrement step of the for loop. For example, for (int i = 0; i < 10; i += 2) will increase i by 2 in each iteration.

Conclusion

In this article, we've learned the concept of for loops in C, starting from what they are and how they're structured and it’s examples to understanstand its implementation. We've explored nested for loops, and learned its advantages and disadvantages providing a comprehensive understanding of their utility and limitations.

You can refer to our guided paths on the Coding Ninjas. You can check our course to learn more about DSADBMSCompetitive ProgrammingPythonJavaJavaScript, etc. Also, check out some of the Guided Paths on topics such as Data Structure and AlgorithmsCompetitive ProgrammingOperating SystemsComputer Networks, DBMSSystem Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry Experts.

Topics covered
1.
Introduction
2.
For Loop in C
2.1.
C
3.
Syntax of for Loop
4.
Structure of For Loop
5.
How For Loop works?
5.1.
Start with Initialization
5.2.
Check the Condition
5.3.
Execute Loop Body
5.4.
Update Loop Variable
5.5.
Repeat
6.
Flowchart of For Loop
6.1.
Start
6.2.
Initialization
6.3.
Condition Check
6.4.
Loop Body
6.5.
Increment/Decrement
6.6.
Back to Condition Check
6.7.
End
7.
Examples of For Loop
7.1.
Example 1: Basic Counter
7.2.
C
7.3.
Example 2: Sum of Numbers
7.4.
C
7.5.
Example 3: Multiplication Table
7.6.
C
7.7.
Nested for Loop in C
7.8.
C
8.
Advantages of For Loop
8.1.
Clarity
8.2.
Control
8.3.
Simplicity
8.4.
Flexibility
8.5.
Efficiency
8.6.
Nested Looping
9.
Disadvantages of For Loop
9.1.
Fixed Iterations
9.2.
Complexity
9.3.
Resource Use
9.4.
Limited Use
9.5.
Overhead
9.6.
Accidental Infinite Loops
10.
Frequently Asked Questions
10.1.
Can a for loop be used for infinite loops?
10.2.
Is it possible to break out of a for loop before the condition is false?
10.3.
Can for loops only increment by 1 each time?
11.
Conclusion