Arrays
Dr. Ali Allam Introduction to Programming (BIS227E)
Introduction to Arrays
An array is a data structure that stores multiple values in one single
object, instead of declaring separate variables for each value.
To introduce the importance of arrays, let’s discuss the following
example. Suppose you have a list of names (e.g. employees’ names).
Storing their names in different separate variables would look like
this:
String name1 = “Ahmed Mostafa”;
String name2 = “Sarah Maged”;
String name3 = “Youssef Farid”;
Introduction to Arrays
Oops! … what if you want to go through the employees and search
for a certain one? and what if you have100 employees? Of course,
it’s unrealistic to define 100 different variables!
Solution … The solution is to create an array. An array can hold
many values within one single structure, and you can access the
values by referring to an index number in that array.
Indexed Arrays
The index of an array refers to the location of an item within the
array.
The index always start from 0. So, an array of 100 items, has an
index starting from 0 to 99. The indices are assigned automatically.
To declare an array, define the data type with square brackets, and
assign its multi-values in a comma-separated list inside curly brackets,
like this:
String[ ] names = {"Ali", "Sarah", "Amr"}; → Array containing three strings
int[ ] marks = {87, 95, 68, 94, 25, 76}; → Array containing six integers
Indexed Arrays
To declare an array, without assigning values to it, the array would
be defined like this:
int[ ] marks = new int[5]; → Array initialized by 5 zero-integers
String[ ] names = new String[10]; → Array initialized by ten empty (null) strings
boolean[ ] status = new boolean[4] → Array initialized by four false-values
Note: The elements of a new array is initialized by “zero-equivalent”
values.
All elements of the array must be of the same data type of which the
array is declared.
Example (1): Assigning values to an array
public class Prog1
{
public static void main(String[ ] args)
{
Employees:
String[ ] names = {"Ahmed", "Sarah", "Dina", "Amr", "Ali"};
System.out.println("Employees:"); Employee(1): Ahmed
System.out.println("Employee(1): " + names[0]); Employee(2): Sarah
System.out.println("Employee(2): " + names[1]); Employee(3): Dina
System.out.println("Employee(3): " + names[2]); Employee(4): Amr
System.out.println("Employee(4): " + names[3]); Employee(5): Ali
System.out.println("Employee(5): " + names[4]);
}
}
Tip: ARRAYS should be typically handled via LOOPS. Let’s see how …
Example: Handling an array using “for” loop
Printing the elements of an array using a for-loop:
public class Prog1for
{ Employees:
public static void main(String[ ] args)
Employee(1): Ahmed
{
String names[ ] = {"Ahmed", "Sarah", "Dina", "Amr", "Ali"};
Employee(2): Sarah
System.out.println("Employees:"); Employee(3): Dina
for(int i=0; i<=4; i++) Employee(4): Amr
System.out.println("Employee (" + (i+1) +"): " + names[i]); Employee(5): Ali
}
}
Looping is the typical way to deal with an array, no matter how big it is.
Example: Handling an array using “while”
public class Prog1while
{
public static void main(String[ ] args)
{ Employees:
String names[ ] = {"Ahmed", "Sarah", "Dina", "Amr", "Ali"}; Employee(1): Ahmed
System.out.println("Employees:"); Employee(2): Sarah
int i=0;
while(i<=4)
Employee(3): Dina
{ Employee(4): Amr
System.out.println("Employee (" + (i + 1) + "): " + names[i]); Employee(5): Ali
i++;
}
}
}
Example: Handling an array using “do while”
public class Prog1dowhile
{
public static void main(String[ ] args)
{ Employees:
String names[ ] = {"Ahmed", "Sarah", "Dina", "Amr", "Ali"}; Employee(1): Ahmed
System.out.println("Employees:"); Employee(2): Sarah
int i=0;
do
Employee(3): Dina
{ Employee(4): Amr
System.out.println("Employee (" + (i + 1) + "): " + names[i]); Employee(5): Ali
i++;
} while(i<=4);
}
}
The “for-each” loop
“for-each” is a special kind of loop, which is heavily used with
arrays (i.e. it works exclusively with arrays, and nothing else).
The striking advantage of using a “for-each” loop, is that it
surpasses the hassle of the array’s indexing.
General Syntax:
for (dataType variableName : arrayName)
{
statement(s) that loops through the elements of the whole array …
}
Example: Handling an array using “for-each”
public class Prog1foreach
{
public static void main(String[ ] args)
{ Employees:
String names[ ] = {"Ahmed", "Sarah", "Dina", "Amr", "Ali"}; Employee(1): Ahmed
System.out.println("Employees:"); Employee(2): Sarah
int counter=1;
for(String v: names)
Employee(3): Dina
{ Employee(4): Amr
System.out.println("Employee (" + counter + "): " +v); Employee(5): Ali
counter++;
}
}
}
Example (2): Input the values into an array
All the previous examples
used to assign fixed
values to the declared
array.
What if the user is asked
to input the names of
these employees? like this:
import javax.swing.*;
public class Prog2
{
public static void main(String[ ] args)
{
String names[] = new String[3];
for(int i=0; i<=2; i++)
names[i]= JOptionPane.showInputDialog("Enter the name of Employee (" + (i+1) + "):");
JTextArea msg = new JTextArea("Employee ID\tEmployee Name\n");
msg.append("========================\n");
for(int i=0; i<=2; i++)
{
msg.append("Employee (" + (i + 1) + ")\t" + names[i] + "\n");
msg.append("--------------------------------------------\n");
}
JOptionPane.showMessageDialog(null,msg);
}
}
Indexed Arrays: dynamic size
Let’s go for more dynamicity and flexibility… Suppose that we want to
define an array of an undetermined size in which the user is asked to enter
its size.
For example, the user is first asked to enter the number of employees.
Accordingly, the user is redirected to enter their names. At the end, the
program prints the names of these employees.
Example: Input the size of the array
import javax.swing.*;
public class Prog2B
{
public static void main(String[ ] args)
{
int n = Integer.parseInt(JOptionPane.showInputDialog("Enter the number of employees:"));
String names[] = new String[n];
for(int i=0; i<n; i++)
names[i]= JOptionPane.showInputDialog("Enter the name of Employee (" + (i+1) + "):");
JTextArea msg = new JTextArea("Employee ID\tEmployee Name\n");
msg.append("========================\n");
for(int i=0; i<names.length; i++)
{
msg.append("Employee (" + (i + 1) + ")\t" + names[i] + "\n");
msg.append("................................................................................\n");
}
JOptionPane.showMessageDialog(null, msg);
}
}
Arrays: More examples
In the previous part, you’ve been introduced to the concept of defining
arrays, inputting and outputting their values.
Now, let’s take more examples to emphasize the importance of using
arrays. Examples, such as:
➢ Filtering the values of an array
➢ Calculating the average of the values of an array
➢ Handling more than one array at a time
➢ Determining the highest value in an array
➢ Searching for a value inside the array
➢ Sorting the values of an array
Example (3): Filtering the values of an array
The user inputs eight values into an array Enter the weather temperature of 8 cities:
Temperature of city (1): 25.4
that represents the temperatures of eight Temperature of city (2): 19.2
cities. Then the program prints the Temperature of city (3): -6.8
Temperature of city (4): 38
temperatures above zero. Temperature of city (5): 10.9
Temperature of city (6): -8.9
Temperature of city (7): -1
Temperature of city (8): 13.2
The temperatures above zero-degree are:
25.4
19.2
38.0
10.9
13.2
import java.util.*;
public class Prog3
{
public static void main(String[ ] args)
{
Scanner input = new Scanner(System.in);
double[] temp = new double[8];
System.out.println("Enter the weather temperature of 8 cities: ");
for(int i=0; i<temp.length; i++)
{
System.out.print("Temperature of city (" + (i+1) + "): ");
temp[i] = input.nextDouble();
}
System.out.println("The temperatures above zero-degree are:");
for(double x: temp)
if (x >= 0)
System.out.println(x);
}
}
Example (4): Calculating the average
The user inputs ten values Enter the age of student (1): 25
into an array. The program Enter the age of student (2): 22
calculates and prints the Enter the age of student (3): 33
Enter the age of student (4): 41
average of these values. Enter the age of student (5): 25
Enter the age of student (6): 22
Enter the age of student (7): 23
Enter the age of student (8): 28
Enter the age of student (9): 30
Enter the age of student (10): 38
The age average of the students is: 28.7
import java.util.*;
public class Prog4
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int[] age = new int[10];
int sum=0;
for(int i=0; i<age.length; i++)
{
System.out.print("Enter the age of student (" + (i+1) + "): ");
age[i] = sc.nextInt();
sum += age[i];
}
double avg = 1.0*sum / age.length;
System.out.print("The age average of the students is: "+avg);
}
}
Enter the marks of student (1):
Example (5): Adding up two First Exam: 45
Second Exam: 46
different arrays Enter the marks of student (2):
First Exam: 37
Second Exam: 43
Enter the marks of student (3):
First Exam: 35
The user inputs the marks of five Second Exam: 35
different students on two exams. Enter the marks of student (4):
First Exam: 42
The program prints the grades sheet Second Exam: 48
Enter the marks of student (5):
which contains the marks of all First Exam: 50
students in both exams, as well as Second Exam: 49
Exam(1) Exam(2) Total
their total marks, as shown. =========================
45 46 91
37 43 80
35 35 70
42 48 90
50 49 99
Example (5): Adding up two different arrays
Scanner sc = new Scanner(System.in);
int[] exam1 = new int[5];
int[] exam2 = new int[5];
int[] total = new int[5];
for(int i=0; i<=4; i++)
{
System.out.println("Enter the marks of student (" + (i+1) + "): ");
System.out.print("First Exam: ");
exam1[i] = sc.nextInt();
System.out.print("Second Exam: ");
exam2[i] = sc.nextInt();
total[i] = exam1[i] + exam2[i];
}
System.out.println("Exam(1)\tExam(2)\tTotal\n=====================");
for(int i=0; i<=4; i++)
System.out.println(exam1[i]+"\t\t"+exam2[i]+"\t\t"+total[i]);
Example (6): Getting the maximum value
import javax.swing.*;
public class Prog6A
{
public static void main(String[] args)
{
int temp[] = {21, 24, 18, 20, 9, -5, 42, 28, 6, 30};
int max = temp[0];
for(int i=1; i<temp.length; i++)
if(temp[i] > max)
max = temp[i];
JOptionPane.showMessageDialog(null, "The highest
temperature is: "+max);
}
}
Example (6): Getting the maximum value
import javax.swing.*;
public class Prog6B
{
public static void main(String[] args)
{
int temp[] = {21, 24, 18, 20, 9, -5, 42, 28, 6, 30};
int max = temp[0];
for(int t: temp)
if(t > max)
max = t;
JOptionPane.showMessageDialog(null, "The highest
temperature is: "+max);
}
}
Example (7): Searching inside an array
String guests[] = {"Ali", "Amr", "Aya", "Ola", "Joe", "Mai", "Dina", "Mary", "Sam", "Bob"};
String str = JOptionPane.showInputDialog("Search for a name:");
boolean status=false;
for(int i=0; i<guests.length; i++)
{
if( str.equalsIgnoreCase(guests[i]) )
{
JOptionPane.showMessageDialog(null, str + " is invited to the party!");
status = true;
}
}
if(status == false )
JOptionPane.showMessageDialog(null, str +" is not invited to the party!","",0);
Example (7): Searching inside an array
Example (8): Sorting an array ascendingly
int marks[] = {53, 44, 77, 83, 62, 94, 58, 98, 45, 77};
System.out.println("The sorted array is:");
for(int i=0; i<9; i++)
{ The sorted array is:
for(int j=i+1; j<=9; j++) 44
{ 45
if(marks[j]<marks[i]) 53
{
58
int temp = marks[i];
marks[i]=marks[j];
62
marks[j]=temp; 77
} 77
} 83
System.out.println(marks[i]); 94
}
Built-in methods for Arrays!
Ah-ha! Java has a class called (Arrays) that contains several inbuilt
methods that facilitate some of the previous examples ☺
This class is predefined in the java.util package.
Arrays.sort(arrayName) → Sorts the elements of an array ascendingly
Arrays.binarySearch(arrayName,searchKey) → Searches for an element
within a sorted array (the array must be sorted). This method returns the
index/position of that element. If the element is not found, the method
returns -1.
Arrays.compare(array1,array2) → Compares two arrays to each other
and other many methods …
Example (9): Sorting and Searching
import java.util.*;
public class prog9{
public static void main(String[] args) The sorted marks are:
{ 44
int marks[] = {53,44,77,100,62,94,85,98,45,77}; 45
Arrays.sort(marks); 53
System.out.println("The sorted marks are:"); 62
for(int m: marks) 77
System.out.println(m); 77
int index = Arrays.binarySearch(marks,100);
85
if(index==-1)
System.out.println("Uh-Oh. Nobody got the full mark!"); 94
else 98
System.out.println("Wow. Someone got the full mark!"); 100
} Wow. Someone got the full mark!
}