Loops
——
1. while
// fucntion to check for a prime number public static boolean isPrime( int n){ int divisor = 2; while(divisor < n){ if (n % divisor == 0){ // this is the while loop return false; // since n is divisible by a number } divisor++; } return true; // checked all values from 2 to n-1 }
If n <= 2, the loop wont execute.
2. for
for(initialise; test; next){ // intitalise gets executed first while (test){ //statements; //next; } }
// check for the prime number using a for loop public static boolean isPrime( int n){ for(int divisor =2 ; divisor < n ; divisor ++){ if (n % divisor == 0){ // this is the while loop return false; // since n is divisible by a number } return true; // checked all values from 2 to n-1 }
Loop bounds
————-
// Print all the prime numbers in the range from 2 to n public static void printPrimes( int n) { int i; for(i =2; i < n ; i++){ // error as the condition should be i <= n if (isPrime(i)){ System.out.println(" " + i); } } }
Arrays
——–
An object consists of numbered list of variables. Each is a primitive type or a reference to a object.
char[] c; // reference to an array of characters which can be of any length c = new char[4]; // creates the array and the size is mentioned c[0] = 'b'; // we use the single quotes for characters c[3] = 't'; c[8] = 'y'; // Runtime exception int a = c.length; // gives the length of the array c.length = 20; // gives a compile time error
Multidimensional arrays
————————
2D array : Is an array of references to 1D arrays. For example the Pascal’s triangle: In mathematics, Pascal’s triangle is a geometric arrangement of the binomial coefficients in a triangle. It is named after mathematician Blaise Pascal.
// creates and returns a pascal triangle using 2D arrays public static int[][] pascalTriangle (int n){ int[][] pt = new int[n][]; // allocates n references for the array. for( int i = 0; i< n ; i++){ pt[i] = new int[i+1]; pt[i][0] = 1; for (int j = 1; j< i; j++){ pt[i][j] = pt[i-1][j-1] + pt[i-1][j]; } pt[i][j] = 1; } return pt; }