Menu
CoddyTech

횟수가 정해진 반복

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

C#의 foreach는 일반적으로 쓰기 가능한 슬롯 별칭 없이 요소를 읽습니다. C++의 range-for는 명시적인 가변 참조에 바인딩할 수 있습니다. C++의 range-for는 요소를 순회합니다. 참조 루프 변수는 요소를 수정할 수 있고, 값 루프 변수는 각 요소를 복사합니다.

C#

using System;
using System.Collections.Generic;
using System.Linq;
class Program {

  static void Main() {
    int total=0; foreach(int n in new[]{2,4}) total+=n; Console.WriteLine(total);
  }
}

C++

#include <iostream>
#include <string>
#include <vector>
#include <array>
#include <map>
#include <set>
#include <algorithm>
#include <memory>
#include <sstream>
#include <stdexcept>
#include <utility>

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

각 프로그램을 독립적으로 추적하세요. 이 예제들은 과제와 다른 연산이나 데이터를 사용해 개념을 보여 줍니다. 소스와 대상의 출력이 일치한다고 가정하지 않습니다.

challenge icon

챌린지

쉬움

입력: 음이 아닌 n. 1부터 n까지의 정수 합을 반환하세요. n은 최대 1000입니다.

exercise.hpp와 exercise.cpp에 선언된 API를 구현하세요. 두 파일은 모두 편집할 수 있습니다. 공개 시그니처는 그대로 유지하세요. 잠긴 main.cpp는 stdin을 읽고 API를 직접 호출합니다. 또한 명시된 경우 공개 API 동작을 독립적으로 확인합니다. API 안에서 출력하지 말고 반환값을 사용하세요. 정수 입력과 결과는 부호 있는 int에 들어가며, 별도로 명시되지 않는 한 텍스트는 ASCII입니다.

직접 해보기

#include "exercise.hpp"
#include <iostream>
int main(){

std::vector<std::string> rows; std::string line; while(std::getline(std::cin,line)) rows.push_back(line);
std::istringstream in(rows.empty()?"":rows[0]);int n;in>>n;std::cout<<triangle(n)<<"\n";
}
quiz icon실력 점검

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

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

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