Ch 1- Intro to DS and Array (4)
Ch 1- Intro to DS and Array (4)
Data Structures
Algorithms are used to process data within data structures to perform the
intended tasks (for example add, delete, update, sort, and search)
So ..
Algorithms + Data structures = A program
Computer applications are getting more complex and require the use of rich
and large data.
Storing, processing, and searching the used data efficiently becomes
challenging.
The choice of a suitable algorithm and a data structure can affect the
}
public static void main(String[] args) {
enterMarks ();
} 19
Faculty of Information Technology - Computer Science Department
}
The length Property of Arrays
In Java, arrays are objects.
Each array has the length member variable (or property) that represents the number of
elements of the array.
For example, the output of the following two lines of code is 5:
int[] a = new int[5];
System.out.println(a.length);
Always remember, that the first element of the array has an index 0, and the last element
has index length-1.
A for statement can be used to iterate from 0 to length–1 int[] marks ={95,75,42,68,57,88};
25
Faculty of Information Technology - Computer Science Department
Copying Arrays
Suppose we want to copy the elements of an array to another array. We could try this
code:
int [] numbers ={1, 8, 9, 0, 6, 7, 10};
numbersBackup = numbers; // incorrect!
Although this code compiles, it is logically incorrect! We are copying the numbers
object reference to the numbersBackup object reference. We are not copying the
array data.
The result of this code is shown on the next slide.
Example: this code copies the values of all elements in an array named numbers to an
array named numbersBackup, both of which have previously been instantiated
with the same length:
for ( int i = 0; i < numbers.length; i++ )
{
numbersBackup[i] = numbers[i];
}
The effect of this for loop is shown on the next slide.
numbers
numbersBackup
numbers [0] 0 1
numbersBackup [0] 0 1
numbers [1] 1 8
numbers [2] numbersBackup [1] 1 8
2 9
numbersBackup [2] 2 9
numbers [3] 3 0
numbersBackup [3] 3 0
numbers [4] 4 6
numbersBackup [4] 4 6
numbers [5] 5 7
numbersBackup [5] 5 7
numbers [6] 6 10
numbersBackup [6] 6 10
2 ndMark
3 rdMark
1 stMark
In fact, matrices have many applications in
mathematics and our daily lives. 0 1 2
Consider an example of five students, each student 0 0 0 0 1st Student
1 0 0 0 2nd Student
has three marks.
2 0 0 0 3rd Student
In this case, we need to declare a 2D array with: marks=
4th Student
3 0 0 0
5 rows, each row represents a student. 4 0 0 0 5th Student