The second program I wrote today during the for loop lecture was used to print out a list of prime numbers.

public class Main {
    public static void main(String[] args) {
        int count = 0;
        for(int i=10; i<50; i++){
            if (isPrime(i)){
                count++;
                System.out.println("Number " + i + " is a prime number");
                if(count == 10){
                    System.out.println("Exiting for loop");
                    break;
                }
            }
        }
    }
//Code to check whether n is a prime number, returns true if yes
    public static boolean isPrime (int n){
        if (n == 1) {
            return false;
        }
        for(int i=2; i<= n/2; i++){
            if(n % i == 0) {
                return false;
            }
        }
        return true;
    }
}

At the bottom is a method which returns true if a number is prime. I was given this and don’t entirely understand it yet.

In the above block of code there is an integer variable declared called count and set to 0.

Then there is a for loop where i starts at 10 and counts up by 1 until it gets to 49.

Within the for loop there is an if statement. This if statement refers to the aforementioned method which returns true if the given number i is a prime number. Thus if i is prime it runs what’s in the following brackets.

In the if statement:

  • The number count is added to by 1.
  • It prints a line saying that i is a prime number.
  • Then there is another if statement which breaks out of the for loop if count is equal to 10 and prints a line saying that it’s exiting the for loop.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s