C# 기초

C# Loops: for, foreach and while

Repeat work with the right loop: for when you need an index, foreach for every item, while for a condition.

  • 초급
  • 2분 분량
  • 실행 가능한 예제 1개
배울 내용
  • for with a counter
  • foreach over arrays and lists
  • while, break and continue
foreach even number, print its square
1skip
2→ 4
3skip
4→ 16
5skip
6→ 36
Odd numbers hit continue; even ones are squared.

Pick the loop that matches the job

C#에는 상황에 맞는 여러 반복문이 있습니다. for 반복문은 인덱스가 필요할 때, foreach는 값만 차례로 필요할 때 알맞고, while은 조건이 참인 동안 반복합니다.

foreach 반복문은 인덱스를 다루지 않고 배열의 각 숫자를 꺼냅니다. 숫자가 홀수이면 continue 키워드가 반복문을 멈추지 않고 현재 반복의 나머지를 건너뛰어 다음 숫자로 넘어갑니다. 그래서 프로그램은 짝수의 제곱인 4, 16, 36만 출력합니다.

핵심 포인트

  1. foreach visits every element in order without an index.
  2. continue skips to the next round; break leaves the loop.
  3. while repeats as long as its condition is true.

동작 원리 보기

한 단계를 누르면 반복문이 한 걸음씩 실행됩니다. 조건 확인, 본문 실행, 추적 표가 한 줄씩 늘어나는 모습을 보세요.

실행 가능한 C# 예제

C#
코드 실행 →
Program.cs
using System;

class Program
{
    static void Main()
    {
        int[] numbers = { 1, 2, 3, 4, 5, 6 };
        foreach (int number in numbers)
        {
            if (number % 2 != 0) continue;
            Console.WriteLine(number * number);
        }
    }
}
이 예제의 실행 버튼 만들기 실행 결과
4
16
36

디버거로 연습하기

중요한 대입이나 조건에 중단점을 두고 Debug를 눌러 다음 줄로 넘어가기 전에 지역 변수 값을 확인하세요.

챌린지로 연습하기

이 레슨에서 배운 내용으로 실제 문제를 풀어 보세요. 모든 챌린지는 브라우저에서 실행되며 즉시 테스트와 AI 리뷰를 받을 수 있습니다.

모든 챌린지