Nested loop in java - java nested loop with examples

Nested loop in java - java nested loop with examples

 

Nested loop in java

Nested loop in java

A nested loop is a loop within another loop. We can nested for loops is a loop within another for loop or vice versa.

Nested for loop

Syntax for Nested For loop:

// this is outer loop

for ( initial-value; test-condition; increment / decrement )  

{

   // this is the inner loop

   for ( initial-value; test-condition; increment / decrement )

{     

      // statement within the inside loop

   }

} //statement of outer loop or end of scope of outer loop

 

Syntax for Nested While loop:

// this is outer loop

while(test-condition)

{

   // this is the inner loop

   while(test-condition)

   {     

      // statement within the inside loop

    }

 

   // statement of outer loop or end of scope of outer loop

}

 

Syntax for Nested Do-While loop:

// this is outer loop

do{

   // this is the inner loop

   do{

     

      // statement within the inside loop

   }while(test-condition);

 

   // statement of outer loop or end of scope of outer loop

}while(test-condition);

 

The execution of statement of nested loop will perform its task from inner most loop to outer most loop. In nested loop, the loop inside a loop will finished first then the outer most loop.

Nested For loop in java 

Example of nested for loop in java

public class NestedForLoop1

{

    public static void main(String args[])

    {

        int i, j;

        for(i=1;i<=3;i++)

        {

            System.out.println("Outer Loop: "+ i);

            for(j=1;j<=2;j++)

            {

                System.out.print(" Inner Loop :"+ j);

            }

            System.out.println();

        }

    }

}

Sample output

Outer Loop:1

 Inner Loop:1 Inner Loop:2

Outer Loop:2

 Inner Loop:1 Inner Loop:2

Outer Loop:3

 Inner Loop:1 Inner Loop:2

Here outer most loop will execute three times and inner loop will execute six times as it run three times from outer most loop.

 

Print prime number between 1 to 100

public class PrintPrimeOneTo100

{

    public static void main(String atgs[])

    {

        int j, f=1,i;

        for (i=2; i<=100; i++)

        {

            f=1;

            for (j=2; j<i; j++)

            {

                if(i % j==0)

                // if number is divided other then 1 and by itself the flag variable become f=0        

                {

                    f=0;

                    break;

                }

            }

            // print prime number if flag variable is f=1

            If (f==1)

            {

                System.out.print (I + " ");

            }

        }

    }

}

In the above program all the prime number will print between 1 to 100. And this is done with the help of nested for loop. Here in each iteration value I of first loop will check for prime number and if it so it will print the prime number.

 

Print the series s = 1! + 2! + 3! + 4! + 5!

public class FactorialofSum

{

    public static void main(String args[])

    {

        int i, j, f, s=0;

        for (i=1; i<=5; i++)

        {

            f=1;

            // factorial of ith digit

            for(j=1; j<=i; j++)

            {

                f=f*j;

            }

            // print the factorial f

            System.out.println ("Factorial="+f);

            // summation of factorial

            s=s + f;

        }

        System.out.println ("Sum="+s);

    }

}

Sample output

Factorial= 1

Factorial= 2

Factorial= 6

Factorial= 24

Factorial= 120

Sum = 153

 

Star pattern with nested for loop

*

* *

* * *

* * * *

* * * * *

public class StarPattern

{

    public static void main(String args[])

    {

        int i, j;

        for  (i=1 ;i<=5; i++)

        {

            For (j=1; j<=i; j++)

            {

                System.out.print ("* ");

            }

            System.out.println (); // dummy println

        }

    }

}

Nested while loop in java

Nested while is a loop within another while loop. The inside loop will end first the outside loop or we can say the function of the inner loop continues till the condition of the inner loop is satisfied or become false.

Syntax

 

while(test-expression)

{

         Statement 1;

         Statement 2;

         while(test-expression)

        {

           Statement 1;

                        Statement 2;

                        Statement 31;

         }

}

 

Example of the nested while loop in java

class NestedWhileLoop

{

    public static void main(String args[])

