learn2code

Master Java Number Patterns Program: 10 Interview Questions

Java Number Patterns Program

10 Java Number Patterns Programs for Interview. Elevate your interview performance and showcase your problem-solving skills effortlessly.

1.Half Pyramid of Numbers – Number Patterns Program

HalfPyramidNumbers Pattern Program
1
12
123
1234
12345
Java Pattern Program: HalfPyramidNumbers Pattern Program
public class HalfPyramidNumbers {
    public static void main(String[] args) {
        int rows = 5;
        for (int i = 1; i <= rows; i++) {
            for (int j = 1; j <= i; j++) {
                System.out.print(j + " ");
            }
            System.out.println();
        }
    }
}
        
Run Code

Here's a step-by-step explanation:

  1. Class Declaration:
    • The program starts with the declaration of a public class named HalfPyramidNumbers.
  2. Main Method:
    • Inside the HalfPyramidNumbers class, there's a main method, which serves as the entry point of the program. It is declared as public static void main(String[] args).
  3. Variable Declaration:
    • In the main method, an integer variable rows is declared and initialized with the value 5. This variable represents the number of rows in the pattern to be printed.
  4. Outer Loop (Rows):
    • The program uses a for loop to iterate over the rows of the pattern. It starts with i = 1 and continues as long as i is less than or equal to rows. In each iteration, i is incremented by 1.
  5. Inner Loop (Columns):
    • Inside the outer loop, there's another for loop responsible for printing the numbers in each row of the pattern. It starts with j = 1 and continues as long as j is less than or equal to i (the current row number). In each iteration, j is incremented by 1.
  6. Print Numbers:
    • Inside the inner loop, the program prints the value of j followed by a space using System.out.print(j + " "). This prints the numbers from 1 up to the value of i in each row, separated by spaces.
  7. New Line:
    • After printing all the numbers for a particular row, the program moves to the next line using System.out.println() to start a new row.
  8. Repeat:
    • The outer loop continues to execute until i reaches the value of rows, printing one row at a time with increasing numbers in each row.

2.Inverted Half Pyramid of Numbers

Inverted Half Pyramid of Numbers Pattern Program
1 2 3 4 5 
1 2 3 4 
1 2 3 
1 2 
1 
Java Pattern Program: Inverted Half Pyramid of Numbers
public class InvertedHalfPyramidNumbers {
    public static void main(String[] args) {
        int rows = 5;
        for (int i = rows; i >= 1; i--) {
            for (int j = 1; j <= i; j++) {
                System.out.print(j + " ");
            }
            System.out.println();
        }
    }
}
        
Run Code

Here's a step-by-step explanation:

  1. Class Declaration: The program begins with the declaration of a public class named InvertedHalfPyramidNumbers. This class contains the main method, which serves as the entry point of the program.
  2. Main Method: Inside the main method, the program's execution starts. This method is declared as public static void, indicating that it can be accessed by other classes without needing to instantiate an object of the class (static), and it doesn't return any value (void).
  3. Variable Initialization: Within the main method, an integer variable rows is declared and initialized with the value 5. This variable represents the number of rows in the inverted half pyramid.
  4. Outer Loop (i): The program uses a for loop to iterate over the rows of the inverted half pyramid. The loop starts with the value of i set to the value of rows (5 in this case), and it decrements i by 1 in each iteration until i becomes 0. This loop controls the number of rows in the inverted half pyramid.
  5. Inner Loop (j): Within the outer loop, another for loop is used to print the numbers in each row. This loop starts with the value of j set to 1 and increments j by 1 in each iteration until j becomes equal to i. This loop controls the number of columns in each row and prints the numbers from 1 to i.
  6. Print Statement: Inside the inner loop, the program prints the value of j followed by a space using System.out.print(). This prints the numbers in the pattern required for the inverted half pyramid.
  7. New Line: After printing the numbers for each row, the program moves to a new line using System.out.println(). This results in the numbers being printed in different rows, forming the inverted half pyramid pattern.
  8. End of Inner Loop: Once the inner loop completes its execution for each row, the program moves to the next iteration of the outer loop (if applicable), where i is decremented, and the process repeats until all rows are printed.
  9. End of Program: After all rows are printed, the program execution completes, and the program terminates.

