Loops in Java

Posted on

Loops: A loop can be defined as a repeated execution of statements or a block of statements a specified no. of times Java provides thread looping structures namely

  • while
  • do…while
  • for
  1. while: Syntax: –
    while(condition)
    {

    statements;
    }

 

/*A small demo on while control loop*/

class App7{

public static void main(String yck[])
{

int x;
x=1;
while(x<=10)
{

System.out.println(x);
x++;
}
}

}

 

output:
\>javac App7.java
\>java App7
1
2
3
4
5
6
7
8
9
10

do…while:Syntax: –

do
{

statements;
}while(condition);

 

/*A small demo on do…while control loop*/

class App8{

public static void main(String yck[])
{

int x;
x=10;
do
{

System.out.println(x);
x–;
}while(x>=1);
}
}

 

output:
\>javac App8.java
\>java App8
10
9
8
7
6
5
4
3
2
1

for:Syntax: –

for(initialization; condition; increment/decrement)
{

statements;
}

 

/*A small demo on for loop control*/

class App9{

public static void main(String yck[])
{

int x;
for(x=1;x<=10;x++)
System.out.println(x);
}

}

 

output:
\>javac App9.java
\>java App9
1
2
3
4
5
6
7
8
9
10

Leave a Reply

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