Hello , am new here and i need some help in finding prime numbers.....I actually wrote this code below and it compiles but it repeats sequence with some numbers or most, plus if you run it you will see that the prime numbers are printed as prime numbers only but repeated ...but if you notice the numbers that are not prime, it actually prints the numbers not to be prime and then prints them to be prime and then again not prime. Again it runs too many times for all the numbers. Can someone please help me see whats wrong with the code....thanks

public class Prime {

	/**
	 * @param args
	 */
	public static void main(String[] args) {

		int i,i2;
		
		for ( i=1;i<=40;i++){
			
				for(i2=1;i2<i;i2++){
			  if(i%i2==0 & i2!=1){
						                            System.out.println(i+"is not prime\n");}
	if(i%i2!=0){
		System.out.println(i+"is a prime number\n");}		
					
				}
				
		}
	

	

	}

}

Make your first for loop like so :

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

Then make your second for loop like so

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

The main problem is that you are printing inside the loop. Print outside.
You overall loop could look like this :

int i = 0, i2 = 0;
	for(i = 2; i <= 40; i++){
   for(i2=2; i2<i; i2++){
      if(i % i2 == 0 && i != 2) break;
   }
  if(i2 == i)print "i" is prime;
  else print "i" is not a prime;

}

See how the print is outside the second loop.