작성일 :

문제 링크

2442번 - 별 찍기 - 5

설명

주어진 N에 따라서, 공백과 별의 개수를 계산한 후 정삼각형 모양으로 출력하는 문제입니다.


접근법

  • N줄이 출력됩니다.
  • 각 줄의 구성은 아래와 같습니다:
    • 왼쪽 공백: N - 1 - i개 (i0부터 시작)
    • *: 2 * i + 1
  • 위 규칙을 이용하여 반복문을 통해 각 줄마다 공백과 별을 출력합니다.

Code

[ C# ]

1
2
3
4
5
6
7
8
9
10
11
12
13
using System;

namespace Solution {
  class Program {
    static void Main(string[] args) {
      var n = int.Parse(Console.ReadLine()!);
      for (int i = 0; i < n; i++) {
        Console.Write(new string(' ', n - 1 - i));
        Console.WriteLine(new string('*', 2 * i + 1));
      }
    }
  }
}



[ C++ ]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <bits/stdc++.h>

using namespace std;

int main() {
  ios::sync_with_stdio(false);
  cin.tie(nullptr);

  int n; cin >> n;
  for (int i = 0; i < n; i++) {
    for (int j = 0; j < n - 1 - i; j++) cout << " ";
    for (int j = 0; j < 2 * i + 1; j++) cout << "*";
    cout << "\n";
  }

  return 0;
}