Showing posts with label WHILE loop. Show all posts
Showing posts with label WHILE loop. Show all posts

Tuesday, May 5, 2015

JAVA program to print all prime numbers between two user given numbers

JAVA program to print all prime numbers between two user given numbers.

import java.io.*;
public class MyMain {
public static void main(String[] args) {
// TODO Auto-generated method stub
InputStreamReader istream = new InputStreamReader(System.in) ;
        BufferedReader read = new BufferedReader(istream) ;
        System.out.print("Enter the first number: ");
        int num1=0, num2=0;
        try{
            num1=Integer.parseInt(read.readLine() );
            System.out.print("Enter the second number: ");
            num2=Integer.parseInt(read.readLine() );
            if(num1>=num2){ //Checking for valid range
            System.out.println("The first number should must be less than the second number.");
            }
            else{
            for(int i=num1;i<=num2;i++){
            int count = 0; //Setting a counter
            for(int j=1;j<=i;j++){
            if(i%j==0) count++;
            }
            if(count == 2)
            System.out.println(i+ " is a prime number.");
            else
            System.out.println(i+ " is a non-prime number.");
            }
            }
           
        } catch(Exception Number){
            System.out.println("Invalid Number!");
        }
           
}
}

Output: 

Enter the first number: 12
Enter the second number: 23
12 is a non-prime number.
13 is a prime number.
14 is a non-prime number.
15 is a non-prime number.
16 is a non-prime number.
17 is a prime number.
18 is a non-prime number.
19 is a prime number.
20 is a non-prime number.
21 is a non-prime number.
22 is a non-prime number.
23 is a prime number.

Monday, April 27, 2015

Java WHILE loop


Flow of control in a WHILE loop:

  1. When executing, if the boolean_expression in while result is true, then the actions inside the loop will be executed. This will continue as long as the expression result is true.
  2. Here, key point of the while loop is that the loop might not ever run. When the expression is tested and the result is false, the loop body will be skipped and the first statement after the while loop will be executed.

Example

public class HelloWorld{

     public static void main(String []args){
        int i = 5;
        int k = 0;
        while(k<=i){
            System.out.println(k+"\n");
            k++;
        }
     }
}