From the free course Java Programming and Algorithmic Thinking Fundamentals on Lykke
Logic and Control Flow
Key concepts: Conditional Statements (if-else, else-if) · Iterative Loops (while and for) · Boolean Logic · Relational Operators · Nested Control Structures
Exploration of conditional branching and iterative processes to control program execution.
Logic and Control Flow
In the realm of computational theory, a program is more than a linear sequence of instructions; it is a dynamic entity capable of responding to varying inputs and environmental states. Control Flow refers to the order in which individual statements, instructions, or function calls are executed or evaluated. Without control flow, a program would be a static script, executing from top to bottom and terminating regardless of the data it encounters. By implementing Logic and Control Flow, we introduce the "nervous system" of the software, allowing for decision-making (branching) and repetition (iteration).
Boolean Logic and Relational Operators
At the core of every control flow decision lies Boolean Logic, a branch of algebra in which the values of the variables are the truth values true and false. In Java and most C-style languages, these decisions are driven by predicates—expressions that evaluate to a boolean result.
Relational Operators
Relational operators are the primary tools used to compare primitive data types. They establish a relationship between two operands and return a boolean value based on the validity of that relationship.
| Operator | Description | Example (a=5, b=10) |
Result |
|---|---|---|---|
== |
Equal to | a == b |
false |
!= |
Not equal to | a != b |
true |
> |
Greater than | a > b |
false |
< |
Less than | a < b |
true |
>= |
Greater than or equal to | a >= 5 |
true |
<= |
Less than or equal to | b <= 10 |
true |
Logical Operators
To handle complex decision-making, we combine simple relational expressions using Logical Operators. These follow the laws of Boolean Algebra, specifically conjunction, disjunction, and negation.
- AND (
&&): Returnstrueonly if both operands aretrue. - OR (
||): Returnstrueif at least one operand istrue. - NOT (
!): A unary operator that inverts the boolean value.
The Principle of Short-Circuit Evaluation: In Java, the
&&and||operators exhibit "short-circuit" behavior. Fora && b, ifaisfalse, the system does not evaluatebbecause the entire expression cannot possibly betrue. Similarly, fora || b, ifaistrue,bis skipped. This is critical for preventing errors, such as checking if an object is null before accessing its members:if (list != null && list.length > 0).
Truth Tables
Truth tables serve as the formal proof for logical operations. They define the output for every possible combination of inputs.
| P | Q | P && Q (AND) | P || Q (OR) | !P (NOT) |
| :--- | :--- | :--- | :--- | :--- |
| true | true | true | true | false |
| true | false | false | true | false |
| false | true | false | true | true |
| false | false | false | false | true |
Conditional Statements (if-else, else-if)
Conditional Statements are the fundamental branching mechanism in programming. They allow the execution path to diverge based on the evaluation of a boolean predicate.
The if and else Mechanics
The if statement evaluates a condition. If the condition is true, the subsequent block of code executes. If an else block is provided, it serves as the "catch-all" for when the condition is false.
// Basic conditional logic for error handling
if (b == 0) {
System.out.println("Error: Division by zero is undefined.");
} else {
int quot = a / b;
System.out.println("Result: " + quot);
}
Multi-way Branching with else if
When a problem requires more than two possible outcomes, we use the else if ladder. This structure ensures that only one block of code in the chain is executed—the first one whose condition evaluates to true.
Worked Example: The Leap Year Algorithm
A year is a leap year if it is divisible by 4, unless it is divisible by 100, in which case it must also be divisible by 400. This logic requires a combination of relational operators and logical nesting.
public class LeapYear {
public static void main(String[] args) {
int year = Integer.parseInt(args[0]);
boolean isLeapYear;
// Divisible by 4 AND (not divisible by 100 OR divisible by 400)
isLeapYear = (year % 4 == 0);
isLeapYear = isLeapYear && (year % 100 != 0);
isLeapYear = isLeapYear || (year % 400 == 0);
if (isLeapYear) {
System.out.println(year + " is a leap year.");
} else {
System.out.println(year + " is not a leap year.");
}
}
}
Common Pitfalls in Conditionals
- The Dangling Else: In nested
ifstatements without braces, anelsealways associates with the closest precedingif. Always use curly braces{}to avoid ambiguity. - Assignment vs. Equality: Using
=(assignment) instead of==(equality) inside a condition is a frequent source of logic errors. - Redundant Logic: Writing
if (condition == true)is unnecessary;if (condition)is sufficient and cleaner.
Iterative Loops (while and for)
Iteration allows a program to execute a block of code multiple times. This is the cornerstone of processing large datasets, such as arrays, or performing simulations.
The while Loop
The while loop is an entry-condition loop. It checks the condition before executing the loop body. If the condition is initially false, the body never executes.
Syntax:
while (condition) {
// statements to repeat
}
The for Loop
The for loop is a specialized iteration structure designed for cases where the number of iterations is known or follows a specific counter-based pattern. It encapsulates initialization, condition, and increment/update in a single line.
Syntax:
for (initialization; condition; increment) {
// statements to repeat
}
Comparison of Iterative Structures
| Feature | while Loop |
for Loop |
|---|---|---|
| Best Use Case | When the number of iterations is unknown (e.g., reading until end of file). | When iterating over a range or a collection (e.g., arrays). |
| Readability | Can become cluttered if counters are managed manually. | Highly readable; counter logic is localized. |
| Termination | Relies on a state change within the loop body. | Relies on a counter reaching a limit. |
| Risk | High risk of infinite loops if the condition is never met. | Lower risk of infinite loops, but "off-by-one" errors are common. |
Worked Example: Summing an Array
Using a for loop to traverse an array and accumulate a total is a foundational pattern in software engineering.
public class ArraySum {
public static void main(String[] args) {
// Assume args contains integers passed via command line
int[] nums = new int[args.length];
int sum = 0;
// Parsing and Populating
for (int i = 0; i < args.length; i++) {
nums[i] = Integer.parseInt(args[i]);
}
// Accumulation Loop
for (int i = 0; i < nums.length; i++) {
sum += nums[i]; // sum = sum + nums[i]
}
System.out.println("The total sum is: " + sum);
}
}
Nested Control Structures
Real-world logic often requires Nesting—placing one control structure inside another. This allows for the representation of multi-dimensional data and complex decision trees.
Nested if Statements
Nested conditionals are used to refine decisions. For example, in the "cats" example from the source materials, we first check if the input is valid (non-negative), and then perform further checks on the total sum.
if (anaCats < 0 || ellenCats < 0) {
System.out.println("Can't have negative cats.");
} else {
int totalCats = anaCats + ellenCats;
if (totalCats > 20) {
System.out.println("You might need a mansion.");
} else if (totalCats > 10) {
System.out.println("You might need a bigger house!");
}
}
Nested Loops and Complexity
Nested loops are frequently used to process 2D grids or compare every element in a list with every other element. However, engineers must be wary of Computational Complexity. A loop running $n$ times inside another loop running $n$ times results in $O(n^2)$ complexity.
// Printing a multiplication table
for (int i = 1; i <= 10; i++) {
for (int j = 1; j <= 10; j++) {
System.out.print((i * j) + "\t");
}
System.out.println(); // New line after each row
}
Advanced Patterns in Logic
Variable Swapping
Swapping the values of two variables is a classic operation that requires a temporary storage location to prevent data loss.
int a = 10;
int b = 20;
int temp = a; // temp = 10
a = b; // a = 20
b = temp; // b = 10
Accumulators and Flags
- Accumulator: A variable (like
sumorcount) that is updated during each iteration of a loop to gather a final result. - Flag: A boolean variable used to signal that a certain condition has been met (e.g.,
boolean found = false;). Once the target is located in a loop, the flag is set totrue.
Sentinel Values
A Sentinel Value is a special value used to terminate a loop. For instance, if reading a list of positive test scores, a user might enter -1 to signal they are finished. The loop condition would be while (score != -1).
Standard Libraries and I/O Integration
Control flow is often driven by external data. Java's standard libraries, such as StdIn and StdOut, provide streamlined methods for integrating user input into logic structures.
StdIn.readInt(): Reads the next integer from standard input, allowing loops to process data dynamically.StdIn.isEmpty(): A boolean method that returnstruewhen there is no more data to read. This is the idiomatic way to write awhileloop for data processing.
// Reading until the end of input
while (!StdIn.isEmpty()) {
double value = StdIn.readDouble();
// process value...
}
Summary of Best Practices
- Keep Conditions Simple: If a boolean expression is too complex, break it into smaller boolean variables with descriptive names.
- Avoid Deep Nesting: If you find yourself nesting four or five levels deep, consider refactoring your code into Methods to improve readability.
- Initialize Counters Correctly: Always double-check your loop boundaries. Remember that arrays in Java are 0-indexed, meaning a loop should typically run from
0tolength - 1. - Use Final Else: In an
if-else ifchain, always include a finalelseto handle unexpected cases or provide an error message.
| Concept | Primary Purpose | Key Operator/Keyword |
|---|---|---|
| Selection | Branching execution based on data. | if, else |
| Iteration | Repeating logic for efficiency. | for, while |
| Comparison | Evaluating relationships between values. | ==, !=, <, > |
| Combination | Merging multiple logical predicates. | &&, ` |

Source Materials
- Week 04 - 1 - Conditionals and Loops-FT.pdf
- Week 04 - 2 - Conditionals and Loops-FT.pdf
- Week 4 - Conditionals and Loops.pdf
- Week 04 - Conditionals and Loops-FT.pdf
- Week 4 - Conditionals and Loops.pdf
- 04-Conditionals and Loops.pdf
- Copy of Week 2 Recitation Slides – Algorithmic Thinking and Anaysis II (Loops).pdf
- Week 04 - 1 - Conditionals and Loops-FT.pdf
Study Java Programming and Algorithmic Thinking Fundamentals on Lykke
This course page is free to open: signed out, you can read its first two sections, and signing in, on any plan, opens the rest. The free Lykke Chrome extension syncs your own Canvas courses, so ChatGPT, Claude and Muse can answer from your classes and deadlines. It only reads Canvas.
Add the free extensionSign in to open every sectionAll sections of Java Programming and Algorithmic Thinking Fundamentals · Browse more course pages