Implementing Selection and Iteration Algorithms
Skill 2.ASkill 3.ASkill 4.A
Big idea: A handful of loop patterns (sum, count, min/max, digits, divisibility) solve most problems. Learn them as templates.
- Develop code for standard and original algorithms (without data structures) and determine the result of these algorithms.
Sum, count, and average
Codeint sum = 0;
int evens = 0;
for (int n = 1; n <= 10; n++) {
sum += n;
if (n % 2 == 0) {
evens++;
}
}
double avg = (double) sum / 10;
System.out.println(sum + " " + evens + " " + avg);Output55 5 5.5Minimum and maximum
Start the running max at the first value or at Integer.MIN_VALUE, never at 0, in case every value is negative.
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
for (int x = -8; x <= -2; x += 3) {
if (x > max) max = x;
if (x < min) min = x;
}
System.out.println(min + " " + max);Output-8 -2Divisibility and digits
Codeint n = 36;
int factors = 0;
for (int d = 1; d <= n; d++) {
if (n % d == 0) factors++;
}
System.out.println("36 has " + factors + " factors");
int num = 9045;
int reversed = 0;
while (num > 0) {
reversed = reversed * 10 + num % 10;
num /= 10;
}
System.out.println(reversed);Output36 has 9 factors 5409
Stop early with a flag
To check whether any value meets a condition, stop as soon as you find one. To check whether all do, stop as soon as one fails.
Codeint n = 91;
boolean prime = n > 1;
for (int d = 2; d * d <= n && prime; d++) {
if (n % d == 0) prime = false;
}
System.out.println(prime);Outputfalse- Divisibility:
n % d == 0. - Digits:
n % 10is the last digit;n / 10removes it. - Count matches, find min/max, compute sum and average.
- Start a max at the first value (or
Integer.MIN_VALUE), not 0, when values can be negative. - Cast before dividing for an average:
(double) sum / count. - Initialize accumulators before the loop, not inside it.
What does this compute for n = 5?
int r = 1;
for (int i = 2; i <= n; i++) r *= i;Show answer
120, which is 5 factorial.