The for loop is also entry-controlled loop.
Syntax:
for(initialization; condition; increment/decrement)
{
Body of loop
}
Initialization: in this part of the loop the variable is initialized such as i=0; and this is the control variable for the loop, which tells from where the loop is starting.
Condition: The condition is a relational expression and the value of the variable is evaluated using some condition. E.g: i<=5;
Increment/decrement: After the execution of the statements which are in the body of the loop the control will again transfer to the loop and then the value of the variable is incremented. This value can be incremented by one or more according to our need.
if we want to increment variable with one then we can use i++;
Program:
/*PROGRAM TO CHECK WHETHER A GIVEN NUMBER IS PRIME OR NOT*/
#include<conio.h>
#include<iostream.h>
class prime_no
{
int n,i,f;
public:
void input();
void output();
};
void prime_no::input()
{
cout<<“Enter any number: “;
cin>>n;
}
void prime_no::output()
{
f=0;
for(i=2;i<=(n/2);i++)
{
if(n%i==0)
f=1;
}
if(f==0)
cout<<n<<” is a prime number”;
else
cout<<n<<” is not a prime number”;
}
void main()
{
prime_no p1;
clrscr();
p1.input();
p1.output();
getch();
}