반응형

for문을 활용하는 대표적인 문제이다
#include <iostream>
#include <string>
using namespace std;
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
int a;
cin >> a;
for (int tmp=1; tmp<=a; tmp++)
{
cout << string(tmp, '*') << "\n";
}
return 0;
}
정석 풀이는 이중 for문으로 한 줄 씩 찍어나가는 풀이지만
string 함수를 사용한 풀이도 있어 소개하려고 한다
string 함수는 특정 문자를 반복해서 출력하고 싶을 때 사용하면 편리하다
#include <string>을 선언해야 하고
첫번째 파라미터에는 int타입의 숫자가 들어가야하고
두번째 파라미터에는 char타입의 문자가 들어가야한다
즉 string(tmp, "*")은 tmp번 반복되는 *을 생성하라는 의미이다
정석적인 풀이도 소개해보겠다
// Authored by : wogha95
// Co-authored by : BaaaaaaaaaaarkingDog
// http://boj.kr/b6adf7a5cfeb49f7a45563ac675a6b3a
#include <bits/stdc++.h>
using namespace std;
int main(void){
ios::sync_with_stdio(0);
cin.tie(0);
int N;
cin >> N;
for(int i = 0; i < N; i++) {
for(int j = 0; j <= i; j++) cout << '*';
cout << "\n";
}
}
반응형
'algorithm > 기초 코드' 카테고리의 다른 글
| [algorithm] 백준 2562번 최댓값 (0) | 2025.10.25 |
|---|---|
| [algorithm] 백준 15552번 빠른 A+B (0) | 2025.10.25 |
| [algorithm] 백준 10804 카드 역배치 (0) | 2025.10.18 |
| [algorithm] 백준 1267번 핸드폰 요금 (0) | 2025.10.18 |
| [algorithm] 백준 2309번 일곱난쟁이 (0) | 2025.10.18 |
