Loops and Iteration
Loops repeat a block of statements while an index or condition changes. They turn “read n values” or “visit every candidate” into code of fixed length. This lesson combines a for loop that consumes input, a while loop that counts decimal digits, and a do-while countdown. The focus is proving what changes each iteration and why the loop stops, not memorizing punctuation.
Prerequisites: Conditional Statements.
Build the idea
1. Count input with a for loop
for(int i=0; i<n; ++i) starts at zero, checks before each iteration, then increments afterwards. For n=5, indices are 0,1,2,3,4: exactly five iterations. We read one number every time. continue skips the rest of the current body but still executes the for-loop increment. The example adds only nonnegative values while consuming all n input numbers.
2. Do not confuse skipping and stopping
A negative value triggers continue, so later values are still read. break instead exits the nearest loop entirely. Use break when a requested answer has already been found or a sentinel ends the task; do not break from a fixed-length input section unless the rest of the program handles the unread values. Both keywords affect the nearest enclosing loop, not every nested loop.
3. Control a while loop with a decreasing quantity
To count digits of the nonnegative sum, repeatedly divide a copy by 10 while it is at least 10. digits starts at 1 so zero correctly has one digit. The copy decreases whenever the loop executes, proving termination. If you forget the division, the same condition can remain true forever. The original sum is preserved for output.
4. Understand the first do-while iteration
A do-while checks its condition after the body, guaranteeing one execution. The example counts 3,2,1, then decrements to zero and stops. This differs from a while loop whose condition may be false initially. A semicolon is required after while(condition) in a do-while statement, unlike the beginning of an ordinary while body.
5. Estimate nested loops
Two loops each running n times normally execute n² body iterations; their costs multiply, not add. A triangular inner loop j<i executes n(n−1)/2 iterations, still quadratic. Loops one after another add costs. Our loops are sequential: n reads, a short digit loop and three countdown steps. For sample values 4,−2,7,0,−1 the sum is 11; it has two decimal digits.
C++17 implementation
This is a complete program. Compile with C++17 and enter the input described below.
#include<iostream>
int main(){
int n;
std::cin>>n;
long long sum=0;
for(int i=0;i<n;++i){
long long x;
std::cin>>x;
if(x<0){
continue; // Skip this contribution, not the remaining input.
}
sum+=x;
}
long long copy=sum;
int digits=1;
while(copy>=10){
copy/=10;
++digits;
}
std::cout<<sum<<' '<<digits<<'\n';
int countdown=3;
do{
std::cout<<countdown<<(countdown==1?'\n':' ');
--countdown;
}
while(countdown>0);
}
Complexity analysis
O(n+log(S+1)) time if considering the decimal digit count of sum S, and O(1) space. With bounded long long, the digit loop has a small fixed maximum; input processing dominates as O(n). Nested loops are discussed separately and are not present in this implementation.
Example input and output
Read n (0..100000), then n integers with absolute value≤10^9. Print the sum of nonnegative values and its digit count, then the fixed countdown 3 2 1.
Input
5 4 -2 7 0 -1
Output
11 2 3 2 1
Only 4,7,0 contribute; 11 has two digits. The do-while demonstrates three executions.
Practical applications
Use for when iterating a known count or index range, while for a condition-driven process, and do-while when one execution is mandatory. Traversals, enumeration and repeated test cases all use these tools. Before optimizing a loop, verify its invariant and termination condition.
Check your understanding
How many times does for(int i=0;i<n;++i) execute for n=0?
Put it into practice
Change the filter to sum only even values, including negative even values.
Show a hint
Replace the continue condition; test x%2!=0 to reject odd numbers.