C programming tutorial

                 

PREVIOUS                                                                                   NEXT CHAPTER


In c programming it is sometime needed to perform a set of instruction repeatedly.Suppose we need to print a line 10 times.In this case instead of using printf 10 times it would be better to run a loop with single printf statement inside it.Repeating can be done either a specified number of times or till a partcular condition is met.loops are there to perform such kind of tasks.There are three types of loops in C namely for loop ,while loop,do while loop.


For loop

syntax of for loop

for(initilize counter;loop condition;increment/decrement counter)

{

//statements

}

initilization of counter is done before execution of loop.It is used to set loop counter to an initial value.counter is a variable which is used to control number of iteration in loop.

 

loop continues to run until loop condition evaluates to be false.Condition is checked at the beginning of each iteration.If condition evaluates true loop will continue otherwise it will be terminated.

 

counter is iincremented after the end of every iteraion.

 

 

In short initially counter is assigned a value,then loop condition is checked.If it comes to be true statements inside C for loop executes ,after executing all instructions inside loop counter is incremented or decremented.Then again condition is checked if its come to be true all the statements inside ther loop are executed ,then again counter is incremented,then again condition is checked......

This loop continues to run until the condition of loop evaluates to be false.Concept of for loop would become crystal clear after reading the following example

 

For loop example

Suppose we have to make a program that print table of two . There are two methods to do it.First we can use ten printf statements to print table.It would be very cumbersome Other method is using C for loop.We would just use one printf statement in this method.

void main( )
{
for(int i=1;i<=10:i=i+1)
printf("%d\n",2*i);
}
  1. Counter (i) was initialised to 1
  2. Condition is checked.Since value of i is 1 i.e less then 10. printf inside loop will run.It will print 2*i.Value

    of i is 1 Hence it will print 2*1 i.e 2.

  3. Then counter (i ) incremented by 1.Hence i becomes 2 now.Then condition is checked .Yes i is less then 10 printf will run.Its output will be 2*2 i.e 4

  4. counter(i) is incremented,Its value becomes 3 now..It will check condition.Yes 3 is less then 10. loop will run it will print 2*3 i.e 6.

 

and so on.... loop will run until condition evaluates to be false .Here loop will stop when i will become 11.

 

Following is the output of our program

2

4

6

8

10

12

14

16

18

20

I hope now concept of c for loop would be clear to you.


                  PREVIOUS                                                                                   NEXT CHAPTER