    {

        // Local variable initialized i=1, j=1

        int i=1,j=1;

        while(i<=3)

        {

            System.out.println("\n"+i+" "+"outer loop executed\n");

            while(j<=2)

            {

                System.out.println(j+" "+"inner loop executed");

                j++;       

            } // end of inner loop

            i++; // iterate i++

            j=1; // initialize j again with 1

        }// end of outer loop

    }

}

Star pattern in java with nested while loop

public class StarPatternWhileLoop

{

    public static void main(String args[])

    {

        int i=1, j;

        while(i<=5) // outer while loop

        {

            j=1;

           while(j<=i) // inner while loop

           {

                System.out.print("* ");

                j++;  // inner while loop iteration

            }

            System.out.println();

            i++; // outer while loop iteration

        }

    }

}

Sample Output

*

* *

* * *

* * * *

* * * * *

Nested do while loop in java

 The nested do while loop is a loop which exist inside to another loop. Working is same as the while loop except it is exit control.

Syntax

 

Statements 1;

Statements 2;

do {

Statements 1;

Statements 2;

Statements 3;

Do {

Statements 1;

Statements 2;

Statements 3;

} while(test-condition);

} while (test-condition);

 

Example of nested do while loop

 

class NestedDoWhileLoop

{

    public static void main(String args[])

    {

        // Local variable initialized i=1, j=1

        int i=1,j=1;

        do{

            System.out.println("\n"+i+" "+"outer loop executed\n");

            do{

                System.out.println(j+" "+"inner loop executed");

                j++;       

            }while(j<=2); // end of inner loop

            i++; // iterate i++

            j=1; // initialize j again with 1

        } while(i<=3);// end of outer loop

    }

}

 

Star pattern in java with do while loop

 

public class StarPatternDoWhileLoop

{

    public static void main(String args[])

    {

        int i=1, j;

        do// outer while loop

        {

            j=1;

           do // inner while loop

           {

                System.out.print ("* ");

                j++;  // inner while loop iteration

            } while (j<=i);

            System.out.println ();

            i++; // outer while loop iteration

        } while (i<=5);

    }

}

 More tutorial and examples of java

Loops in Java - Java loop explained with examples



Java program for Pronic Number


Loops in java - Java loop explained with examples

Loops in java - Java loop explained with examples

 

loops in java

Loops in Java

When we execute one or more sets of instructions or statements repetitively of any programming language with the given condition is known as Loop. Or execute one or more sets of instructions with a condition is called Loop. It is also called repetition structure and this structure allows an action is to be repeated until a given condition is true.

Any loop contains three parts

  • First, it has a starting point or initialization
  • Second, it has a condition
  • Third, it has iteration or step

Types of Loop in java

Depending on control

The entry-controlled loop: The loop that checks it’s a condition at the entry point of the loop. For and while() loop are examples of an entry-controlled loop.

The exit control loop: The loop that checks its condition at an exit point or at the end of from loop is known as an exit controlled loop. Do..while() is the example of an exit control loop.

Depending on execution

Definite loop: This kind of loop performs a fixed number of repetitions. For() loop is the example of a definite loop.

Indefinite loop: This kind of loop perform execution indefinite number of times while() and do..while() are the example of indefinite loop.

Java for loop

Java for will executes its operation a fixed number of times or we can say for loop is a repetition control structure that lets you to efficiently execute a specific number of times.

A for loop is useful when you know how many times a task is to be repeated.

All the parts of for loop are optional. Anyone can be left empty, but the two semi-colon must be included.

For Loop syntax

for ( initialization ; test condition ; increment / decrement ) {

// statements

}

In for loop, we can give curly brace if multiple of statements are there but if single statement curly brace is optional.

for(i=1; i<=5; i++)

 Statement;

 

for(i=1; i<=5; i++)

{

 Statement 1;

Statement 2;

Statement 3;

…….

}

The initialization part is used to declare and initialize variables that will be used by the loop. For example, we can write the initialization part as
int i = 1
The condition is the loop condition similar to the one in while and do-while loops. The increment/decrement part is commonly used to include statements like i++, i– etc.

Algorithm:

