Are you sure question has been asked to solve by using 3 for loops? As it is better to use less loop as much as we can. Secondly there is no requirement in problem to use third loop. you can find the desired result by using two loops: public class Main { public static void main(String[] args) { for (int i = 1; i <= 7; i++) { for (int j = 1; j <= 7; j++) { if (j <= i) { System.out.print(j); } else { System.out.print("*"); } } System.out.println("\n"); } } } output will be:1******12*****123****1234***12345**123456*1234567