Loop in C Part II


In the first part of tutorial we have studied about while and do-while loop. In this tutorial we are going to study ‘for loop’, a very important loop in C, and off course very handy one. In for loop number of repetitions needed for the loop is known before the loop begins; these loops have control variables to count repetitions. Counter controlled repetitions need initialized control variable (loop counter), an increment (or decrement) statement and a condition used to terminate the loop (continuation condition).

Syntex:

for(control_variable;  continuation_condition;  increment or decrement)

{                 
            Single statement

       or Block of statements 
}

 

For loop can be implemented in different verities of using for loop –

  • Single Statement inside For Loop
  • Multiple Statements inside For Loop
  • No Statement inside For Loop
  • Semicolon at the end of For Loop
  • Multiple Initialization Statement inside For
  • Missing Initialization in For Loop
  • Missing Increment/Decrement Statement
  • Infinite For Loop
  • Condition with no Conditional Operator.

Examples:

#include <stdio.h>

#define my_field  9

void main()

{

int i = 0;

for(i = 0;i<=my_field; i++)

{

printf("I am learning for loop\n");

}

getch();

}

 

 

There is one more thing if you write for loop as:

                                                                         for(i=0;i<=my_field; i++);

Here we have a semicolon at the end, if you expect that compiler is going to through an error for this, then you are wron. This is a perfect statement in C; compiler takes it as bodyless for loop.

There is always a two mind that where and when we should use for loop and while loop, and which one is more convenient for compiler.The performance difference between for loop and while loop is not a big issue because modern compilers can generate same machine code for both loops and secondly both loops require same operations:

  • Initialization of counter variable.
  • Test condition.
  • Increment / decrement in counter variable.

In general you should use for loop in your code for the following reasons:

  • To increase the readability of your code.
  • To improve the maintainability of your code since all three major parts of a loop i.e. initialization, increment / decrement and test condition are written at the same line(in most cases).
  • It limits the scope of counter variables better than a while loop, hence it helps in better memory management.

 

Related posts:

About author

This article was written by admin

Admin has over twenty years experience in the electronics industry, largely dedicated to embedded software. A frequent presenter at conferences and seminars and author of numerous technical articles. Working presently as Development Manager in India. A firm Believer in Knowledge grows when it shared.

Comments

No Comments

Leave your comment

Your email address will not be published. Required fields are marked *