C# 중첩 루프 마스터하기: For, While, Do-While 완벽 가이드
다른 루프 안에 있는 루프를 중첩 루프(nested loop)라고 합니다. 중첩 루프의 구조는 다음과 같습니다:
외부 루프 { // 외부 루프 본문 내부 루프 { // 내부 루프 본문 } ... ... ... } 보시다시피 외부 루프가 내부 루프를 감싸고 있습니다. 내부 루프는 외부 루프의 일부이며 외부 루프 본문 내에서 시작하고 끝나야 합니다.
외부 루프의 각 반복마다 내부 루프가 완전히 실행됩니다.
중첩 for 루프
다른 for 루프 안에 있는 for 루프를 중첩 for 루프라고 합니다.
예시:
for (int i=0; i<5; i++) { // 외부 for 루프 본문 for (int j=0; j<5; j++) { // 내부 for 루프 본문 } // 외부 for 루프 본문 } 예제 1: 중첩 for 루프
using System; namespace Loop { class NestedForLoop { public static void Main(string[] args) { int outerLoop = 0, innerLoop = 0; for (int i=1; i<=5; i++) { outerLoop ++; for (int j=1; j<=5; j++) { innerLoop++; } } Console.WriteLine("외부 루프 실행 횟수: {0}", outerLoop); Console.WriteLine("내부 루프 실행 횟수: {0}", innerLoop); } } }
프로그램 실행 시 출력:
외부 루프 실행 횟수: 5 내부 루프 실행 횟수: 25
이 프로그램에서 외부 루프는 5번 실행됩니다. 외부 루프가 실행될 때마다 내부 루프가 5번 실행되어 총 25번 실행됩니다.
예제 2: 패턴 출력을 위한 중첩 for 루프
using System; namespace Loop { class NestedForLoop { public static void Main(string[] args) { for (int i=1; i<=5; i++) { for (int j=1; j<=i; j++) { Console.Write(j + " "); } Console.WriteLine(); } } } }
프로그램 실행 시 출력:
1 1 2 1 2 3 1 2 3 4 1 2 3 4 5
중첩 while 루프
다른 while 루프 안에 있는 while 루프를 중첩 while 루프라고 합니다.
예시:
while (조건1) { // 외부 while 루프 본문 while (조건2) { // 내부 while 루프 본문 } // 외부 while 루프 본문 } 예제 3: 중첩 while 루프
using System; namespace Loop { class NestedWhileLoop { public static void Main(string[] args) { int i=0; while (i<2) { int j=0; while (j<2) { Console.Write("({0},{1}) ", i,j); j++; } i++; Console.WriteLine(); } } } }
프로그램 실행 시 출력:
(0,0) (0,1) (1,0) (1,1)
중첩 do-while 루프
다른 do-while 루프 안에 있는 do-while 루프를 중첩 do-while 루프라고 합니다.
예시:
do { // 외부 루프 본문 do { // 내부 루프 본문 } while (조건2); // 외부 루프 본문 } while (조건1); 예제 4: 중첩 do-while 루프
using System; namespace Loop { class NestedWhileLoop { public static void Main(string[] args) { int i=0; do { int j=0; do { Console.Write("({0},{1}) ", i,j); j++; } while (j<2); i++; Console.WriteLine(); } while (i<2); } } }
프로그램 실행 시 출력:
(0,0) (0,1) (1,0) (1,1)
서로 다른 내부 및 외부 중첩 루프
동일한 유형의 루프를 중첩할 필요는 없습니다. for 루프를 while 루프 안에 넣거나 do-while 루프를 for 루프 안에 넣을 수 있습니다.
예제 5: C# 중첩 루프: 서로 다른 내부 및 외부 루프
using System; namespace Loop { class NestedLoop { public static void Main(string[] args) { int i=1; while (i<=5) { for (int j=1; j<=i; j++) { Console.Write(i + " "); } Console.WriteLine(); i++; } } } }
프로그램 실행 시 출력:
1 2 2 3 3 3 4 4 4 4 5 5 5 5 5
위 프로그램에서 for 루프가 while 루프 내에 배치되었습니다. 루프 안에 다른 유형의 루프를 사용할 수 있습니다.