Reading — step 1 of 5
Learn
Loops and Iteration
TypeScript has every JavaScript loop, with type inference riding along — loop variables get their types for free.
The classic for loop
for (let i = 0; i < 5; i++) {
console.log(i); // 0 1 2 3 4
}
Three clauses: initialize (let i = 0), keep-going-while (i < 5), step (i++). i is inferred as number; annotating it (let i: number = 0) is legal but unnecessary noise.
while
let n = 10;
while (n > 0) {
n = Math.floor(n / 2);
}
Reach for while when you do not know the number of iterations up front.
for...of — values (what you usually want)
const nums: number[] = [10, 20, 30];
for (const v of nums) {
console.log(v); // 10, 20, 30 — v is inferred as number
}
for...in — keys (the trap)
for...in iterates KEYS, and for arrays those keys are strings ("0", "1", "2"):
for (const k in nums) {
console.log(k); // "0", "1", "2" — string indices, not values!
// k + 1 is "01" — string concatenation, not arithmetic
}
Rule of thumb: for...of for arrays; for...in only for plain-object keys (and even then Object.keys() is usually cleaner). Need the index AND the value? Use .entries() and destructure:
for (const [i, v] of nums.entries()) {
console.log(i, v);
}
Method-style iteration
nums.forEach((v, i) => console.log(i, v));
forEach passes (element, index) to your callback. It is fine for side effects like printing; the transforming cousins map / filter / reduce get their own lesson later.
Accumulating: the sum pattern
The bread-and-butter loop shape — start an accumulator at zero, fold each element in:
let sum: number = 0;
for (let i = 1; i <= n; i++) {
sum += i;
}
console.log(sum);
The trap: off-by-one boundaries
The single most common loop bug in existence. To sum 1 through N you must INCLUDE N, so the condition is i <= n:
for (let i = 1; i < n; i++) { sum += i; } // WRONG — stops at n-1
for (let i = 1; i <= n; i++) { sum += i; } // right — includes n
For n = 5 the wrong version computes 1+2+3+4 = 10; the right one computes 15. Every time you write a loop, ask: "does my last intended iteration actually run?"
(Sanity-check trick: Gauss's formula n * (n + 1) / 2 computes the same sum with no loop — for 100 it gives 5050. If your loop disagrees, the loop is wrong.)
Your exercise
The starter reads one positive integer and declares the accumulator:
const n: number = Number(require('fs').readFileSync(0, 'utf-8').trim());
let sum: number = 0;
Loop from 1 to N inclusive, add each value to sum, then print it with console.log(sum).
The exact mistake the grader will catch is the off-by-one: writing i < n instead of i <= n prints 10 for input 5, but the test expects 15 (and 5050 for the hidden input 100). Print only the final sum — no Sum: prefix, no intermediate values.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…