Java (OOPS) Lab Archive

Programming Exercises - August 4, 2026

Experiment 1 : Write a Java program to print the following pattern : 1! + 2! + 3! + … + n

Code

public class FactorialSum {
    public static void main(String args[]) {
        int n = 5;
        int i, fact = 1, sum = 0;

        for (i = 1; i <= n; i++) {
            fact *= i;
            sum += fact;
        }

        System.out.println("The Sum Of Factorials From 1 To " + n + " Is: " + sum);
    }
}

Output

The Sum Of Factorials From 1 To 5 Is: 153

Experiment 2 : Write a Java program to print Hello World

Code

class HelloWorld {
    public static void main(String args[]) {
        System.out.print("Hello World!");
    }
}

Output

Hello World!

Exercise 3: Pattern One

Question: Write a Java program to print the following pattern

* * * *
  * * *
    * *
      *

Code

public class PatternOne {
    public static void main(String args[]) {

        int n = 4;
        int i, j;

        for (i = 0; i < n; i++) {
            for (j = 0; j < i; j++) {
                System.out.print("  ");
            }

            for (j = 0; j < n - i; j++) {
                System.out.print("* ");
            }

            System.out.println();
        }

    }
}

Output

* * * * 
  * * * 
    * * 
      *

Experiment 4 : Write a Java program to print the following pattern.

1
1 2
1 2 3
1 2 3 4

Code

public class PatternTwo {
    public static void main(String args[]) {
        int n = 4;
        int i, j;

        for (i = 1; i <= n; i++) {
            for (j = 1; j <= i; j++) {
                System.out.print(j + " ");
            }

            System.out.println();
        }
    }
}

Output

1 
1 2 
1 2 3 
1 2 3 4

Experiment 5: Write a Java program to determine whether a number is prime

Code

public class PrimeNumber {
    public static void main(String args[]) {
        int n = 511111;
        int i, count = 0;

        for (i = 2; i <= Math.sqrt(n); i++) {
            if (n % i == 0) {
                count++;
                break;
            }
        }

        if (count == 0 && n > 1) {
            System.out.println(n + " Is A Prime Number.");
        } else {
            System.out.println(n + " Is Not A Prime Number.");
        }
    }
}

Output

511111 Is A Prime Number.

Files in this folder

Attachments that ship next to this document.