0

введите сюда описание изображения

Мой код:

public class Main { public static void main(String[] args) {

    for (int i = 0; i < 10; i++){
        for (int j = 0; j < 10; j++) {

            if (j >= i) {
                System.out.print((j) + " ");
            }
            else {
                System.out.print(" " + " ");
            }
        }
        System.out.println();
    }
}

}

2 ответа 2

1

Представленный код печатает только одну половину треугольника/пирамиды по возрастанию, его следует переделать для печати по убыванию и добавить вложенный цикл для печати чисел от 0 до 9:

    for (int i = 10; i-- > 0; ) {
        for (int j = 0; j < 9 - i; j++) {
            System.out.print("  ");
        }
        for (int j = i; j > 0; j--) {
            System.out.print(j);
            System.out.print(" ");
        }
        for (int j = 0; j <= i; j++) {
            System.out.print(j);
            if (j < i) { 
                System.out.print(" ");
            }
        }
        System.out.println();
    }
9 8 7 6 5 4 3 2 1 0 1 2 3 4 5 6 7 8 9
  8 7 6 5 4 3 2 1 0 1 2 3 4 5 6 7 8
    7 6 5 4 3 2 1 0 1 2 3 4 5 6 7
      6 5 4 3 2 1 0 1 2 3 4 5 6
        5 4 3 2 1 0 1 2 3 4 5
          4 3 2 1 0 1 2 3 4
            3 2 1 0 1 2 3
              2 1 0 1 2
                1 0 1
                  0

Первый вложенный цикл для вывода пробелов можно заменить на System.out.print(" ".repeat(9 - i));


Вариант со Stream API:

IntStream.iterate(9, i -> i >= 0, i -> i - 1) // цикл от 9 до 0 включительно
    .mapToObj(i -> IntStream.range(0, 2 * i + 1)
            .map(j -> Math.abs(j - i))   // цифры по убыванию и возрастанию
            .mapToObj(String::valueOf)   // цифра в строку
            .collect(Collectors.joining( // склеить все "цифры"
                " ",                     // через пробел
                "  ".repeat(9 - i),      // префикс из 2 пробелов
                ""                       // суффикс (не нужен)
            ))
    )
    .forEach(System.out::println);       // вывод готовой строки
0

Пример на C#, на java сами переведите =)

int padding = 0;
for(int i=0; i<10;i++)
{
    var pad = padding;
    while(--pad >= 0) Console.Write(" ");
    
    var num = 10 - padding;
    while(--num > 0)  Console.Write(num);
    Console.Write(0);
    while(++num < 10-padding)  Console.Write(num);          
    padding++;
    
    Console.WriteLine();
}

Вывод

9876543210123456789 
 87654321012345678  
  765432101234567   
   6543210123456    
    54321012345     
     432101234      
      3210123       
       21012        
        101         
         0          

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.