Overall, this program generates an inverted half pyramid of numbers with each row containing numbers from 1 to the row number. The number of rows in the pyramid is specified by the rows variable, which is currently set to 5.


3. Floyd's Triangle

Floyd's Triangle of Numbers Pattern Program
1 
2 3 
4 5 6 
7 8 9 10 
11 12 13 14 15 
Java Pattern Program: Floyd's Triangle
public class FloydsTriangle {
    public static void main(String[] args) {
        int rows = 5;
        int num = 1;
        for (int i = 1; i <= rows; i++) {
            for (int j = 1; j <= i; j++) {
                System.out.print(num + " ");
                num++;
            }
            System.out.println();
        }
    }
}
        
Run Code

Here's a step-by-step explanation:

  1. Class Declaration:
    • The program starts with declaring a public class named FloydsTriangle. In Java, the name of the class must match the name of the file containing it.
  2. Main Method:
    • Inside the FloydsTriangle class, there is a main method. This method is the entry point of the program, where execution begins.
  3. Variable Initialization:
    • Two integer variables rows and num are initialized. rows stores the number of rows in the triangle pattern, and num is used to generate the numbers for the triangle.
  4. Nested Loop:
    • Two nested for loops are used to print the triangle pattern.
    • The outer loop (for (int i = 1; i <= rows; i++)) controls the number of rows in the triangle. It iterates from 1 to the value of rows.
    • The inner loop (for (int j = 1; j <= i; j++)) controls the number of elements in each row. It iterates from 1 to the current value of i.
    • Inside the inner loop, the value of num is printed followed by a space, and then num is incremented.
    • After printing all elements of a row, a newline character (System.out.println()) is printed to move to the next row.
  5. Output:
    • The program prints a Floyd's Triangle pattern with 5 rows. Floyd's Triangle is a right-angled triangular array of natural numbers, used in mathematics and computer science education. Each row contains consecutive natural numbers, starting from 1 and increasing by 1 in each subsequent row.
  6. End of Program:
    • After printing the triangle pattern, the main method ends, and the program terminates.

Explore More Star Pattern Interview Questions: Click Here

4. Pyramid of Numbers

Pyramid of Numbers Pattern Program
        1 
      1 2 3 
    1 2 3 4 5 
  1 2 3 4 5 6 7 
1 2 3 4 5 6 7 8 9 
Java Pattern Program: Pyramid of Numbers
public class PyramidNumbers {
    public static void main(String[] args) {
        int rows = 5, k = 0;
        for (int i = 1; i <= rows; i++, k = 0) {
            for (int space = 1; space <= rows - i; space++) {
                System.out.print("  ");
            }
            while (k != 2 * i - 1) {
                System.out.print((k + 1) + " ");
                k++;
            }
            System.out.println();
        }
    }
}
        
Run Code

Here's a step-by-step explanation:

  1. The program begins with the declaration of a public class named PyramidNumbers.
  2. Inside the class, there is a main method, which serves as the entry point for the program.
  3. In the main method, two integer variables are declared and initialized:
    • rows is set to 5, indicating the number of rows in the pyramid.
    • k is initialized to 0. This variable is used to keep track of the numbers to be printed in each row.
  4. The program uses a nested loop structure to generate the pyramid pattern. The outer loop iterates over each row of the pyramid, starting from row 1 and ending at row rows.
  5. Within the outer loop, a nested loop is used to print spaces before printing the numbers. The number of spaces decreases as the row number increases, creating the pyramid shape. This loop runs from 1 to rows - i, where i represents the current row number.
  6. Inside the nested loop, System.out.print(" ") prints two spaces for each space required in the pyramid. This ensures proper alignment of the numbers.
  7. After printing the spaces, a while loop is used to print the numbers for each row. This loop runs until k becomes equal to 2 * i - 1, where i represents the current row number. In each iteration of this loop, it prints the value of k + 1, followed by a space.
  8. The variable k is incremented in each iteration of the while loop to ensure that the correct sequence of numbers is printed for each row.
  9. Once all the numbers for the current row have been printed, a new line is printed using System.out.println() to move to the next row.
  10. This process repeats until all the rows of the pyramid have been printed.

5. Pascal's Triangle

Pascal's Triangle Pattern Program
          1
        1   1
      1   2   1
    1   3   3   1
  1   4   6   4   1
