easyBasics 0 views

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

LanguageSyntax
Javafor (int i = 0; i < n; i++) { ... }
C#for (int i = 0; i < n; i++) { ... }
Pythonfor i in range(n): ... (no C-style for loop at all)
JavaScript / TypeScriptfor (let i = 0; i < n; i++) { ... }

Iterating a collection directly

LanguageSyntax
Javafor (int x : arr) { ... }
C#foreach (var x in arr) { ... }
Pythonfor x in arr: ...
JavaScript / TypeScriptfor (const x of arr) { ... }not for...in, which iterates indices/keys, not values

While loops

LanguageSyntax
Java / C# / JavaScript / TypeScriptwhile (condition) { ... }
Pythonwhile condition: ...

If / else

LanguageSyntax
Java / C# / JavaScript / TypeScriptif (cond) { ... } else if (cond2) { ... } else { ... }
Pythonif cond:\n ...\nelif cond2:\n ...\nelse:\n ...elif, not else if

Ternary (conditional expression)

LanguageSyntax
Java / C# / JavaScript / TypeScriptcond ? valueIfTrue : valueIfFalse
PythonvalueIfTrue if cond else valueIfFalse — order is reversed from the others

Switch / match

LanguageSyntax
Javaswitch (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
Pythonmatch x: case 1: ... case _: ... (Python 3.10+) — no fallthrough; older Python has no switch at all, use if/elif chains
JavaScript / TypeScriptswitch (x) { case 1: ...; break; default: ...; } — falls through like Java

Loop control

Want to...Java / C# / JS / TSPython
Exit the loop entirelybreakbreak
Skip to the next iterationcontinuecontinue

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.