There are mainly 4 type of loops in Java.
2. do while loop:
package com.java.basics;
public class Loops {
public static void main(String[] args) {
System.out.println("While Loop:");
int num1 = 10, num2 = 20;
while (num1 != num2) {
System.out.print(num1 + " ");
num1++;
}
System.out.println("\nDo while Loop:");
int a = 99, b = 100;
do {
System.out.print(a);
a++;
} while (a < b);
System.out.println("\nFor Loop:");
for(int i = 1; i < 10; i++){
System.out.print(i + " ");
}
}
}
Exercise:
- while loop
- do while loop
- for loop
- for each loop
- while loop:
Syntax:
while(condition) {
/*If condition is true loop statements will execute else execution will come out of the while loop*/
loop statements
2. do while loop:
Syntax:
do {
/*If condition is true loop statements will execute else execution will come out of the while loop Loop will execute at-least one time*/
do {
/*If condition is true loop statements will execute else execution will come out of the while loop Loop will execute at-least one time*/
} while(condition);
3. for loop:
Syntax:
for(initialization ; condition ; increment / decrements) {
/*If condition is true loop statements will execute else execution will come out of the while loop*/
for(initialization ; condition ; increment / decrements) {
/*If condition is true loop statements will execute else execution will come out of the while loop*/
}
package com.java.basics;
public class Loops {
public static void main(String[] args) {
System.out.println("While Loop:");
int num1 = 10, num2 = 20;
while (num1 != num2) {
System.out.print(num1 + " ");
num1++;
}
System.out.println("\nDo while Loop:");
int a = 99, b = 100;
do {
System.out.print(a);
a++;
} while (a < b);
System.out.println("\nFor Loop:");
for(int i = 1; i < 10; i++){
System.out.print(i + " ");
}
}
}
Exercise:
- Write a program to find factorial of a number?
- Write a program to check a number is prime?
- Write a program to print Fibonacci series?
- Write a program to print 500 to 600 using loop?
- Write a program to check a number is power of 2 using loops?
- Write a program to find HCF or GCF of two numbers?
- Write a program to print only odd numbers from 1000 to 2000?
No comments:
Post a Comment