Pages

January 29, 2013

Loop Control- for loop in C++ (OOPs)



loop control statement banner of for loop in C++ (OOPs)

“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 factorial of number using for loop*/


#include<iostream.h>
#include<conio.h>
main()
{
      int n,i,fact=1;
      cout<<"\n Enter any number whose factorial is to be find";
      cin>>n;
      for(i=n;i>0;i--)
      {
                      fact=fact*i;
                      }
      cout<<"\n Factorial of "<<n<<" is "<<fact;
      getch();
      }
output of program to show factorial of a number using for loop in C++ (OOPs)

/* Program to enter limit and print the fibonacci series */

#include<iostream.h>
#include<conio.h>
main()
{
      int a=0,b=1,c,n,i;
      cout<<"\n Enter the limit of the Fabonic series";
      cin>>n;
      cout<<"\n "<<a<<","<<b<<",";
      for(i=3;i<=n;i++)
      {
                       c=a+b;
                       a=b;
                       b=c;
                       cout<<c<<",";
                       }
      getch();
      }
output of program to print fibonacci series upto limit using for loop in C++ (OOPs)
 

/* Program to enter limit and find its sum and average */

#include<iostream.h>
#include<conio.h>
main()
{
      int n,i,sum=0;
      float av;
      cout<<"\n Enter the limit of the sum series";
      cin>>n;
      for(i=1;i<=n;i++)
      {
                       sum=sum+i;
                       }
      av=sum/float(n);
      cout<<"\n Sum of the series with limit "<<n<<" is "<<sum;
      cout<<"\n Average is "<<av;
      getch();
      }
output of program to enter limit and find sum and average of a number using for loop in C++ (OOPs)

No comments:

Post a Comment