“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();
}
/* 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();
}
No comments:
Post a Comment