January 21, 2013

Loop Control- for loop


loop control statement banner of for loop

“for” loop is also structure control loop as program will run or execute if the initial condition is true otherwise it will terminate and program will run until some condition is fulfilled.

FORMAT:
for(expression1;expression2;expression3)
{
Statement1;
Statement2;
}


“for” loop is used in those problems where the number of times the body of the loop is to be executed is known in advance.
Here expression1 is used to give initial value to the loop control variable.
Here expression2 represents some test condition which should be true before executing the body of the loop
Here expression3 changes the value of the loop control variable i.e. increment or decrement.


/*Program to find the average of n natural numbers and limit is set by the user*/


#include<stdio.h>
#include<conio.h>
void main()
{
     int i,n,sum=0;
     float av=0;
     printf("\n enter the limit");
     scanf("%d",&n);
     for(i=1;i<=n;i++)
     {
                      sum=sum+i;
                      }
     float n1=n;
     av=sum/n1;
     printf("\n average of %d natural numbers is %f",n,av);
     getch();
     }
output of average of a number using for loop in C language




/*Program to find the factorial of a number*/

#include<stdio.h>
#include<conio.h>
void main()
{
     int n,i, fact=1;
     printf("\n enter any number whose factorial you want to find");
     scanf("%d",&n);
     for(i=n;i>=1;i--)
     {
                      fact=fact*i;
                                  }
     printf("\n factorial of %d is %d",n,fact);
     getch();
     }
output of factorial of a number using for loop in C language


/*Program to enter limit of the Fibonacci series and print the series*/

#include<stdio.h>
#include<conio.h>
void main()
{
     int a=0,b=1,c,n,i;
     printf("\n enter the limit of the fibonacci series");
     scanf("%d",&n);
     printf("%d %d",a,b);
     for(i=0;i<=(n-3);i++)
     {
                          c=a+b;
                          a=b;
                          b=c;
                          printf(" %d",c);
                          }
     getch();
     }
output of fibonacci series using for loop in C language



/*Program to print 10 - 10 numbers in each line of natural number series*/

#include<stdio.h>
#include<conio.h>
void main()
{
     int i;
     for(i=1;i<=100;i++)
     {
                        printf("%d ",i);
                        if(i%10==0)
                        printf("\n");
                        }
     getch();
     } 
output of printing 10-10 natural number up to a certain limit using for loop in C language




PRECAUTIONS

1. Use accurate header files.
2. Don’t use ‘;’ after for loop.
3. Separate expressions of for loop by ‘;’.
4. Always close the brackets if taken.
5. Here values used in for loop aren’t defined in advance i.e. in variable declaration section.

No comments:

Post a Comment