Java Pattern Program: Pascal's Triangle
public class PascalsTriangle {
    public static void main(String[] args) {
        int rows = 5;
        for (int i = 0; i < rows; i++) {
            int number = 1;
            System.out.format("%" + (rows - i) * 2 + "s", "");
            for (int j = 0; j <= i; j++) {
                System.out.format("%4d", number);
                number = number * (i - j) / (j + 1);
            }
            System.out.println();
        }
    }
}
        
Run Code

Here's a step-by-step explanation:

  1. Class Declaration: The program starts with the declaration of a public class named PascalsTriangle.
  2. Main Method: Inside the class, there's the main method, which serves as the entry point for the program execution.
  3. Variable Initialization: Within the main method, an integer variable rows is initialized with a value of 5. This variable determines the number of rows in Pascal's triangle that will be printed.
  4. Outer Loop (Row Generation): The program uses a for loop to iterate over each row of Pascal's triangle. It starts from i = 0 and continues until i < rows.
  5. Space Formatting: Inside the outer loop, there's a line to format spaces before printing the numbers. It dynamically adjusts the number of spaces based on the current row (rows - i), multiplying it by 2 and formatting it as a string with System.out.format.
  6. Inner Loop (Printing Numbers): Within the outer loop, there's another for loop to generate and print the numbers for each row of the triangle. It starts from j = 0 and continues until j <= i, where i represents the current row number.
  7. Number Calculation: Inside the inner loop, a variable named number is initialized with a value of 1. This variable holds the value of each number in the current row of Pascal's triangle.
  8. Printing Numbers: Using System.out.format, the program prints each number with a width of 4 characters (%4d). This ensures that each number is properly aligned in the triangle.
  9. Number Calculation (Cont.): After printing each number, the program calculates the next number in the row using the formula number = number * (i - j) / (j + 1). This formula calculates each number based on the previous number and its position in the row.
  10. New Line: After printing all the numbers for a row, the program prints a newline character (System.out.println()) to move to the next row.
  11. Loop Continuation: The outer loop continues until all rows of Pascal's triangle are generated and printed.
  12. End of Program: Once all rows are printed, the main method ends, and consequently, the program terminates.

6. Number Pattern with Spaces

Number Pattern with Spaces Pattern Program
        1 
      1 2 
    1 2 3 
  1 2 3 4 
1 2 3 4 5 
Java Pattern Program: Number Pattern with Spaces
public class NumberPatternWithSpaces {
    public static void main(String[] args) {
        int rows = 5;
        for (int i = 1; i <= rows; i++) {
            for (int j = 1; j <= rows - i; j++) {
                System.out.print("  ");
            }
            for (int k = 1; k <= i; k++) {
                System.out.print(k + " ");
            }
            System.out.println();
        }
    }
}
        
Run Code

Here's a step-by-step explanation:

  1. Class Declaration:
    • The program begins with the declaration of a public class named NumberPatternWithSpaces.
  2. Main Method:
    • Inside the class, there is a main method, which is the entry point of the program.
  3. Variable Initialization:
    • In the main method, an integer variable rows is initialized with a value of 5. This variable determines the number of rows in the pattern.
  4. Outer Loop:
    • The program uses a for loop with a control variable i to iterate over each row of the pattern. It starts from 1 and continues until i reaches the value of rows.
  5. Inner Loop for Spaces:
    • Inside the outer loop, there is another for loop with control variable j. This loop is responsible for printing the spaces before the numbers in each row.
    • The number of spaces decreases as i increases. This is achieved by iterating from 1 to rows - i.
  6. Printing Spaces:
    • Within the inner loop, System.out.print(" ") is used to print two spaces without advancing to a new line. This creates the required spacing before the numbers.
  7. Inner Loop for Numbers:
    • After printing the spaces, there is another for loop with control variable k, responsible for printing the numbers in each row.
    • This loop starts from 1 and continues until k reaches the value of i.
    • The loop prints the numbers from 1 to i, separated by a space.
  8. Printing Numbers:
    • Inside the inner loop, System.out.print(k + " ") is used to print the current value of k followed by a space.
  9. Newline:
    • After printing the numbers for each row, System.out.println() is used to move to the next line, starting a new row in the pattern.
  10. Loop Continues:
    • The outer loop continues to iterate until i reaches the value of rows, printing each row of the pattern with appropriate spaces and numbers.
  11. Program Completion:
    • Once the outer loop finishes executing, the main method concludes, and the program execution ends.

