Skip to main content

ProwessApps

Learn · Practice · Excel

Write a program to print the following pattern:
1
2 3
4 5 6
7 8 9 10

Java Code Example — Pattern Programs

ADVERTISEMENT

Write a program to print the following pattern:
1
2 3
4 5 6
7 8 9 10

Objective

Write a Java program to print Floyd's Triangle (a right-angled triangle with running sequential numbers).

Algorithm / Approach

  1. Initialize a counter k = 1 outside the loops.
  2. Use an outer loop (i) from 1 to 4.
  3. Use an inner loop (j) from 1 to i.
  4. Print the value of k, then increment k by 1.
  5. Print a newline.
Test.java
class Test {
 public static void main(String[] a)
 {
  int k = 1;
  for(int i = 1; i<= 4; i++) {
   for(int j = 1; j<=i; j++) {
    System.out.print(k+" ");
    k++;
   }
   System.out.println();
  }
 }
}

Explanation of the Program

  • Floyd's Triangle is a classic computer science problem.
  • Similar to the even-number triangle, it relies on a stateful variable (k) declared outside the loops.
  • The variable simply increments by 1 on every single inner loop execution, creating a continuous sequence spanning across multiple rows.

Complexity

Time Complexity O(n2)
Space Complexity O(1)
ADVERTISEMENT