while Loop

A while loop is a control structure that allows you to repeat a task a certain number of times. The smplest of all the looping structures in java is the while statement.The basic format of the while statement is.

Intilization;
while(Boolean_expression)
{
Body of the loop
}

When executing, if the boolean_expression result is true, then the actions inside the loop will be executed. This will continue as long as the expression result is true.

Example:

class while
{
public static void main(String args[])
{
int x =10;
while(x< =20)
{
sum = sum x*x;
x=x+1;
}
System.out.print(10+"x”+= "+10* x );
x++;
}
}
}

do...

Syntax:

The body of the loop may not be executed at all if the condition is not statisfied at the very first attempt. On some occasions it might be neccessary to execute the body loop before the test is performed.such situvations can be handeled with the help of the do statement.

do
{
body of the loop
}
while(test condition)

The loop will be executed as long as one of the two relations is true.Program illustrate the use of do..while loops for printing a multiplication table.

Example:

class dowhile
{
public static void main(String args[])
{
int row,coloum,y;
System.out.print("multiplication table/n");
row=1;
coloum=1;
do
{
y=row*colum;
System.out.println(""+y);
colum=colum+1;
}
while(colum<=3);
System.out.println("\n");
row=row+1;
}
while(row<=3);
}
}

for Loop

The for loop is another entry-controlled loop that provides a more concie loop control struture. The general form of the for loop is.

Syntax:

The syntax of a for loop is:
for(initialization;test condition;increment)
{
body of the loop
}

The Boolean expression is now evaluated again. If it is true, the loop executes and the process repeats itself (body of loop, then update step,then Boolean expression). After the Boolean expression is false, the for loop terminates.

Example:

class forTest
{
public static void main(String args[])
{
long p;
int n;
double q;
System.out.println("2 to power -n  n  2 to power n");
p=1;
for(int n =0; n <10; ++n)
{
if (n==0)
p=1;
else
p=p*2;
q=1.0/(double)p;
System.out.print("" +q+ "" +n+ "" +p );
}
}
}

News Walls


Copyrights © 2016. All Rights Reserved to Learn Computers Home, India. //Site Designed.