foreach, break와 continue
Coddy의 Python 개발자를 위한 C# 코스 레슨. 48개 중 15번째.
시퀀스를 순회하는 Python의 for-in은 C#의 foreach에 해당합니다. break와 continue의 의미는 익숙하지만, C#에는 Python의 loop-else 절이 없습니다. C#의 while에는 bool 조건이 필요하므로, 숫자나 횟수를 명시적으로 비교해야 합니다.
foreach는 인덱스를 직접 관리하지 않고 값들을 차례로 방문합니다. break는 루프를 끝내고 continue는 다음 반복으로 건너뜁니다. 반복이 컬렉션이 아니라 변하는 조건에 따라 달라질 때는 while이 유용합니다. foreach 열거자가 활성화된 동안에는 List를 변경하지 마세요.
Python 참고
value = 0
while value < 3:
value += 1
print(value)Main 안의 C# 문장
int value = 0;
while (value < 3) value++;
Console.WriteLine(value);이 내용은 핵심을 다루는 교육용 발췌문입니다. 챌린지 파일에는 실행 가능한 전체 래퍼가 포함되어 있으며, 위 코드 조각은 관련 선언과 문장을 보여 줍니다.
참고 출력:
3C# 출력:
3챌린지
쉬움첫 번째 음수 값이 나오기 전에 배열의 양수 값을 합산하고, 0은 건너뛰며 첫 번째 음수 뒤의 모든 값은 무시하세요. 입력은 쉼표로 구분된 한 줄입니다.
잠금 해제된 C# 파일을 수정하세요. 잠겨 있어 보이는 Main.cs는 설명된 줄을 읽고, Exercise.Solve를 호출하며, 입력이 변경되지 않았는지 확인한 다음 결과를 마지막 줄바꿈 하나와 함께 출력합니다. 선언된 API를 유지하세요. 두 번째 Main을 추가하거나 진단 출력을 하지 마세요.
직접 해보기
using System;
using System.Linq;
using System.Collections.Generic;
using System.Globalization;
public class Program {
static int I(string text) { return int.Parse(text,CultureInfo.InvariantCulture); }
static int[] Ints(string text) { return text.Length==0 ? new int[0] : text.Split(',').Select(I).ToArray(); }
static string[] Words(string text) { return text.Length==0 ? new string[0] : text.Split(','); }
static string Snapshot(object value) { if (value==null) return "<null>"; if (value is string) return (string)value; var sequence=value as System.Collections.IEnumerable; if (sequence!=null) { var items=new List<string>(); foreach (object item in sequence) items.Add(Snapshot(item)); return string.Join("|",items); } return Convert.ToString(value,CultureInfo.InvariantCulture); }
public static void Main() {
System.Threading.Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
var rows = new List<string>(); string line; while ((line=Console.ReadLine()) != null) rows.Add(line);
string[] input=rows.ToArray();
var a0 = Ints(input[0]); string before0=Snapshot(a0);
var result = Exercise.Solve(a0);
if (Snapshot(a0) != before0) throw new Exception("Input mutation");
Console.WriteLine(result);
}
}
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
Python 개발자를 위한 C#의 모든 레슨
1여기서 시작하기
첫 C# 프로그램 실행하기직접 연습해 보세요: 온라인 C# 컴파일러