The for loop is executed in the following way: 
Step 1. Firstly the statements in initialization is executed.
Step 2. The loop condition is evaluated. If it is true, go to step 3 else move out of the loop.
Step 3. Execute the statement in the loop body.
Step 4. Execute the increment /decrement part.
Step 5. Go to step 2.

We can take the following example

fact=1;

for(i=1; i<=5; i++)

{

  fact = fact * I;

}

Statement 1 i =1 is executed before the execution of the code block and the initialization will not again.

Statement 2 i<=5 will defines the condition for executing the next code block and if it is true then body part of the loop will execute.

Statement 3 i++ is executed after the code block has been executed and it will execute till the condition satisfied. In this it will execute 5 times and the body part of loop will produce 120 after repetition of times as follows

fact = 1 * 1;

fact = 1 * 2;

fact = 2 * 3;

fact = 6 * 4;

fact = 24 * 5;

the final value will be 120.

For loop has some unusual construct.

First type

int i=0;

for( ; i<5; i++)

{

   expression 1;

   expression 2;

   expression 3;

   …………………. ;

}

Here the initialization done outside loop.

Second type

int i=0;

for( ; i<5; )

{

   expression 1;

   expression 2;

   expression 3;

   …………………. ;

   i++;

}

Here the initialization done outside loop and iteration i++ will done within the block.

Third type

int i, s;

 

for(i=1, s=0 ; i<=5; i++)

{

   expression 1;

   expression 2;

   expression 3;

   …………………. ;

}

Here the initialization done within the for loop and also one extra variable initialize with 0 within the for loop.

So for loop can be deferent variant as long as it satisfies three components of a loop.

Few examples of the for loop in java.

Perfect number in Java

A number can be a Perfect Number if the sum of its positive divisors except the number itself is equal to that number. For example, 6 is a perfect number because 6 is divisible by 1, 2, 3 the sum of these values is 1 + 2 + 3 = 6.

public class PerfectNumber

{

    public static void main(String args[])

    {

        int i, num=6, sum=0;

        for(i=1; i<num; i++)

        {

            if(num % i ==0)

            {

                sum = sum + i;

            }

        }

        if(num==sum)

        {

            System.out.println("Perfect Number");

        }

        else

        {

            System.out.println("Perfect Number");

        }

    }

}

Prime number in java

Any number which is divisible 1 and by itself is called prime number.  For example 2, 3, 5, 7, 11, 19, 23, 29.... are the prime numbers.

public class PrimeNumberFirstMetod

{

    public static void main(String args[])

    {

        int i, n=5, f=1;

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

        {

            if(n %i == 0)

            {

                f=0;

                break;

            }

        }

        if(f==1)

        {

            System.out.println("Prime Number");

        }

        else

        {

            System.out.println("Not a Prime Number");

        }

    }

}

Amicable number in Java

Amicable numbers are those two numbers are the the sum of the proper divisors of each is equal to the other number. For example amicable pairs is: (220, 284)

public class AmicableNumber

{

    public static void main(String args[])

    {

        int s1,s2,i;

        int n1=220, n2=284; // pair of two number

        s1=s2=0;

        // First number sum

        for(i=1;i<n1;i++)

        {

            if(n1%i==0)

                s1=s1+i;

        }

        // Second number sum

        for(i=1;i<n2;i++)

        {

            if(n2%i==0)

                s2=s2+i;

        }

        // checking of first number sum to the second number and vice versa 

        // second to first

        if(s1==n2 && s2==n1)

        {

            System.out.println("Amicable Number");

        }

        else

        {

            System.out.println("Not amicable Number");

        }

    }

}

While Loop

The second type of loop is ‘while loop’. It is used we do not know how many times the loop will execute. This is an entry-controlled loop. In a while loop, if the initial condition is true then the execution will enter into the loop.

The syntax for the while loop

While(condition)

{

  statement 1;

  statement 2;

  statement 3;

  ---------------;

  ---------------;

}

The parentheses at the condition is same as the if condition and it will execute as long as the condition is true. The body of the loop will execute until the condition become false.

