Java fundamental programs to practice: Looping

              A set of statements are executed until a condition is met. This concept is called looping. There are three types of loops used in java.

  • 1.       While loop
  • 2.       Do-while loop
  • 3.       For loop

Java program to illustrate while loop:

              While loop deals with a condition followed by set of statements. The syntax is given below.

While(condition)

{

Statements……..

}

Eg: java program to display the odd numbers upto ‘n’.

 import java.util.Scanner;

public class whileEg

{

 public static void main(String args[])

 {

   Scanner scanner = new Scanner(System.in);

   System.out.print("Enter the number:");

   int n= scanner.nextInt();

   int i=1;

   while(n>0)

   {

    System.out.println(n);

    n=n-1;

   }

  }

}

Compile and execute the program to get the output.   

C:\raji\blog>javac whileEg.java

C:\raji\blog>java whileEg

Enter the number:5

5

4

3

2

1

Next is do while loop.

Java program to illustrate do while loop:

              This program reads a input as n. using do while, it repeatedly prints the number.

Syntax:

Do

{

 Statements….

}while(condition);

Eg:

import java.util.Scanner;

public class dowhileEg

{

 public static void main(String args[])

 {

   Scanner scanner = new Scanner(System.in);

   System.out.print("Enter the number:");

   int n= scanner.nextInt();

   do

   {

    System.out.println(n);

    n=n-1;

   }while(n>0);

  }

}

The output is given below.      

C:\raji\blog>javac dowhileEg.java

C:\raji\blog>java dowhileEg

Enter the number:6

6

5

4

3

2

1

Next program uses for loop.

Java program to illustrate for loop:

              For loop is most usable loop in programming. It includes the below syntax.

Syntax:

For(initialization;Condition;increment)

{

 Statements…..

}

Eg: Java program to display odd numbers

              This program reads n as input. Where n is the number of elements.

It displays the odd numbers in the list.

import java.util.Scanner;

public class forEg

{

 public static void main(String args[])

 {

   Scanner scanner = new Scanner(System.in);

   System.out.print("Enter the number:");

   int n= scanner.nextInt();

   int i=0;

   System.out.println("The odd numbers are:");

   for(i=1;i<=n;i=i+2)

   {

    System.out.println(i);

   }

  }

}

C:\raji\blog>javac forEg.java

C:\raji\blog>java forEg

Enter the number:9

The odd numbers are:

1

3

5

7

9

These are the java programs to illustrate looping.

No comments:

Post a Comment