KnowledgeBoat Logo

Computer Applications

Write a program in java by using for loop to print all the prime numbers from 1 to 50.

Java

Java Nested for Loops

2 Likes

Answer

public class KboatPrime
{
    public static void main(String args[]) {
        System.out.println("Prime Numbers from 1 to 50:");
        
        for (int i = 1; i <= 50; i++) {
            
            int c = 0;
            
            for (int j = 1; j <= i; j++) {
                if (i % j == 0) {
                    c++;
                }
            }
            
            if (c == 2) {
                System.out.println(i);
            }
        }
    }
}

Output

BlueJ output of Write a program in java by using for loop to print all the prime numbers from 1 to 50

Answered By

2 Likes