C programming tutorial
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(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
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.
of i is 1 Hence it will print 2*1 i.e 2.
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