Plus
$7.99 / month
- Nemotron Nano 12B VL
- Nemotron Nano 30B
- 20 AI credits/week
Save your current position in the course
Certificates are issued to Unlimited subscribers who finish a course. Your progress is saved either way — upgrade whenever you want yours.
Report a problem with this course via Discord
View available keyboard shortcuts
Reset all section and file completion progress
Imagine you are designing the software for a self-driving car. If the car only followed a single, linear set of instructions—"Drive forward for 10 miles, then stop"—it would be useless and dangerous. To navigate the real world, the software needs to make decisions: If a pedestrian is in the crosswalk, then apply the brakes. It also needs to perform repetitive tasks: While the battery level is above 5%, continue monitoring the GPS.
In computer science, these capabilities are known as Selection and Iteration. They are the fundamental structures that transform a simple calculator into a powerful, intelligent system. In Unit 1, we learned about variables and basic operations (Sequencing). In this unit, we introduce the "brain" of the program. We will explore how Boolean logic allows a program to branch into different paths and how loops allow a program to repeat complex calculations millions of times per second. By the end of this chapter, you will move from writing simple scripts to developing robust algorithms capable of solving complex mathematical and data-processing problems.
Boolean Value: A data type that can only be either true or false.
Relational Operators: Used to compare two values.
| Operator | Description | Example ($a=5, b=10$) | Result |
|---|---|---|---|
== |
Equal to | $a == b$ | false |
!= |
Not equal to | $a != b$ | true |
< |
Less than | $a < b$ | true |
<= |
Less than or equal to | $a <= b$ | true |
> |
Greater than | $a > b$ | false |
>= |
Greater than or equal to | $a >= b$ | false |
Logical Operators: Used to combine multiple Boolean expressions.
&& (AND): True if both operands are true.|| (OR): True if at least one operand is true.! (NOT): Reverses the Boolean value.Every computer program, regardless of complexity, is built from three building blocks:
The order and combination of these blocks define the algorithm. For example, to find the largest number in a list, you use sequencing to start at the beginning, repetition to look at every number, and selection to compare the current number with the largest one found so far.
A Boolean expression is any expression that evaluates to true or false.
int, double, or char, Java compares the actual values.== or != with Objects (like String), Java compares the memory addresses (references), not the content. Two Strings can both contain "Hello" but exist at different memory locations, making str1 == str2 evaluate to false.The if statement is the most basic form of selection.
if (boolean_expression) {
// executes if true
}
The if-else provides an alternative path:
if (score >= 60) {
System.out.println("Pass");
} else {
System.out.println("Fail");
}
Exactly one branch will execute in an if-else structure.
Nesting allows for complex logic. A multi-way selection (else-if) ensures that only the first true condition is executed.
$$ \text{If } C_1 \text{ is true, execute } B_1. \text{ Else if } C_2 \text{ is true, execute } B_2. \dots \text{ Else execute } B_{default}. $$
Once a condition is met, the rest of the ladder is skipped.
Logic operators follow a strict order of operations (Precedence):
()!*, /, %, then +, -)<, >, <=, >=)==, !=)&&||Short-circuit evaluation:
A && B: If A is false, the result must be false, so B is never evaluated.A || B: If A is true, the result must be true, so B is never evaluated.if (list != null && list.size() > 0) prevents a NullPointerException.Two expressions are equivalent if they yield the same result for all possible inputs. We use Truth Tables to prove this.
De Morgan’s Laws:
!(A && B) is equivalent to !A || !B!(A || B) is equivalent to !A && !BTo negate a complex expression, negate each individual term and flip the operator ($&& \leftrightarrow ||$, $< \leftrightarrow \ge$, $== \leftrightarrow !=$).
The while loop is used when the number of iterations is not known beforehand.
while (condition) {
// loop body
}
If the condition is false initially, the body executes zero times. If the condition never becomes false, an infinite loop occurs.
The for loop is specialized for counting.
for (initialization; condition; update) {
// body
}
Any for loop can be written as a while loop:
int i = 0; // Initialization
while (i < n) { // Condition
// body
i++; // Update
}
n % d == 0 means $n$ is divisible by $d$.num % 10num / 10max to a very small value or the first element, then update if a larger one is found.Since Strings are immutable, we use substring() and length() to process them.
for (int i = 0; i < str.length(); i++) {
String letter = str.substring(i, i + 1);
}
When a loop is inside another, the inner loop completes all its cycles for every one cycle of the outer loop.
Total executions of the inner-most statement = $(\text{Outer Iterations}) \times (\text{Inner Iterations})$.
In AP CSA, we count how many times a statement executes.
Determine if a student passed based on a grade.
int grade = 85;
if (grade >= 65) {
System.out.println("Passed");
}
Logic: Since $85 \ge 65$ is true, "Passed" is printed.
Using the modulo operator.
int num = 7;
if (num % 2 == 0) {
System.out.println("Even");
} else {
System.out.println("Odd");
}
Calculation: $7 \pmod 2 = 1$. $1 == 0$ is false. Output: "Odd".
Checking eligibility for a discount.
int age = 70;
boolean isMember = false;
if (age > 65) {
if (isMember) {
System.out.println("50% discount");
} else {
System.out.println("25% discount");
}
}
Logic: age > 65 is true. isMember is false. Output: "25% discount".
$A \text{ and } B$.
int temp = 25;
if (temp > 0 && temp < 100) {
System.out.println("Liquid");
}
Logic: $25 > 0$ (true) AND $25 < 100$ (true). Result: true.
int x = 0;
if (x != 0 && 10 / x > 1) {
System.out.println("Success");
}
Logic: x != 0 is false. Because of &&, the second part 10/x is never evaluated, avoiding a DivisionByZeroException.
int y = 10;
if (y > 5 || 10 / 0 == 1) {
System.out.println("True");
}
Logic: y > 5 is true. Because of ||, the second part (which would crash) is skipped. Output: "True".
Simplify !(x < 5 && y >= 10).
Step 1: Negate x < 5 $\rightarrow$ x >= 5.
Step 2: Negate y >= 10 $\rightarrow$ y < 10.
Step 3: Flip && to ||.
Result: (x >= 5 || y < 10).
String s1 = new String("AP");
String s2 = new String("AP");
System.out.println(s1 == s2); // false
System.out.println(s1.equals(s2)); // true
Note: == checks if they are the same object in memory. .equals() checks the characters.
Summing integers until 5.
int sum = 0;
int i = 1;
while (i <= 4) {
sum += i;
i++;
}
Trace:
int i = 10;
while (i > 0) {
System.out.println(i);
// i++ is missing or written as i++, leading to i always being > 0
}
for (int i = 5; i > 0; i--) {
System.out.print(i + " ");
}
Output: 5 4 3 2 1.
Calculate $\sum_{i=1}^{10} i$.
int sum = 0;
for (int i = 1; i <= 10; i++) {
sum += i;
}
Calculation: $\frac{n(n+1)}{2} = \frac{10(11)}{2} = 55$.
Reverse the digits of 123.
int n = 123;
int rev = 0;
while (n > 0) {
int d = n % 10;
rev = rev * 10 + d;
n = n / 10;
}
Trace:
d=3, rev=3, n=12d=2, rev=32, n=1d=1, rev=321, n=0How many times does '7' appear in 7172?
int n = 7172;
int count = 0;
while (n > 0) {
if (n % 10 == 7) count++;
n /= 10;
}
Result: count = 2.
Count 'a's in "banana".
String s = "banana";
int count = 0;
for (int i = 0; i < s.length(); i++) {
if (s.substring(i, i + 1).equals("a")) {
count++;
}
}
Result: 3.
Given a set of inputs (e.g., from a sensor).
int max = Integer.MIN_VALUE;
// Assume we have a loop reading values
if (currentVal > max) {
max = currentVal;
}
int sum = 0;
int count = 0;
for (int i = 1; i <= 5; i++) {
sum += i;
count++;
}
double avg = (double) sum / count;
Note: Must cast to double to avoid integer division: $15 / 5 = 3.0$.
String original = "Java";
String reversed = "";
for (int i = 0; i < original.length(); i++) {
reversed = original.substring(i, i+1) + reversed;
}
Trace:
J + "" = "J"a + "J" = "aJ"v + "aJ" = "vaJ"a + "vaJ" = "avaJ"for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
System.out.print("*");
}
System.out.println();
}
Output:
***
***
Analysis: Outer runs 2 times, Inner runs 3 times. Total stars = $2 \times 3 = 6$.
for (int i = 1; i <= 4; i++) {
for (int j = 1; j <= i; j++) {
System.out.print(j);
}
System.out.println();
}
Execution count: $1 + 2 + 3 + 4 = 10$ times.
Output:
1
12
123
1234
How many times does "th" appear in "the thistle"?
String s = "the thistle";
int count = 0;
for (int i = 0; i <= s.length() - 2; i++) {
if (s.substring(i, i + 2).equals("th")) {
count++;
}
}
Logic: Loop goes to length - 2 to prevent StringIndexOutOfBoundsException.
Find all factors of 12.
int n = 12;
for (int i = 1; i <= n; i++) {
if (n % i == 0) System.out.print(i + " ");
}
Output: 1 2 3 4 6 12 .
int input = 0;
int sum = 0;
// Hypothetical loop reading user input
while (input != -1) { // -1 is the sentinel
sum += input;
input = // read next value
}
Prove (A && B) is NOT the same as (A || B).
| A | B | A && B | A || B |
|---|---|--------|--------|
| T | T | T | T |
| T | F | F | T |
| F | T | F | T |
| F | F | F | F |
Since rows 2 and 3 differ, they are not equivalent.
int n = 7;
boolean isPrime = true;
for (int i = 2; i < n; i++) {
if (n % i == 0) isPrime = false;
}
Logic: If any number between 2 and $n-1$ divides $n$, it is not prime.
int count = 0;
for (int i = 0; i < N; i++) {
for (int j = 0; j < M; j++) {
count++;
}
}
Total count = $N \times M$.
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
for (int k = 0; k < n; k++) {
// statement
}
}
}
Total executions = $n \times n \times n = n^3$.
String s = "Java";
for (int i = 0; i <= s.length(); i++) {
System.out.println(s.substring(i, i+1));
}
Error: When i = s.length(), i+1 is out of bounds. The condition should be i < s.length().
String s = "education";
String result = "";
for (int i = 0; i < s.length(); i++) {
String c = s.substring(i, i + 1);
if (!(c.equals("a") || c.equals("e") || c.equals("i") || c.equals("o") || c.equals("u"))) {
result += c;
}
}
Result: "dctn".
int x = 15;
if (x > 10) {
System.out.print("A");
} else if (x > 5) {
System.out.print("B");
} else {
System.out.print("C");
}
Logic: Even though $15 > 5$ is true, only "A" prints because it was the first true condition.
Negate: (age >= 18 && hasID == true).
Result: !(age >= 18) || !(hasID == true) $\rightarrow$ (age < 18 || hasID == false).
int count = 0;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= i; j++) {
count++;
}
}
Analysis: This follows the arithmetic series $\sum_{i=1}^{n} i = \frac{n(n+1)}{2}$.
for (int i = 0; i < 10; i += 2) {
System.out.print(i + " ");
}
Output: 0 2 4 6 8 . (Skips every other number).
String str = null;
if (str != null && str.length() > 0) {
System.out.println("Valid String");
}
Logic: The first condition is false, so str.length() is not called, preventing a crash.
Find the index of the first 'x' in a string, or -1 if not found.
String s = "pixel";
int index = -1;
for (int i = 0; i < s.length(); i++) {
if (s.substring(i, i+1).equals("x")) {
index = i;
break; // In AP CSA, we usually use a boolean or check index == -1
}
}
Logic: This demonstrates searching and early termination concepts.
Right-click any tab and choose Split screen to view it here.
Course Mastery Certificates require an active Unlimited subscription at the time of generation and 100% course completion. They recognise learning content completion only — not an accredited qualification, licence, or professional credential unless explicitly stated. edusolum may modify eligibility, design, and issuance requirements per its Terms of Service.