Tuesday, April 5, 2016

Example of While loop & Nesting of loops

Nesting of loops:
Nesting of loops mean using loop inside a loop.It could be "For" loop inside a "For" loop or a "For" loop inside a "While" loop or the other way round. 

Our Objective ?
Our objective is to write a JAVA program which keeps on taking values from user unless user give a prime number as input value.
We can easily solve this problem using nested loops.
We will use a "While" loop because we don't know when user will give a prime number as input value.



But to check for prime number we will use "For" loop , because we will end it on the half of the value given by user .
So its code will be like this:
Here we used "factors" variables which will store factors of the value given by user, and if factors are one or more than one then it will not be a prime number.
So, we used " if(factors==0) " condition to end the loop.If the value given by the user have no factors other than 1 and its ownself , then it will be a prime number. So if we break the loop here then our task will be completed.

The code will be like this :

package labwork;
import java.util.*;
public class A2
{
    public static void main(String[] args)
    {
        Scanner input=new Scanner(System.in);
        int a;
        int factors;
        while(true)
        {
            factors=0;
            System.out.print("Enter an integer value: ");
            a=input.nextInt();
            for(int i=2;i<=a/2;i++)
            {
              
                if(a%i==0)
                {
                    factors++;
                  
                }
                  
            }
            if(factors==0)
             break;
          
        }
      
    }
  
}

If you have any problem then you can comment down here or you can send us an email.Our email address is : K.ahmed2k19@gmail.com

You can contact us on facebook : https://www.facebook.com/Tuts.by.khalil/
If you like it then please share our website with your friends .
Keep visiting and keep learning.

0 comments:

Post a Comment