google Ads

Monday, July 13, 2009

For Loop

For Loop
The “For Loop” is another repetitive control structure, and is used to execute set of instruction repeatedly until the condition become false.
The assignment, increment and decrement and condition checking is done in “For” statement only, where as other control structures are not offered all this features in one statements in one statements only.

Syntax:

for(initial value; condition; increment/ decrement )
{
body of the loop
}

The for loop has three parts
1. Initialize counter is used to initialize counter variable.
2. Test condition is used to test the condition
3. Increment / Decrement counter is used to increment or decrement counter variable

If there is a single statement within the for-loop, the blocking with braces is not necessary, if more than one statement in body of the loop, the statements within the body must be blocked with braces.

Example: 1

public class forLoopDemo
{
public static void main(String args[])
{
int i;
for(i=0;i<6;i++)
{
System.out.println(“Now the I value is : “+i);

}
System.out.println(“The out of the loop! “);
}
}


The output will be:

Now the I value is :0
Now the I value is :1
Now the I value is :2
Now the I value is :3
Now the I value is :4
Now the I value is :5

The out of the loop!

Example 2: for Nested for loop

public class binaryTriangle
{
public static void main(String arg[])
{
String k="1", l="", s="";
int m=0;
int n=6;
for(int i=0;i< n;i++)
{
for(int j=1;j {
l=l+"0";
}

System.out.println(k+l+s+"\n");
s="1";
l="";
m=m+2;
}
}
}


The output will be:

1

101

10001

1000001

100000001

10000000001

No comments:

Post a Comment