Social Icons

Monday, December 24, 2012

For loop in C

for loop is also a kind of loop and used to execute a block of code for a specified number of times. It is the most widely used loop.


Syntax of 'for' loop


           for(initialization counter;loop condition;increment counter)
           {
                --------------------------------
                Some code to execute
                --------------------------------
           }


 Explanation of the syntax:


 There are 3 parts in the for loop written in a single line itself. They are:
  •  initialization counter - It is used to initialize the counter before execution of the loop starts.
  • loop condition - As the loop condition will be true, the execution of the loop will be continued. Its execution will be stopped when the loop condition is false.
  • increment counter - It is used to increase or decrease the value of counter each time after the end of each loop iteration. In other words, it will increase(or decrease) every time after the f block of code inside for loop will execute once.


 Now, lets see an example of for loop with a program.


 WAP to print numbers between 1 to 100 using for loop.


      #include<stdio.h>
      void main()
      {
           int i=1;
           for(i=1;i<100;i++)
           {
                 printf("%d\t",i);
           }
       }


   Explanation for the program:


           Here, we have initialized a variable i and set its value equal to 1. Now, it will come in for loop statement. Firstly, the initialization counter is there i.e, i=1. Then, it will check for the loop condition as i<100 i.e, currently 1<100 which is true. Then, it will execute the block of code written inside for loop i.e, printf statement. Now, it will print the value of i. Then, it will go to for loop statement again and will increase the value of i by 1 as i++ is there. So, now i=2. Again, it will check 2<=100 i.e, true. And value of i will be printed. Similarly, it will print from 1 to 100. \t is provided in the print statement as provide a tab space between each number.

No comments:

Post a Comment

Total Pageviews