Skip to content

Instantly share code, notes, and snippets.

@rshepherd
Last active December 25, 2015 11:19
Show Gist options
  • Save rshepherd/6968332 to your computer and use it in GitHub Desktop.
Save rshepherd/6968332 to your computer and use it in GitHub Desktop.
public class ForLoops {
public static void main(String[] args) {
// for ( init ; test ; increment ) {
// body
// }
// 1) The 'init' code runs once to set things up at the very start of the loop.
// 2) The boolean 'test' is evaluated.
// 3) The 'body' is a series of statements.
// 4) Finally, the 'increment' code executes just after the body.
for (int i = 0; i < 100; i++) {
System.out.println("i:" + i);
}
// 'continue' - skips to next iteration of the loop. useful to short circuit iteration in order to avoid something expensive.
// 'break' - discontinues execution of the loop. useful if further work is unnecessary.
int answer = -1;
for (int i = Integer.MAX_VALUE; i > 0; i--) {
if (isEven(i)) { // cheap to check
// can't be the answer if its even, avoid expensive calc below
continue;
}
if (isPrime(i)) { // comparatively expensive
answer = i;
// found our answer, no need to keep computing
break;
}
}
System.out.println("The first prime less than max int is " + answer);
}
private static boolean isEven(int i) {
return i % 2 == 0;
}
private static boolean isPrime(int n) {
for (int i = 2; i < n / 2; i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment