One of the more fundamental concepts to uderstand in programming is in finding the maximum or minumum in an array. Suppose you want to find the largest number in an array. Keep a candidate for the maximum. If you find an element with a larger value, then replace the candidate with that value. When you have reached the end of the array list, you have found the maximum. There is just one problem. When you visit the beginning of the array, you don’t yet have a candidate for the maximum. One way to overcome that is to set the candidate to the starting element of the array and start the comparison with the next element.
1 2 3 4 5 6 7 8 9 10 11 | //creating an array with 5 numbers int[] numbers = {1, 3, 5, 7, 9}; //creating a variable and setting it to array position 0 int largestYet = numbers[0] //looping through the rest of the array to find maximum num for(int i = 0; i < numbers.lenght; i++) { int a = numbers[i]; if(a > largestYet) largestYet = a; } |
Inheritance: is a mechanism for enhancing existing classes. If you need to implement a new class and a class representing a more general concept is already available, then the new class can inherit from the existing class. For example , suppose you need to define a class SavingsAccount to model an account that pays a fixed interest rate on deposit. You already have a class BankAccount, and a savings account is a special case of a bank account. In this case, it makes sense to use the language construct of inheritance. Here’s the syntax for the class definition. Read the rest of this entry »