*
**
***
****
*****
위와 같이 별을 출력하는 문제이다.
반복문을 사용해 별의 개수를 1개씩 늘려가며 출력한다.
이중 반복문과 단일 반복문을 사용하는 방법 2가지를 설명한다.
Console.Write()와 string 말고 StringBuilder를 사용해 런타임 시간을 줄였다. StringBuilder sb에 출력할 별을 추가한 후 한 줄마다 출력한다.
using System;
using System.Text;
namespace BJ_2438{
class Program{
static void Main(string[] arg){
int n = int.Parse(Console.ReadLine());
for (int i = 1; i <= n; i++){
StringBuilder sb = new StringBuilder();
for(int j = 0; j < i; j++)
sb.Append('*');
Console.WriteLine(sb);
}
}
}
}
코드를 줄일 방법을 찾다 알게된 방법이다.
string 객체를 생성과 동시에 초기화한다.
new string(문자, 개수)는 개수만큼 문자가 출력된다.
즉, new string('*', 3); 는 "***" 으로 출력된다.
using System;
namespace BJ_2438{
class Program{
static void Main(string[] arg){
int n = int.Parse(Console.ReadLine());
for (int i = 1; i <= n; i++)
Console.WriteLine(new string('*', i));
}
}
}