반복문의 경계와 진행
Coddy의 C++ 개발자를 위한 C 코스 레슨. 48개 중 10번째.
인덱스를 사용하는 C++ for 루프는 C로 직접 옮길 수 있습니다. C에는 범위 기반 for나 표준 반복자 컨테이너 프레임워크가 없으므로, 명시적인 경계와 포인터/길이 쌍이 그 역할을 대신합니다.
초기화, 경계, 갱신을 명시적으로 작성하세요. 유효한 마지막 인덱스는 배열 길이보다 작게 유지하세요.
C++ 예시
#include <iostream>
#include <iomanip>
#include <string>
#include <vector>
#include <array>
#include <map>
#include <memory>
#include <algorithm>
#include <functional>
#include <variant>
#include <sstream>
int main(){
int total=0;for(int i=1;i<4;i++)total+=i;std::cout<<total<<"\n";
}
C++ 출력:
6C 예시
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stddef.h>
#include <stdbool.h>
#include <limits.h>
#include <errno.h>
int main(void) {
int total=0;for(int i=1;i<4;i++)total+=i;printf("%d\n",total);
return 0;
}
C 출력:
6챌린지
쉬움입력 n은 0부터 100까지입니다. 1부터 n까지의 정수 합을 반환하세요.
잠금 해제된 소스 파일과 헤더 파일을 수정하세요. 표시된 잠금 상태의 main.c에서 함수를 직접 호출하므로, 선언된 공개 API와 호환되도록 유지하세요. 다른 main을 추가하지 마세요. 작업에서 범위를 명시적으로 검사하는 경우가 아니라면, 모든 숫자 작업 테스트 데이터는 오버플로가 발생하지 않을 만큼 작습니다. 지정된 출력만 출력하세요. 표시된 경우 드라이버가 입력 구문 분석과 출력을 담당합니다.
직접 해보기
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stddef.h>
#include <stdbool.h>
#include <limits.h>
#include <errno.h>
#include "lesson.h"
int main(void){int n=0;if(scanf("%d",&n)!=1)return 1;printf("%d\n",sum_to(n));return 0;}
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
C++ 개발자를 위한 C의 모든 레슨
직접 연습해 보세요: 온라인 C 컴파일러