How Loops & Conditionals Work — Syntax Cheat Sheet
No exercise here — for/while/switch syntax side by side across Java, C#, Python, and JavaScript/TypeScript, for when you're rusty in a language you don't use daily.
This is a reference page, not a graded exercise. If you're solid in one language but the interview is in another, this is the syntax that trips people up under pressure — not the algorithm.
For loops
| Language | Syntax |
|---|---|
| Java | for (int i = 0; i < n; i++) { ... } |
| C# | for (int i = 0; i < n; i++) { ... } |
| Python | for i in range(n): ... (no C-style for loop at all) |
| JavaScript / TypeScript | for (let i = 0; i < n; i++) { ... } |
Iterating a collection directly
| Language | Syntax |
|---|---|
| Java | for (int x : arr) { ... } |
| C# | foreach (var x in arr) { ... } |
| Python | for x in arr: ... |
| JavaScript / TypeScript | for (const x of arr) { ... } — not for...in, which iterates indices/keys, not values |
While loops
| Language | Syntax |
|---|---|
| Java / C# / JavaScript / TypeScript | while (condition) { ... } |
| Python | while condition: ... |
If / else
| Language | Syntax |
|---|---|
| Java / C# / JavaScript / TypeScript | if (cond) { ... } else if (cond2) { ... } else { ... } |
| Python | if cond:\n ...\nelif cond2:\n ...\nelse:\n ... — elif, not else if |
Ternary (conditional expression)
| Language | Syntax |
|---|---|
| Java / C# / JavaScript / TypeScript | cond ? valueIfTrue : valueIfFalse |
| Python | valueIfTrue if cond else valueIfFalse — order is reversed from the others |
Switch / match
| Language | Syntax |
|---|---|
| Java | switch (x) { case 1: ...; break; default: ...; } — falls through without break |
| C# | switch (x) { case 1: ...; break; default: ...; } — falls through is a compile error unless the case is empty |
| Python | match x: case 1: ... case _: ... (Python 3.10+) — no fallthrough; older Python has no switch at all, use if/elif chains |
| JavaScript / TypeScript | switch (x) { case 1: ...; break; default: ...; } — falls through like Java |
Loop control
| Want to... | Java / C# / JS / TS | Python |
|---|---|---|
| Exit the loop entirely | break | break |
| Skip to the next iteration | continue | continue |
The gotcha that costs the most time: forgetting break in a Java/JS switch and silently falling into the next case — this compiles and runs, it just does the wrong thing. And in Python, indentation is the block syntax — a misplaced or missing indent is a syntax error, not just a style nit, and mixing tabs and spaces will crash your program.
Hints
Companies
No companies reported yet.
Discussion
Sign in to join the discussion.
Loading discussion...
Test results
This question doesn't have a code exercise.