Diamond with nested for loop in Java

前端 未结 7 610
暗喜
暗喜 2021-01-23 13:27

I am trying to display a diamond of asterisks using nested for loops.

Here is my code so far:

public          


        
7条回答
  •  悲哀的现实
    2021-01-23 14:06

    In your first for loop remove = mark and just use < e.g. for (int i = 1; i < size; i += 2).

    Full code:

    int size = 9;
    
    for (int i = 1; i < size; i += 2) {
        for (int k = size; k >= i; k -= 2) {
            System.out.print(" ");
        }
        for (int j = 1; j <= i; j++) {
            System.out.print("*");
        }
        System.out.println();
    }// end loop
    
    for (int i = 1; i <= size; i += 2) {
        for (int k = 1; k <= i; k += 2) {
            System.out.print(" ");
        }
        for (int j = size; j >= i; j--) {
            System.out.print("*");
        }
        System.out.println();
    }// end loop
    

提交回复
热议问题