선택 및 반복 구현하기
도입됨
7:49
선택 및 반복
세 개의 루프가 있습니다. 첫 번째와 두 번째는 한 문자의 차이, 즉 ‘보다 작다’와 ‘보다 작거나 같다’의 차이입니다. 첫 번째는 열 번 실행되고, 두 번째는 열 한 번 실행됩니다.
영어 내레이션 · 영어와 중국어 자막 전환 가능
이 수업의 내용
| English | 의미 |
|---|---|
| accumulator/əˈkjuːmjʊleɪtə/ | 누적기 |
A zero initial maximum invents a result
- An array contains −8, −3 and −11. Starting max at zero leaves a maximum that was never in the array.
- For this nonempty array, start max at a[0]. Comparing the later values updates −8 to −3 and keeps it there.
![A zero initial maximum invents a result: for the array −8, −3, −11, starting max at 0 returns 0, a value never in the array; starting at a[0] gives −8, then −3, which stays; an empty array needs a separate check](/learn-media/ap_computer_science_a/assets/0209-max-start.png?v=1794225445)

Loop patterns: accumulate
- A loop pattern is a reusable recipe for a common task. The accumulator 累加器 pattern builds a running total or product across iterations.
- Start
sum = 0, thensum = sum + xinside the loop; the running total changes; it can decrease when a negative value is added. Same idea for a running count (count++) or a running max.
Conditionals inside loops
- Put an
ifinside a loop to act only on items that match. "Count the even numbers": loop, andif (x % 2 == 0) count++; - The loop visits every item; the
ifdecides which ones to process. Combining selection and repetition is the heart of most algorithms.
Finding a maximum
- To find the largest value, keep a
maxvariable and update it when you see something bigger. Check the array is nonempty, startmaxat its first value, then examine the rest. An unspecified “very small number” can still exceed every actual input. if (x > max) { max = x; }inside the loop. After the loop,maxholds the largest value seen.
accumulator 패턴
sum이 반복을 걸쳐 누적됩니다; 0에서 시작합니다.
루프 내에서Running SUM을 만들려면 accumulator를 ...으로 초기화해야 합니다.
난이도 1/5 · 100코인 + 오늘 첫 완료 시 작은 보너스 추가
합계는 0에서 시작하고, 곱은 1에서 시작해야 합니다.
Running PRODUCT를 만들려면 accumulator를 ...으로 초기화해야 합니다.
난이도 1/5 · 100코인 + 오늘 첫 완료 시 작은 보너스 추가
0에서 시작하면 곱은 항상 0이 되므로, 1에서 시작해야 합니다.
루프 중 짝수를 세려면 ...을 사용합니다.
난이도 1/5 · 100코인 + 오늘 첫 완료 시 작은 보너스 추가
if가 루프가 세는 항목을 선택합니다.
accumulator의 초기화를 루프 안에 두면 매 반복마다 초기화되어 리셋됩니다.
난이도 1/5 · 100코인 + 오늘 첫 완료 시 작은 보너스 추가
루프 내부가 아닌, 루프 전에 초기화해야 합니다.
목표를 찾으면 즉시 루프를 멈추려면 ...을 사용할 수 있습니다.
난이도 1/5 · 100코인 + 오늘 첫 완료 시 작은 보너스 추가
break문은 가장 안쪽 루프에서 탈출합니다. 부울 플래그도 루프 조건이나 제어 논리에서 사용되어야 하며, 단순히 할당만으로는 실행이 중단되지 않습니다.
Early exit with a flag or break
- Sometimes you can stop early once you've found what you need. A
booleanflag can record “found it” and be checked by the loop condition; assigning the flag alone does not exit a loop.breakexits the innermost loop immediately. - "Does the list contain a zero?" — stop at the first zero. Early exit saves work but keep the logic correct for the "not found" case.
Initialize the accumulator correctly, or every result is off. A sum starts at 0, a product at 1 (starting a product at 0 makes it always 0), a max at the first element after a nonempty check. An empty collection has no maximum unless the contract explicitly defines a separate outcome. And update it every matching iteration — a misplaced initialization inside the loop resets it each pass and ruins the total.
What is the maximum of the nonempty array {−8, −3, −11}?
난이도 2/5 · 140코인 + 오늘 첫 완료 시 작은 보너스 추가
−3 is the greatest actual element. Starting at 0 produces an invalid invented candidate.
a[0]를 읽는 것은 빈 배열의 최대값을 초기화하는 유효한 방법입니다.
난이도 1/5 · 100코인 + 오늘 첫 완료 시 작은 보너스 추가
빈 배열에는 첫 번째 요소가 없습니다. 입력을 확인하거나 별도의 '최대값 없음' 결과 설정을 정의하십시오.
int 배열 {-8, -3, -11}에는 짝수가 몇 개 있습니까?
난이도 2/5 · 140코인 + 오늘 첫 완료 시 작은 보너스 추가
-8만 2로 나눈 나머지가 0이며, 음수는even(짝수)일 수 있습니다.
Counting evens in a loop over an array a:
int count = 0;for (int i = 0; i < a.length; i++) { if (a[i] % 2 == 0) count++; }- The loop visits each element; the
ifcounts only the even ones.
Carry the reasoning to a new case
- An empty array has no first element and needs a separate contract or check.
- The initial value must suit the operation: sum zero, product one, maximum a valid starting candidate.
Common loop patterns combine iteration and selection: an accumulator (sum += x, count, or running max) built across passes, with an if inside to process only matching items. Initialize the accumulator right (sum 0, product 1, max the first value), and consider an early exit (break/flag) once the answer is found.
어떤 문제가 있었나요? 사이트 팀만 이 내용을 볼 수 있습니다.