0
Sponsored Links


Ad by Google
Java programming interview question, specially for freshers, to check the candidates logical analysis and basic knowledge of coding. Some of the popular coding interview questions like how to balanced parentheses and finding second largest numbers from an array. In this post, I'm going to show you a simple Java code to print prime numbers.

What is Prime number?
A prime number is a natural number greater than 1, that has no any positive divisors other than 1 and itself. For example 2,3,5,7,11,13,17,19,23,29,31....

package com.javamakeuse.poc;

public class PrimeNumbers {
 // printing prime numbers till given number
 public static void printPrimeNumbers(int number) {
  int count;

  for (int i = 1; i <= number; i++) {
   count = 0;
   for (int j = 2; j <= i / 2; j++) {
    if (i % j == 0) {
     count++;
     break;
    }
   }

   if (count == 0) {
    System.out.println(i + " is a Prime number");
   }
  }

 }

 public static void main(String[] args) {
  printPrimeNumbers(50);
 }
}

Output:
1 is a Prime number
2 is a Prime number
3 is a Prime number
5 is a Prime number
7 is a Prime number
11 is a Prime number
13 is a Prime number
17 is a Prime number
19 is a Prime number
23 is a Prime number
29 is a Prime number
31 is a Prime number
37 is a Prime number
41 is a Prime number
43 is a Prime number
47 is a Prime number

Sponsored Links

0 comments:

Post a Comment