Saturday, April 13, 2013

Java - Iteration and Arrays


"while" loops to check a number is prime or not.

public static boolean isPrime (int n) {
  int divisor =2;
  while (divisor < n) {
    if (n%divisor == 0) {
      return false;
    }
  return true;
}

"for" loops

for (initialize; test; next) {
  statement;
}
  Equivalent to: 
initialize;
while (test) {
  statement;
}
next;

ARRAYS
initialize a list of charactors:
char[] c = new char[4]; // reference to array of charactors of any length

For strings c.length() is a method
For characters c.length is a field.

Print the primes from 1 to n using Sieve of Eratosthenes:
public static void printPrimes(int n) {
boolean[] prime = new boolean[n+1];
        int i;

for (i=2; i<=n; i++){
prime[i]=true;
}
for(int divisor=2; divisor*divisor<=n; divisor++){
if(prime[divisor]){
for(i=2*divisor; i<=n; i=i+divisor){
prime[i]=false;
}
}
}
for(i=2; i<=n; i++){
if(prime[i]){
System.out.print(" "+i);
}
}
}
}

No comments:

Post a Comment