LOOP IN JAVA
LOOP:
- It is used to execute a set of statement multiple times.
- In loop there are three major factors.
- Initialization: It is also known as starting point or initial point.
- Condition: It is also known as stopping point or ending point.
- Updation: It is the count of number of iteration.
While loop
Syntax
Initialization
while (condition)
{
(Statement to execute)
Updation
}
Write a Java program to display 1 to 5 by using while loop
- class WhileLoop
- {
- public static void main(String [] args)
- {
- int a= 1;
- while (a < = 5)
- {
- System.out.println(a);
- ++a;
- }
- }
- }
Output:
1
2
3
3
4
5
5
Write a Java program to display number from 10 to 1
- class WhileLoop
- {
- public static void main(String [] args)
- {
- int a= 10;
- while (a >= 1)
- {
- System.out.println(a);
- --a;
- }
- }
- }
Output:
10
9
8
8
7
6
6
5
4
4
3
2
2
1
Write a Java program to display the even numbers between the range of of 2 to 16 using while looop
- class WhileLoop
- {
- public static void main(String [] args)
- {
- int a= 2;
- while (a <= 16 && a%2==0)
- {
- System.out.println(a);
- ++a;
- ++a;
- }
- }
- }
Output:
2
4
6
6
8
10
10
12
14
14
16
do while loop
Syntax
Initialization
do
{
(Statement to execute)
Updation
}
while (condition)
Write a Java program to display 1 to 3 by using do while loop
- class DowhileLoop
- {
- public static void main(String [] args)
- {
- int a= 1;
- do
- {
- System.out.println(a);
- ++a;
- }
- while(a<=3);
- }
- }
Output:
1
2
3
3
Write a Java program to display number from 5 to 1 by using do while loop
- class DowhileLoop
- {
- public static void main(String [] args)
- {
- int a= 5;
- do
- {
- System.out.println(a);
- --a;
- }
- while(a>=1);
- }
- }
Output:
5
4
3
3
2
1
for loop:
Write a Java program to display 1 to 5 today using for loop
- class Forloop
- {
- public static void main(String [] args)
- {
- for(int a= 1; a<=5; a++)
- {
- System.out.println(a);
- }
- }
- }
Output:
1
2
3
3
4
5
Write a Java program to display even numbers by using for loop from 2 to 14
- class Forloop
- {
- public static void main(String [] args)
- {
- for(int a= 2; a<=14; ++a)
- {
- if(a%2==0)
- {
- System.out.println(a);
- }
- }
- }
- }
Output:
2
4
6
6
8
10
10
12
14
14
Write a Java program to display the numbers which are divisible by 3 from the range 2 to 14 by using for loop
- class Forloop
- {
- public static void main(String [] args)
- {
- for(int a= 2; a<=14; ++a)
- {
- if(a%3==0)
- {
- System.out.println(a);
- }
- }
- }
- }
Output:
3
6
9
9
12
0 Comments