Any experienced coder would say that the ability to see patterns in code, remember them, and learn from them when creating code is another kind of 'superpower'. The following samples are really simple techniques, but they show some common ways of doing things that you should think about and study. In almost all these examples, there may be some missing variable declarations. Just roll with it. If you think about it, I’m sure you can figure out what variable declarations are needed to run the sample in jshell.
If you wanted to find the larger of two values, x and y and assign it to 'max':
if (x > y) {
max = x;
} else {
max = y;
}Related to it, if we have two variables x and y, and we want the smaller in x, and the larger in y.
if (x > y) {
int t = x;
x = y;
y = t;
}Do you see the three statements in the block there? That’s called a 'swap'. If you need to swap two values in two variables, you just create a quick temporary variable 't' and use it as a place to make a copy of the first variable’s value.
If I needed to make sure a number is always positive (greater than zero), it’s easy - this is called taking the "absolute value" of a number.
if (n < 0) n = -n;The next few are examples of the handy use of loops to do a bunch of math easily and quickly. Imagine a problem where you have to "add all the numbers from 1 to 100 and print the sum." It might also be expressed as "sum all the number from x to y" (where x and y are two integers). Turns out there is a very easy pattern to learn here.
int sum = 0;
int n = 100;
for (int i = 1; i < n; i++) {
sum = sum + i;
}
System.out.println(sum);Now, if you wanted to find the average of a bunch of numbers, that’s as easy as taking the sum of the numbers and dividing the sum by the number of numbers (or n).
int sum = 0; // this needs to be 0 not 1
int n = 100;
for (int i = 1; i < n; i++) {
sum = sum + i;
}
int average = sum / n;
System.out.println(average);Pretty easy, yes? And the other common pattern here is doing a product of all the numbers from 1 to n. (Let’s try 20)
int product = 1; // this needs to be 1 not 0
int n = 20;
for (int i = 1; i < n; i++) {
product = product * i;
}
System.out.println(product);Perhaps you want to print a table of values of some equation.
for (int i = 0; i <= n; i++) {
System.out.println(i + " " + i*i/2);
}Arrays are often something that confuses beginning coders. Let’s look at some code patterns with arrays that let you see how arrays and loops can work together to get a lot of work pretty easily.
The array we are going to use in all these cases is pretty simple. It’s an array of 7 numbers.
int[] a = {4, 3, 7, 0, -4, 1, 8};Here how to print out the array, one value per line.
for (int i = 0; i < a.length; i++) {
System.out.println(i + " " + a[i]); // print the index and value of an array element.
}If we needed to find the smallest number in the array, we could do:
int min = a[0];
for (int i = 1; i < a.length; i++) {
if (a[i] < min) min = a[i];
}
System.out.println(min);We should look carefully here. First, notice how I have taken the first element a[0] and made my first 'min' that value. Then, I started at 1 (not 0), to be my first compare. Then we step through the array, looking at each value and if the new value is smaller than the previous one, we update it; otherwise, we just do the next value. [1]
NOW, if you wanted to find the largest value in the array, you really only have to change a couple things.
int max = a[0];
for (int i = 1; i < a.length; i++) {
if (a[i] > max) max = a[i];
}
System.out.println(max);Carefully look at the code, comparing to the one above. What’s different? Well, for one, we changed the variable from 'min' to 'max'. (But did we need to do that? We could have left it max, but it’s cleaner to make the change so people who read it aren’t confused.) We also changed the comparison in the 'if' statement from "less than <" to "greater than >" which lets us decide if the new number is larger than the previous largest we found.
In both of these cases, we start with an initial value, then we step through the array, look at each value comparing it to the smallest (or largest) value we have yet found. If we need to update the 'carrying variable', we do; otherwise, we just ignore the value.
What about finding the average of the values in the array? Well, we do it a lot like the average of the series of numbers.
int sum = 0;
for (int i = 0; i < a.length; i++) {
sum = sum + a[i];
}
int average = sum / a.length ; // whoa! lookee there?
System.out.println(average);Yep, the "a.length" is very handy, it has exactly the count of the numbers in the array!
Finally, if we wanted to reverse the values in the array, we could write some code:
System.out.println("before: " + Arrays.toString(a));
int n = a.length;
int half = (int) Math.ceil(n / 2.0);
for (int i = 0; i < half; i++) {
int t = a[i];
a[i] = a[n-1-i];
a[n-i-1] = t;
}
System.out.println("after: " + Arrays.toString(a));Sometimes, you need to do a loop inside a loop. This is called a "nested loop". Here is an example of a nested loop that prints a multiplication table.
int n = 10;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
System.out.print(i * j + "\t");
}
System.out.println();
}This code prints a multiplication table from 1 to 10. The outer loop (with variable i) goes from 1 to n, and for each value of i, the inner loop (with variable j) goes from 1 to n, printing the product of i and j. The "\t" is a tab character, which makes the output look like a table.
The inner loop completes all its iterations for each iteration of the outer loop. The result is a table of products, where each row corresponds to a value of i and each column corresponds to a value of j. The output looks like this:
1 2 3 4 5 6 7 8 9 10
2 4 6 8 10 12 14 16 18 20
3 6 9 12 15 18 21 24 27 30
4 8 12 16 20 24 28 32 36 40
5 10 15 20 25 30 35 40 45 50
6 12 18 24 30 36 42 48 54 60
7 14 21 28 35 42 49 56 63 70
8 16 24 32 40 48 56 64 72 80
9 18 27 36 45 54 63 72 81 90
10 20 30 40 50 60 70 80 90 100This is a simple example of how nested loops can be used to create complex patterns and structures in code.
In the AI age, (after about mid-2023), you might be tempted to use an AI tool to generate this code for you. That’s fine, but you should understand what the code is doing.
But learning to read code is a very important skill. You should be able to read code and understand what it is doing. These examples of code patterns are a good way to learn to read code. You should be able to glance at a piece of code and say "oh, that’s finding the largest value in an array" or "that’s reversing the values in an array" or "that’s finding the average of the values in an array". You should be able to see these patterns and remember them.