The while loop will execute the following expression perfectly

While(i = i+1)

While(i++)

While(i+=1)

All the above expression will evaluate to 0 then the loop will fail and exit.

Why do we use while 1or 0?

The while loop with 1 or 0, while (1) or while (any non-zero value) is used for infinite loop or unending of the loop. 1 or any non-zero value is present, then the condition is always true. So the loop will execute forever and to come out from this unending loop, we must use conditional statements and break statements.

Example of while loop in java

Print series in while loop in java 1 2 3 4……….

class WhileLoopExample1

{

    public static void main(String args[])

    {

        int i=10;

        while(i!=0) // entry control loop

        {

            System.out.print(i + " "); // print 1 2 3 4 5 6 7 8 9 10

            i--;

        }

    }

}

Reverse number in java

class Reverse

{

    public static void main()

    {

        int n=154,a, rev=0, m=n;;

        while(n!=0) // entry control loop

        {

            a=n % 10; 

            rev=rev*10 + a;

            n=n/10;

        }

        System.out.println("Reverse " + rev );

    }

}

Palindrome number in java

An integer is said to be a palindrome, if it’s reverse is also the same as the number.

Like 121, 141, 242 etc.

class Palindrome

{

    public static void main(String args[])

    {

        int number=151,a, rev=0, m=number;;

        while(number!=0) // entry control loop

        {

            a=number % 10; 

            rev=rev*10 + a;

            number=number/10;

        }

        if(m == rev)

        {

            System.out.println("Palindrome number");

        }

        else

        {

            System.out.println("Not a Palindrome number");

        }

    }

}

Fibonacci series in java using while loop

import java.util.*;

public class Fibonacci

{

    public static void main(String arg[])

    {

        Scanner sc = new Scanner (System.in);

        int f1, f2, fib, i, number;

        System.out.println ("Enter a number to generate Fibonacci Series:");

        number = sc.nextInt();

        f1 = fib = 0;

        f2 = 1;

        i=0;

        System.out.print (fib+" ");

        while (i < number)

        {

            f1 = f2;

            f2 = fib;

            fib = f1 + f2;

            System.out.print (fib+" ");

            i++;

        }

    }

}

Sample output

Enter a number to generate the Fibonacci Series:

10

0 1 1 2 3 5 8 13 21 34 55

do..while loop in java

this loop is the same as the while loop except it tests the condition at the bottom of the loop. This loop will execute at least once. This an example of an exit-controlled loop.

The syntax for the loop is

do{

 expression 1;

 expression 2;

 expression 3;

 expression 4;

 ----------------;

}while(condition);

Generally we use do while in menu driven program because we enter the menu before any condition

 

Example of do-while loop in java

Calculator program in java using a do-while loop with a switch statement

import java.util.*;

public class MenuCalculator

{

    static void menu() // menu method

    {

        System.out.println ("Press 1 for Addition");

        System.out.println ("Press 2 for Subtraction");

        System.out.println ("Press 3 for Multiplication");

        System.out.println ("Press 4 for Division");

        System.out.println ("Press 5 for Exit\n\n");

        System.out.println ("Enter Your Choice");

    }

    // main method

    public static void main (String args[])

    {

        int num1, num2, result, choice;

        Scanner sc=new Scanner (System.in);

        do{

            menu();  // static method

            choice = sc.nextInt();

            System.out.println ("Enter two Numbers:");

            num1=sc.nextInt ();

            num2=sc.nextInt ();

           switch(choice)

            {

                case 1:

                result=num1+num2;

                System.out.println("Sum=" + result);

                break;

                case 2:

                result=num1-num2;

                System.out.println("Subs=" + result);

                break;

                case 3:

                result=num1*num2;

                System.out.println("Mult=" + result);

                break;

                case 4:

                result=num1/num2;

                System.out.println ("Div=" + result);

                break;

                case 5:

                System.exit (0);

                default:

                System.out.println ("Wrong Choice, please press(1-5)");

            }

        } while(choice!=5); // do while loop condition

    }

}

Java Programs



Java program for Pronic Number