for Loop

for Loop
This loop is more compact syntactically. It executes a group of statement as a condition is true.

Syntax
for(initialization;condition;incr/decr)
{
//statements;
}

Programs:

Print all number from 1 to 5 using for loop
class test
{
public static void main(String[] args)
{
for(int i=1;i<=5;i++)
{
System.out.println(i);
}
}
}

Output:
1
2
3
4
5

Write a fibonacci series program
class test
{
public static void main(String args[])
{
int n1=0,n2=1,n3,i,count=10;
System.out.print(n1+” “+n2);
for(i=2;i<count;++i)
{
n3=n1+n2;
System.out.print(” “+n3); n1=n2; n2=n3;
}
}
}

Output:
0 1 1 2 3 5 8 13 21 34

Check whether the number is prime or not
class test
{
public static void main(String args[])
{
int i,m=0,flag=0;
int n=119;
m=n/2;
for(i=2;i<=m;i++)
{
if(n%i==0)
{
System.out.println(“Number is not prime”);
flag=1;
break;
}
}
if(flag==0)
System.out.println(“Number is prime”);
}
}

Output:
Number is prime

Find the factorial of given number
class test
{
public static void main(String args[])
{
int i,fact=1;
int number=5;
for(i=1;i<=number;i++)
{
fact=fact*i;
}
System.out.println(“Factorial of “+number+” is: “+fact);
}
}

Output:
Factorial of 5 is: 120

Leave a Reply

Your email address will not be published. Required fields are marked *