Goals
Session 3
Review
Session 2
Conditional Branching
Enable to branch the program execution, depending on whether a certain condition is met or not.
if clause
Controls the flow of the execution of statements Two-way decision statement Evaluates the expression depending on whether the value of expression is true or false; control is transferred to a particular statement.
if clause
Examples
if ( salary < 1000 ) salary = salary + 100; if (salary < 1000) { salary = salary + 100; }
if
else clause
ifelse statement is an extension of simple if statement. General form of if..else statement is:
if(test expression is true) { block of statements } else { block of statements //if test expression // is false } statement;
If
else clause
if - else clause
Example:
int number; number = 27; if((number % 2) == 0) System.out.println("number is even"); else System.out.println("number is odd");
else if clause
When multipath decisions are involved, multiple ifs are put together.
if(conditon1) { statement block1; } else if(condition2) { statement block2; } else { default statement block; } statement
else if clause
Example
if(salary >= 10000) { bonus = salary * .2; } else if(salary >= 8000) { bonus=salary * .3; } else if(salary >= 6000) { bonus=salary * .5; } else { bonus=salary *.75; } System.out.println(" Bonus is : "+bonus
Nesting if statements
if (salary >= 50000) { if (yearOfService > 5) { System.out.println(Eligible for Bonus); } else { System.out.println(Not eligible for service); } } // if else { System.out.println(Salary not greater than 50000); } // else
switch clause
switch(test) { case value1: block of statements; break; case value2 : block of statements; break; .. default : default block; break; } statements;
switch clause
Example: switch(choice) { case 1: System.out.println (Case 1); break; case 2 : System.out.println (Case 2); break; default : System.out.println (None of the cases); break; } //switch
Methods in Java
Predefined Methods:
User
Defined
Encapsulate few line of code under one name Reusable Divide and Conquer
Provide a way to group a block of code and then refer to it by name. If a program is divided into functional parts, then each part may be independently coded and later combined into a single unit. These sub programs are called as methods Make the program easier to understand, test, debug and maintain. Saves time, memory, space
Method Definition
Name of the method Type of object or primitive type the method returns A list of parameters The body of the method
If the method has a return type, you need to explicitly return a value inside the body of the method. For this return keyword is used. Methods in Java can return any valid Java type. This can be primitive data types, boolean, an array or an object.
Method Prototype
Method's signature or prototype consists of:
Name of the method Type of object or primitive type the returns A list of parameters
method
Advantage: only one copy of the method will be stored and can be used without creating an object. (This will become more clear once we get to object theory.)
Methods Definition
static int findLargest(int a, int b, int c) { int high = a; if (b > high) high = b; if (c > high) high = c; return high; }
Method call
Example
findLargest is the method call. 19, 12 and 16 are args. a, b and c are parameters
The value of arguments is passed to parameters The datatype of args. and parameters must match by position Number of args = Number of parameters
} }
Loops
Loops that keep on repeating an operation, depending on the results obtained within the loop. Not executed a fixed number of times
Loop Structure
Consists of a control statement and a body Control statement tests certain conditions and then directs the repeated execution of the statements contained in the body of the loop. Entry-controlled loop (Pre-Test)
Control conditions tested, before the start of the loop execution. If control condition is not satisfied, the loop never gets executed. Control condition tested at the end of the loop body. Even if the test condition is not satisfied, the loop gets executed at least once
Setting and initialization of the counter Execution of statements in the loop Test for specified condition for the execution of the loop Incrementing or decrementing the counter
Test condition is evaluated If test condition is true, then the body of the loop is executed. Body of the loop executes repeatedly, till the test condition becomes false Control is transferred out of the loop
while Loop
General Syntax
while(test condition) { body of the loop }
do while Loop
An exit-controlled and indeterminate loop:
Test condition is evaluated, after the loop body Even if the condition is false, the loop will get executed, at least once.
do while Loop
General Syntax
do (test condition) { body of the loop } while (test condition);
for loop
Lab 2 Discussion
On Discussion Thread
Arrays
An array is a group of related data items that share a common name. Individual values in an array are referred to as elements. Array can be of any variable type. An item can be referred in an array, by using index number.
Arrays
Arrays help in developing short and concise programs. Examples of arrays in Java:
int numbers[ ]; char[ ] letters; String [ ] names;
Declaring an Array
An array variable is created to hold the array elements. Array variable is declared just like any other variable except that empty brackets i.e. [ ] are used while declaring an array. Array variable declarations:
int score[ ]; float temp[ ]; String names[ ];
Java does not allow to specify a number between the empty square brackets to represent number of items in the array. To create array objects,
num1 = new int[3];
When an array object is created, using new operator, all the slots of the array are initialized
0 for numeric arrays, false for boolean, '\0' for character arrays and null for objects.
Can also create array objects, with values initialized in the array:
int num1[ ] = { 2, 34, 29, 10 };
All the elements inside the braces must be of same type, as the variable that holds the array. In this type of declaration, an array of the size of number of elements included will be automatically created.
To access an initial value stored in an array, the index number or the subscript of that array element has to be used:
ArrayName[subscript];
String[ ] Name = new String[100]; means Name is an array that has 100 slots for storing 100 strings. These strings can be accessed using the subscript from 0 to 99.
To assign a value to an array element, the index number or the subscript of that array element has to be used:
Name[0] = Becky"; Name[1] = Max"; Name[2] = Jim"; Name[99] = John ;
..
To avoid accidentally overrunning the end of the array in the program, you can test the length of the array, by using the length instance variable
int len = Name.length;
One-dimensional array
One-dimensional array is a list of items represented in the form of an array that has only one subscript. For example,
Name[0] = Becky;
One-dimensional array
class ArrayDemo { public static void main(String args[]) { int[] num; int i; num = new int[4]; num[0] = 20; num[1] = 2; System.out.println(" Numbers in array are num[0] + + num [1]); } }
"+
Multi-dimensional array
For example, if we have to store Score1 and Score2 of 4 students, it can be done by:
Student = new int[4][2];
Multi-dimensional array
class ArrayDemo { public static void main(String args[]) { int[][] Student; Student = new int[4][2]; //First student test score Student[0][0] = 20; Student[0][1] = 2; System.out.println(" Score1 of Student1 is: " + Student[0][0]); System.out.println(" Score2 of Student1 is: " + Student[0][1]); } }
Arrays are passed by reference to the methods. This means that changes that occur to the array inside the function, affect the original array.
Searching
Sequential Search
Used if list is not ordered or not sorted This search algorithm is very slow. The list is traversed, till an item is found or till the end of the list.
Sequential Search
//Code for sequential search //target and locn is of found item int looker = 0; while ( looker < last && target != list[looker] ) looker++ ; locn = looker ; return ( target == list[looker] ) ;
Binary Search
Used if the list is ordered or sorted Binary search starts off by testing data in the middle of the array. This determines if the target is in the first half or the second half of the array. Whichever half has the element is checked again. The half in which the element does not exist need not be tested again. Repeat the process till element is found.
Binary Search
Binary Search
int first = 0; int mid ; int last ; while ( first <= last ) { mid = ( first + last ) / 2 ; if ( target > list[ mid ] )
first = mid + 1 ; /* look in upper half else if ( target < list[ mid ] )
*/
last = mid - 1 ; else first = last + 1 ; } locn = mid ; return (target == list [mid]);
Sorting
Insertion Sort
The array is divided into two parts: sorted and unsorted. In each pass the first element of the unsorted sublist is picked and transferred into the sorted sublist by inserting it at the appropriate place. It will take n-1 passes to sort an array of size n.
Insertion Sort
public void insertionSort (int[] list, int last ) { /*Local Declarations*/ int current ; /*Statements*/ for ( current = 1 ; current <= last ; current++) insertOne( list, current) ; return ; } //contd.
Insertion Sort
void insertOne (int[] list, int current ) { int walker; int located; int temp ; located = FALSE ; temp = list[current] ; for (walker=current-1; walker >= 0 && !located;) if (temp < list[ walker ]) { list[walker + 1] = list[walker]; walker--;} else located = TRUE; list [ walker + 1 ] = temp ;}
Bubble Sort
Using a for loop the lowest element is bubbled to the beginning of the unsorted segment of the array. Accomplished by a function called bubbleUp - makes one pass through the data.
Whenever it finds two elements out of sequence, it exchanges them. It then continues with the next element. This allows smallest number to be bubbled to the beginning of the array, while at the same time adjacent elements along the way are rearranged.
Bubble Sort
void bubbleUp (int[] list, int current, int last) { int walker ; int temp ; for ( walker = last ; walker > current ; walker- ) if (list[ walker ] < list[walker - 1]) { temp = list[walker] ; list[walker] = list[walker - 1] ; list[walker - 1] = temp ; }//if return ; }// bubbleUp
Selection Sort
List is divided into sublists, sorted or unsorted, which are divided by an imaginary wall. Find the smallest element from the unsorted sublist and swap it with the element in the beginning of the unsorted list. After each selection the wall between the sublist moves one element ahead, increasing the number in the sorted list and decreasing the number in the unsorted list. Each time we move one element from the unsorted list to the sorted list, it completes a sort pass. n-1 passes for sorting an array of n elements.
Selection Sort
public void selectionSort (int[] list, int last ) { /*Local Declarations*/ int current ; /*Statements*/ for ( current = 0 ; current < last ; current++ ) exchangeSmallest ( list, current, last ) ; return ; } /*selectionSort*/
Selection Sort
void exchangeSmallest(int[] list, int current, int last) { int walker; int smallest; int tempData; smallest = current; for (walker = current + 1 ; walker <= last ; walker++) //Smallest selected: exchange with current element if ( list[ walker ] < list[ smallest ] ) smallest = walker ; tempData = list[ current ] ; list[current] = list[ smallest ] ; list[smallest] = tempData ; return ; }// exchangeSmallest
Lab 3 Discussion
On Discussion Thread