Loops in Java

There are mainly 4 type of loops in Java.
  1. while loop
  2. do while loop
  3. for loop
  4. for each loop

  1. 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*/
     } 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*/
     }




















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:
  1. Write a program to find factorial of a number?
  2. Write a program to check a number is prime?
  3. Write a program to print Fibonacci series?
  4. Write a program to print 500 to 600 using loop?
  5. Write a program to check a number is power of 2 using loops?
  6. Write a program to find HCF or GCF of two numbers?
  7. Write a program to print only odd numbers from 1000 to 2000?

No comments:

Post a Comment