Programming Fundamentals and Logic Building
Core constructs
- Variables hold values of a type: int, float/double, char, boolean, String. Java requires the type to be declared; Python infers it.
- Operators: + − * / , % (remainder), ** or Math.pow for powers, // in Python for floor division. = assigns, == compares.
- Decision: if / else if / else. In Python indentation defines the block; in Java braces do, and every statement ends with a semicolon.
- Loops: for (counted), while (condition tested first), do-while (Java only, runs at least once). break exits the loop; continue skips to the next iteration.
- Arrays: Python list marks = [45, 67, 89], read marks[0]; Java int[] marks = new int[3], read marks[0]. Indexing starts at 0 and the last index is length − 1.
Worked example
Find the largest of [12, 45, 7]. Start with largest = arr[0] = 12. Compare arr[1] = 45 > 12 → largest = 45. Compare arr[2] = 7 > 45 → false, so largest stays 45. Output 45. Reasoning: initialising largest as 0 instead of arr[0] gives the wrong answer for an all-negative array, because no element is greater than 0.
Traps
Off-by-one loops: range(1, 5) produces 1, 2, 3, 4 - not 5. Integer division: 7/2 gives 3 with Java ints and with Python //, but 3.5 with /. Array index out of bounds at index = length. A missing increment inside while causes an infinite loop. Writing = where == was meant turns a comparison into an assignment.