Download Object Oriented Programming Arrays Chapter 5 and more Thesis Object Oriented Programming in PDF only on Docsity!
Lecture 5: Arrays
Arrays
- A data structure which stores fixed size collection of
elements of the same type.
- Once an array is created, its size is fixed.
- An array is used to store a collection of data of the same
type.
- Instead of declaring individual variables such as
number0, number1 ….number99.. We can declare one
array variable called numbers of size 100.
- We can then access all the number using an index. 6/13/2018 Object Oriented Programming
Indexing Arrays
- Access to array members is done through indexes.
- Indexing starts at 0.
- Example:
int [] myarray=new int[5];
myarray[0]=10; myarray[1]=20; myarray[2]=30; myarray[3]=40; myarray[4]=50; 6/13/2018 Object Oriented Programming Index Value myarray[0] 10 myarray[1] 20 myarray[2] 30 myarray[3] 40 myarray[4] 50
Example
6/13/2018 Object Oriented Programming
Examples of processing arrays:
1. Initializing arrays with input values
Scanner input=new Scanner(System.in);
int [] myarray=new int[5];
System.out.println("Enter 5 integers");
for(int i=0; i<5; i++)
myarray[i]=input.nextInt();
6/13/2018 Object Oriented Programming
2. Displaying arrays
int [] myarray=new int[5]; for(int i=0;i<5;i++) { System.out.println(myarray[i]) } 6/13/2018 Object Oriented Programming
length
- How can we get the length of an array?
- Using the .length attribute
- Example myarray.length will return the size of my array We can use this .length attribute in out for loops int [] myarray=new int[5]; double total=0; for(int i=0;i<myarray.length;i++) { total=total+myarray[i] } 6/13/2018 Object Oriented Programming
for(int i=0;i<5;i++)
Passing Arrays to methods
public static void printArray(int [] myarray)
for (int i=0;i<myarray.length;i++)
System.out.println(myarray[i]);
6/13/2018 Object Oriented Programming
Array of Objects
- Student [] mystudent=new Student[5]
- mystudent[0]=new Student() 6/13/2018 Object Oriented Programming
Exercise
- Write a program to find the maximum and minimum values from an int array 6/13/2018 Object Oriented Programming