Skip to the content.

Java - Loops Advanced Exercises

Problem 1: Pyramid Pattern

Description: Write a Java program to print a pyramid pattern using nested for loops.

Example:

Input: Take an integer N from the user (e.g., 5)
Output:
    *
   ***
  *****
 *******
*********

Problem 2: Hollow Square Pattern

Description: Write a Java program to print a hollow square pattern using nested for loops.

Example:

Input: Take an integer N from the user (e.g., 5)
Output:
*****
*   *
*   *
*   *
*****

Problem 3: Pascal’s Triangle

Description: Write a Java program to print Pascal’s Triangle up to N rows using nested for loops.

Example:

Input: Take an integer N from the user (e.g., 5)
Output:
    1
   1 1
  1 2 1
 1 3 3 1
1 4 6 4 1

Problem 4: Spiral Matrix

Description: Write a Java program to generate a square matrix in a spiral order using nested loops.

Example:

Input: Take an integer N from the user (e.g., 3)
Output:
1 2 3
8 9 4
7 6 5

Problem 5: Matrix Multiplication

Description: Write a Java program to multiply two N×N matrices using nested loops.

Example:

Input: Two 2×2 matrices:
Matrix A: 1 2
          3 4
Matrix B: 5 6
          7 8
Output:
Result Matrix:
19 22
43 50

Problem 6: Transpose of a Matrix

Description: Write a Java program to compute the transpose of a matrix using loops.

Example:

Input: 2×3 Matrix:
1 2 3
4 5 6
Output:
Transpose:
1 4
2 5
3 6

Problem 7: Diamond Pattern

Description: Write a Java program to print a diamond pattern using nested loops.

Example:

Input: Take an integer N from the user (e.g., 5)
Output:
    *
   ***
  *****
   ***
    *

Problem 8: Rotate Matrix 90 Degrees

Description: Write a Java program to rotate a square matrix 90 degrees clockwise.

Example:

Input: 2×2 Matrix:
1 2
3 4
Output:
Rotated Matrix:
3 1
4 2

Problem 9: Count Frequency of Elements in 2D Array

Description: Write a Java program to count the frequency of each element in a given 2D array.

Example:

Input: 2×3 Matrix:
1 2 2
3 1 3
Output:
Frequency:
1 → 2 times
2 → 2 times
3 → 2 times

Problem 10: Diagonal Sum of a Matrix

Description: Write a Java program to find the sum of the primary and secondary diagonals of an N×N matrix.

Example:

Input: 3×3 Matrix:
1 2 3
4 5 6
7 8 9
Output:
Primary Diagonal Sum: 15
Secondary Diagonal Sum: 15