For loop in C

Learn via video course
FREE
View all courses
C++ Course: Learn the Essentials
C++ Course: Learn the Essentials
by Prateek Narang
1000
5
Start Learning
C++ Course: Learn the Essentials
C++ Course: Learn the Essentials
by Prateek Narang
1000
5
Start Learning
Topics Covered

A for loop in C is a control structure that is used to run a block of instructions multiple times until a certain condition fails. In this article, we will be learning about loops in c.

Syntax of for loop in C

We have discussed, what is for loop in C?

Now let's discuss the Syntax of for loop in C is as follows:

Structure of For Loop in C

Aside from the above syntax, there are many other ways we can run for loops. Some don't require an initialization, some don't require an updation, and some don't require both! Here are a few ways to run for loops:

A) NO INITIALIZATION: Initialization can be skipped, as shown below:

B) NO UPDATION: We can run a for loop without needing an updation in the following way:

C) NO INITIALIZATION AND UPDATE STATEMENT: We can avoid both initialization and update statements too!

We can see that this syntax is similar to the while loop if we notice carefully. Using a while loop is a better choice than running a for loop with this syntax.

How for Loop Work?

Here's how the for loop works in C:

  1. Step 1: Initialization - At the beginning of the loop, variables are declared or initialized with a starting value. This step occurs only once.
  2. Step 2: Condition Check - Before each iteration, the condition statement is checked, and if the condition is true, then only the loop continues, otherwise, the loop will break and the control exits the loop.
  3. Step 3: Execution of Statements - All the statements inside the loop body are executed.
  4. Step 4: Update - After executing the statements inside the loop, the loop control variable(s) are updated as defined in the loop (e.g., incrementing or decrementing a counter variable).
  5. Continue to Step 2: After completing all the steps, the loop control returns to Step 2, where the condition is rechecked.
  6. If the condition is still true, the loop continues; otherwise, it exits.
  7. This cycle continues until the condition evaluates to false, at which point the loop terminates.

Flow Chart of for Loop in C

FLOWCHART OF FOR LOOP in c

for Loop Example in C

Let's discuss the for loop example in C.

For the case of the company wanting to calculate the salary and bonus of their employees we have taken the above:

OUTPUT:

Special Conditions with C For Loops

1. for loop without curly braces

In C, it's possible to use a for loop without enclosing the loop body within curly braces if there's only a single statement to execute. For example:

This code snippet prints numbers from 0 to 4. While it's allowed in C, it's generally considered good practice to enclose loop bodies within curly braces for clarity and to avoid potential issues with unintended behaviour.

2. Infinite for loop / Null Parameter Loop

An infinite loop in C can be created using a for loop with no initialization, condition, or iteration step specified. For example:

This loop will continue to execute indefinitely until it's terminated externally (e.g., by interrupting the program). Infinite loops are typically avoided in most programming scenarios, but they can be useful in situations where continuous execution is required, such as embedded systems or server applications. However, caution must be practised to prevent consequences, such as resource exhaustion or system crashes.

Advantages of For Loops

  1. Readability: for Loops offer a clear and concise syntax, enhancing code readability compared to while or do-while loops, especially for iterating over sequences or collections.

  2. Controlled Iteration: They provide precise control over loop iteration, with explicit initialization, termination conditions, and iteration steps, making it easier to manage loop behaviour.

  3. Compactness: for loops typically require fewer lines of code than equivalent while loops, simplifying code maintenance and reducing the likelihood of errors.

  4. Efficiency: for loops often result in faster execution compared to other loop types due to their optimized structure, especially when iterating over arrays or other indexed data structures.

  5. Scope Management: Variables declared within the for loop initialization are confined to the loop's scope, preventing unintentional variable exposure and potential conflicts outside the loop.

Limitations

  1. Initialization Overhead: for loops require explicit initialization, which can sometimes lead to additional overhead, especially when dealing with complex initialization expressions.
  2. Fixed Iteration: For loops are primarily suited for situations where the number of iterations is known beforehand. They may be unsuitable for cases where the iteration count depends on dynamic conditions.
  3. Complexity for Non-Linear Iteration: While for loops excel at linear iteration (e.g., iterating over arrays), they can become cumbersome when dealing with non-linear iteration patterns or when skipping or repeating iterations.
  4. Scope Leakage: Variables declared within the initialization expression of a for loop remain accessible after the loop completes its execution, potentially leading to unintended side effects or scope leakage.
  5. Potential for Infinite Loops: Incorrectly defined termination conditions or iteration steps can lead to infinite loops, causing the program to hang or crash. Careful attention is required to ensure proper termination conditions are set.

Conclusion

  • for loops are used to iterate over a sequence.
  • It iterates a preset number of times and stops as soon as conditions are met.
  • Without a condition, the loop will iterate indefinitely until it encounters the break command.
  • Loops run to produce a result or to satisfy a condition or set of requirements.