반복문: for, while, do-while
반복문은 같은 블록을 여러 번 실행합니다. for는 횟수가 정해져 있을 때, while은 조건이 거짓이 될 때까지, do-while은 본문을 최소 한 번은 실행합니다.
반복문: for, while, do-while이란?
반복문은 같은 블록을 여러 번 실행합니다. for는 횟수가 정해져 있을 때, while은 조건이 거짓이 될 때까지, do-while은 본문을 최소 한 번은 실행합니다.
for, while, do-while 반복문과 break, continue로 작업을 반복합니다.
중요한 점
- Compiler warning을 켜고 모두 해결하세요.
- 각 값의 type과 lifetime을 파악하세요.
- 입력과 배열 경계를 검증하세요.
동작 원리 보기
한 단계를 누르면 반복문이 한 걸음씩 실행됩니다. 조건 확인, 본문 실행, 추적 표가 한 줄씩 늘어나는 모습을 보세요.
C와 C++ 코드 예제
C
main.c
#include <stdio.h>
int main(void) {
/* for: start; condition; step */
for (int i = 1; i <= 5; i++) {
printf("%d ", i);
}
printf("\n");
/* while: repeat as long as the condition holds */
int n = 20;
int steps = 0;
while (n > 1) {
n /= 2;
steps++;
}
printf("halved %d times\n", steps);
/* do-while: the body runs at least once */
int tries = 0;
do {
tries++;
} while (tries < 3);
printf("tries = %d\n", tries);
/* break leaves the loop, continue skips to the next round */
for (int i = 1; i <= 10; i++) {
if (i % 2 == 0) continue;
if (i > 7) break;
printf("%d ", i);
}
printf("\n");
return 0;
}
1 2 3 4 5
halved 4 times
tries = 3
1 3 5 7
C++
main.cpp
#include <iostream>
#include <vector>
int main() {
// for: start; condition; step
for (int i = 1; i <= 5; i++) {
std::cout << i << ' ';
}
std::cout << '\n';
// while: repeat as long as the condition holds
int n = 20;
int steps = 0;
while (n > 1) {
n /= 2;
steps++;
}
std::cout << "halved " << steps << " times\n";
// do-while: the body runs at least once
int tries = 0;
do {
tries++;
} while (tries < 3);
std::cout << "tries = " << tries << '\n';
// range-based for visits every element of a container
std::vector<int> values{1, 3, 5, 7};
int sum = 0;
for (int value : values) {
sum += value;
}
std::cout << "sum = " << sum << '\n';
}
1 2 3 4 5
halved 4 times
tries = 3
sum = 16
C와 C++ 비교
for의 머리에는 시작값, 조건, 증감이 들어갑니다. break는 반복을 일찍 끝내고 continue는 다음 회차로 넘어갑니다. C++에는 인덱스 없이 컨테이너의 모든 원소를 도는 범위 기반 for가 있습니다.
C
C는 작은 절차형 API와 표현 세부 사항을 드러냅니다.
C++
C++는 저수준 모델을 유지하며 더 안전한 타입을 추가합니다.
연습 문제
두 버전을 실행하고 수정하여 각 언어의 보장을 관찰하세요.
- 잘못된 입력과 경계값을 추가하세요.
- -Wall -Wextra -Wpedantic으로 컴파일하세요.
- 선언과 구현을 분리하세요.
챌린지로 연습하기
이 레슨에서 배운 내용으로 실제 문제를 풀어 보세요. 모든 챌린지는 브라우저에서 실행되며 즉시 테스트와 AI 리뷰를 받을 수 있습니다.
- Sum of Odd Numbers Add every odd number up to a limit. 쉬움
- Countdown to Liftoff Count down from a number and end with Liftoff! 쉬움
- Multiplication Table Row List the first multiples of a number. 쉬움