Menu
CoddyTech

인덱스를 사용하는 for 반복문

Coddy의 C++ 개발자를 위한 C# 코스 레슨. 48개 중 14번째.

인덱스 기반 반복문 문법은 C++에서 익숙하지만, C# 배열 인덱싱은 범위를 벗어나면 예외를 발생시킵니다. C++에서 부호 있는 인덱스와 부호 없는 인덱스를 혼합하면 추가 버그가 생길 수 있으므로, 의도적으로 범위를 지정하고 size()를 적절한 C# Length 또는 Count 속성으로 바꾸세요.

for 반복문은 초기화, 불리언 조건, 업데이트를 결합합니다. 범위를 벗어나지 않도록 Length와 비교할 때 엄격한 미만 비교를 사용하세요. 반복문 변수는 선언된 범위 안에서만 존재합니다. 누적할 변수는 반복문 앞에 선언하세요.

C++ 참고 코드

#include <algorithm>
#include <array>
#include <cctype>
#include <functional>
#include <iomanip>
#include <iostream>
#include <map>
#include <memory>
#include <optional>
#include <set>
#include <sstream>
#include <stdexcept>
#include <string>
#include <vector>
using namespace std;

int main() {
int total=0;
for(int i=0;i<3;i++) total+=i;
cout << total << "\n";
}

Main 안의 C# 문장

int total = 0;
for (int i = 0; i < 3; i++) total += i;
Console.WriteLine(total);

이 내용은 특정 부분을 중점적으로 보여 주는 학습용 발췌문입니다. 과제 파일에는 실행에 필요한 전체 래퍼가 포함되어 있으며, 위 코드 조각은 관련 선언과 문장을 보여 줍니다.

참고 출력:

3

C# 출력:

3
challenge icon

챌린지

쉬움

쉼표로 구분된 정수 배열의 각 항목에 대해 인덱스 * 값의 가중 합을 반환하세요. 인덱스는 0부터 시작합니다. 입력이 비어 있으면 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);
}
}
quiz icon실력 점검

이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.

C++ 개발자를 위한 C#의 모든 레슨

직접 연습해 보세요: 온라인 C# 컴파일러