Write a program to Find prime and non-prime numbers in the array


The code checks whether each element in the given array a is prime or not. It uses a nested loop to iterate over each element and then over all the numbers from 2 to half of the element's value. If any number divides the element, it is not prime, and the loop is terminated by setting the flag variable to 1.

The output displays each element in the array followed by whether it is prime or not. If the flag variable is 0, it means the number is prime, and "Prime" is displayed, and if it is 1, "Not Prime" is displayed.

Note that the code has a small error in the nested loop condition. It should be j <= a[i] / 2 instead of j < a[i] / 2 to include the value of half of the element's value.

Source Code

public class FindNumber_PrimeNot
{
	public static void main(String[] args)
	{
		int i = 0;
		int j = 0;
		int flag = 0;
 
		int a[] = {3, 12, 21, 11, 71, 96, 19, 41, 83, 101};
 
		for (i = 0; i < a.length; i++)
		{
			flag = 0;
			for (j = 2; j < a[i] / 2; j++)
			{
				if (a[i] % j == 0)
				{
					flag = 1;
					break;
				}
			}
			System.out.println(a[i]+" - "+(flag == 0 ? "Prime" : "Not Prime"));
		}
		System.out.println();
	}
}

Output

3 - Prime
12 - Not Prime
21 - Not Prime
11 - Prime
71 - Prime
96 - Not Prime
19 - Prime
41 - Prime
83 - Prime
101 - Prime

Example Programs