본문 바로가기
C#

반복문

by 김차루 2024. 5. 1.
 
 
 

 

 

 

 

 

 

1. 반복문

1) for 문

for (초기식; 조건식; 증감식)
{
    // 조건식이 참인 경우 실행되는 코드
}

//예시
for (int i = 0; i < 10; i += 2 )
{
    Console.WriteLine(i);
}
  • for 문은 초기식, 조건식, 증감식을 사용하여 반복문을 작성
  • 초기식 : 반복문이 시작될 때 단 한 번 실행
  • 조건식 : 반복문이 실행될 때마다 평가되며, 참(true)인 경우 반복문이 계속 실행
  • 증감식 : 반복문이 실행될 때마다 실행되는 식

2) while 문

while (조건식)
{
    // 조건식이 참인 경우 실행되는 코드
}

//예시
int i = 0;
while (i < 10)
{
    Console.WriteLine(i);
    i++;
}

 

  • 조건식이 참(true)인 동안 코드 블록을 반복적으로 실행

3) for문 vs while문

int sum = 0;
for (int i = 1; i <= 5; i++)
{
	sum += i;
}

Console.WriteLine("1부터 5까지의 합은 " + sum + "입니다.");
  • for문 : 반복 횟수를 직관적으로 알 수 있고, 반복 조건을 한 눈에 확인할 수 있어 가독성이 좋다.
  • while문 : 반복 조건에 따라 조건문의 실행 횟수가 유동적이며, 이에 따라 코드가 더 간결할 수 있다.
  • 따라서, 어떤 반복문을 사용할지는 코드의 흐름에 따라 상황에 맞게 선택하는 것이 좋다.

4) do - while 문

do
{
    // 조건식이 참인 경우 실행되는 코드
}
while (조건식);

//예시
int sum = 0;
int num;

do
{
    Console.Write("숫자를 입력하세요 (0 입력 시 종료): ");
    num = int.Parse(Console.ReadLine());
    sum += num;
} while (num != 0);

Console.WriteLine("합계: " + sum);

 

5) foreach 문

foreach (자료형 변수 in 배열 또는 컬렉션)
{
    // 배열 또는 컬렉션의 모든 요소에 대해 반복적으로 실행되는 코드
}

//예제
string[] inventory = {"검", "방패", "활", "화살", "물약"};

foreach (string item in inventory)
{
	Console.WriteLine(item);
}

 

6) 중첩반복문

for(int i = 0; i < 5; i++)
{
	for(int j = 0; j < 3; j++)
    {
    	Console.WriteLine("i : {0}, j : {1}", i, j);
    }
}
  • 이차원 반복문

7) Break & Continue

for (int i = 1; i <= 10; i++)
{
    if (i % 3 == 0)
    {
        continue; // 3의 배수인 경우 다음 숫자로 넘어감
    }

    Console.WriteLine(i);
    if (i == 7)
    {
        break; // 7이 출력된 이후에는 반복문을 빠져나감
    }
}
  • break : 반복문을 중지시키는 역할
  • continue : 현재 반복을 중지하고 다음 반복을 진행하는 역할

 

2. 반복문 심화 실습

1) 가위바위보

stringp[] choices = {"가위", "바위", "보"};
string playerChoice = "";
string computerChoice = choices[new Random().Next(0, 3)];

while(playerChoice != computerChoice)
{
	Console.Write("가위, 바위, 보 중 하나를 선택하세요 : ");
    playerChoice = Console.ReadLine();
    
    Console.WriteLine("컴퓨터 : " + computerChoice);
    
    if(playerChoice == computerChoice) 
    {
    	Console.WriteLine("비겼습니다!");
    }
    else if((playerChoice == "가위" && computerChoice == "보") ||
			(playerChoice == "바위" && computerChoice == "가위") ||
            (playerChoice == "보" && computerChoice == "바위"))
    {
    	Console.WriteLine("플레이어 승리!");
    }
    else
    {
     Console.WrieLine("컴퓨터 승리!");
    }

 

2) 숫자 맞추기

int targetNum = new Random().Next(1, 101);
int guess = 0;
int count = 0;

Console.WriteLine("1부터 100 사이의 숫자를 맞춰보세요.");

while(guess != targetNum)
{
	Console.Write("추측한 숫자를 입력하세요 : ");
    guess = int.Parse (Console.ReadLine());
    count++;
    
    if(guess < targetNum )
    {
    	Console.WriteLine("좀 더 큰 숫자를 입력하세요.");
    }
    else if (guess > targetNum)
    {
    	Console.WriteLine("좀 더 작은 숫자를 입력하세요.");
    }
    else
    {
    	Console.WriteLine("축하합니다! 숫자를 맞추셨습니다.");
        Console.WriteLine("시도한 횟수 : " + count);
    }
}

'C#' 카테고리의 다른 글

조건문  (0) 2024.05.01
연산자와 문자열 처리  (0) 2024.05.01
변수와 자료형  (0) 2024.05.01
프로그래밍 기본 요소  (0) 2024.04.26