7. Number Pattern in Reverse

Number Pattern in Reverse Pattern Program
5 4 3 2 1 
5 4 3 2 
5 4 3 
5 4 
5 
Java Pattern Program: Number Pattern in Reverse
public class NumberPatternInReverse {
    public static void main(String[] args) {
        int rows = 5;
        for (int i = 1; i <= rows; i++) {
            for (int j = rows; j >= i; j--) {
                System.out.print(j + " ");
            }
            System.out.println();
        }
    }
}
        
Run Code

Here's a step-by-step explanation:

  1. Class Declaration: The program starts with the declaration of a public class named NumberPatternInReverse. In Java, every application begins with a class definition.
  2. Main Method: Within the NumberPatternInReverse class, there is a main method. This method serves as the entry point of the program, where the execution begins.
  3. Variable Declaration and Initialization: Inside the main method, an integer variable named rows is declared and initialized with the value 5. This variable represents the number of rows in the pattern to be printed.
  4. Outer Loop: The program uses a for loop to iterate from 1 to rows. This loop controls the number of rows in the pattern.
  5. Inner Loop: Within the outer loop, there is another for loop. This loop iterates from rows down to i. It controls the number of elements to be printed in each row, and it starts from rows and decrements by 1 in each iteration.
  6. Printing Numbers: Inside the inner loop, the program prints the value of j followed by a space. The value of j represents the numbers to be printed in each row. Since the inner loop iterates from rows down to i, it prints the numbers in reverse order in each row.
  7. Newline: After printing the numbers for each row, the program prints a newline character (\n) to move to the next line and start a new row.
  8. End of Inner Loop: Once the inner loop completes its iterations for a particular row, the control goes back to the outer loop, and the next iteration begins.
  9. End of Program: Once all the iterations of the outer loop are completed, the program execution ends.

8. Right Triangle of Numbers

Right Triangle of Numbers Pattern Program
1 
1 2 
1 2 3 
1 2 3 4 
1 2 3 4 5 
Java Pattern Program: NRight Triangle of Numbers
public class RightTriangleNumbers {
    public static void main(String[] args) {
        int rows = 5;
        for (int i = 1; i <= rows; i++) {
            for (int j = 1; j <= i; j++) {
                System.out.print(j + " ");
            }
            System.out.println();
        }
    }
}

        
Run Code

Here's a step-by-step explanation:

  1. Class Declaration: The program starts with the declaration of a public class named RightTriangleNumbers. In Java, every application must have at least one class definition, and the name of the file containing the class must match the name of the class (in this case, it should be saved in a file named RightTriangleNumbers.java).
  2. Main Method: Inside the class, there's a main method, which serves as the entry point of the program. It is declared with the public static void keywords, indicating that it can be accessed from outside the class without creating an object of the class (public), it can be called without creating an instance of the class (static), and it does not return any value (void). The main method takes an array of strings (String[] args) as its parameter, which allows the program to accept command-line arguments.
  3. Variable Initialization: Within the main method, an integer variable named rows is initialized with the value 5. This variable determines the number of rows in the right triangle pattern.
  4. Outer Loop (Rows): The program then enters a loop that iterates from 1 to the value of rows (inclusive). This loop controls the number of rows in the right triangle pattern.
  5. Inner Loop (Columns): Inside the outer loop, there's another loop that iterates from 1 to the current value of i (inclusive). This inner loop controls the number of columns (or numbers) printed in each row of the pattern.
  6. Printing Numbers: Within the inner loop, the program prints the current value of j followed by a space using System.out.print(j + " "). This prints the numbers 1, 2, 3, ..., up to the current value of i, separated by spaces, in each row of the pattern.
  7. New Line: After printing all the numbers for the current row, the program prints a newline character (\n) using System.out.println(). This moves the cursor to the next line, creating a new row in the pattern.
  8. Loop Execution: The outer loop continues to iterate until the value of i reaches the value of rows, and the inner loop executes its iterations accordingly.
  9. Program Completion: Once the outer loop finishes executing, the main method ends, and consequently, the program terminates.

Explore More Star Pattern Interview Questions: Click Here

Leave a Reply

Harish

Typically replies within a hours