Spring Semester
2024-2025
CS112
Programming Languages Lecture 8
Mahmoud Bassiouni, PhD
[email protected]
Table of Contents
• Arrays
• Create Arrays
• Array Declaration
• Array Length
• Accessing an array
• Array Initialization
• Length of the Array
• Printing and Inputting Arrays
• Copy Arrays
• Comparing Arrays Examples on Arrays
• For-each 2
Arrays
• To define a variable in Java we need to define the datatype of the variable and then
the variable name.
int firstnumber;
• In order to define three variables, we need to create the following:
int firstnumber;
int firstnumber, secondnumber, thirdnumber;
int secondnumber;
• In order to define five variables, we need to create the following: int thirdnumber;
int firstnumber, secondnumber, thirdnumber,
int firstnumber;
fourthnumber, fifthnumber;
int secondnumber;
How can we define 100 variables or 1000 variables in one line ? int thirdnumber;
How can we several values and the variable can take on value only? int fourthnumber;
int fifthnumber; 3
Arrays
• int x;
x is a variable of type integer
• It can store one value at a time
x=10; x=5;
• Sometimes, we need a list of values
Names of Employees
Scores of students
Serial numbers of computers
…
How can we several values and the variable can take on value only?
Solution is to create an Array
4
Create Arrays
• The solution is to use or create an array. It stores a collection of values, of the same
datatype.
– Every slot in the array can take a value and this slot has an address called
(index)
Array of 3 variables 0 0 0
index 0 index 1 index 2
5
Arrays Declaration and Allocation
• To declare a variable, we use the datatype followed by a variable. (int Number;)
• To define an array, we use the datatype followed by the square brackets and the
name of the array
int [] Numbers;
– Declare an array of integers, named Numbers
Numbers= new int [6];
– Allocate memory for this array to store 6 elements
0 0 0 0 0 0
index 0 index 1 index 2 index 3 index 4 index 5
– The declaration and allocation of the array can be performed on one line only.
int[] Numbers = new int [6];
6
Different types of Array Declaration
• int[] numbers;
– OR
• int numbers[];
• int[] numbers, codes, scores;
– OR
• int numbers[], codes[], scores[];
7
Arrays Declaration and Allocation
• float[] temperatures = new float[100];
create an array called temperature with datatype (float) and it consists of
100 variables starting with index 0 to 99.
• char[] letters = new char[41];
create an array called letters with datatype (char) and it consists of
41 variables starting with index 0 to 40.
• long[] units = new long[50];
create an array called units with datatype (long) and it consists of
50 variables starting with index 0 to 49.
• double[] sizes = new double[1200];
create an array called sizes with datatype (double) and it consists of
1200 variables starting with index 0 to 1199.
8
Array length
• Must be non-negative
int [] x = new int [-5]; // syntax error
• Must be positive integer and it should not be a decimal number
int [] x = new int [6.7]; // syntax error
• Literal, constant, or variable
int[] N=new int[10];
final int Asize = 1; int[] N=new int[Asize];
int Asize = 5; int[] N=new int[Asize];
• Any array size is fixed and can’t change after creation
9
Accessing an Array
• Name and index
– int[] numbers=new int[6];
– numbers[3]=10;
– System.out.println(“Fourth Element: “+numbers[3]);
0 0 Index:0 0 to Size-1
10 0 0
numbers[0] numbers[1] numbers[2] numbers[3] numbers[4] numbers[5]
Fourth Element: 10
10
Processing Arrays contents
• An array element is treated as a variable
– hours[3]=12;
– grossPay = hours[3] * payRate;
– if(cost[20] < cost[0]) {…}
– while(value[count] != 0) {…}
11
Array Initialization
Variable Initialization
• int number = 10;
• float price = 13.4;
• int[] days = {31,28,31,30,31,30,31,31,30, 31,30,31};
– days[0] is assigned 31,
– days[1] is assigned 28,
– days[2] is assigned 31,
– days[3] is assigned 30, • int [] numbers = new int[] {3,5,31,12,42}; Or
• int [] numbers; numbers = new int [] {3,5,31,12,42};
– numbers[0] is assigned 3,
– numbers[1] is assigned 5,
– numbers[2] is assigned 31,
– numbers[3] is assigned 12,
– numbers[4] is assigned 42, 11
Array Length
• The length of the array can be computed
– double[] temperatures = new double[25];
– int length = temperatures.length;
for(int i = 0; i < temperatures.length; i++)
{
System.out.println("Temperature " + i ": "
+ temperatures[i]);
}
11
Printing Arrays
• Printing a Variable
int first number = 10; System.out.print (firstnumber);
• Printing an Array
int [] numbers = {4,6,1,4,1,12};
System.out.print (numbers); // Wrong with arrays
• The solution is using loops:
for(int i = 0; i < numbers.length; i++){
System.out.print(numbers[i]);
}
14
Inputting Arrays
• Inputting a Variable
Scanner keyboard = new Scanner (System.in);
int firstnumber; firstnumber = keyboard.nextInt();
• Inputting an Array
int [] numbers = new int [5];
System.out.print (numbers); // Wrong with arrays
• The solution is using loops:
for(int i = 0; i < numbers.length; i++){
numbers [i] = keyboard.nextInt();
}
15
Copying Arrays
• Copying a Variable
int x = 10; int y = 20;
x = y;
• Copying an Array
int [] firstarray = {4,5,3,2,1};
int [] secondarray = {7,4,2,5,2};
secondarray = firstarray; // Wrong copy to the array
• The solution is using loops:
for(int i = 0; i < secondarray.length; i++){
secondarray [i] = firstarray [i];
}
16
Comparing Arrays
• Comparing a Variable
int x = 10; int y = 20;
if(x == y) {System.out.println{“x equals y”);}
• Comparing an Array
int [] firstarray = {4,5,3,2,1};
int [] secondarray = {7,4,2,5,2};
if (firstarray == secondarray) {
// Wrong comparison to the arrays
}
• The solution is using loops:
for(int i = 0; i < secondarray.length; i++){
if (secondarray[i] == firstarray[i]) {
}
17
}
For each
• The for-each loop is a simplified way to loop through arrays or collections
for (Type element : array) {
// use element }
• Type is the data type of the array elements (e.g., int, String)
• Element is a temporary variable for the current item
• array is the array you are looping over
int[] numbers = {10, 20, 30}; String[] names = {"Ali", "Sara", "Zein"};
for (int num : numbers) { for (String name : names) {
System.out.println(num); } System.out.println(name); }
Each loop: Each iteration:
•num takes one value from numbers • name becomes one element of the array
•Prints the value • You print it
18
Summing Array Elements
• Let’s consider that we have an array of units. This array consists of seven elements
(5, 3, 11, 15, 6, 2, 1) and we want to get the summation of these elements in a
variable called total.
int [] units = {5,3,11,15,6,2,1};
int total = 0; // Initialize accumulator
for (int i = 0; i < units.length; i++)
total += units[i];
System.out.println(total);
19
Average Array Elements
• Let’s consider that we have an array of scores. This array consists of six elements (60,
34, 70, 90, 83, 94) and we want to get the summation of these elements in a variable
called total and get the average.
double total = 0; // Initialize accumulator
double average; // Will hold the average
double [] scores = {60,34,70,90,83,94};
for (int i = 0; i < scores.length; i++)
total += scores[i];
average = total / scores.length;
System.out.print(average);
20
Finding largest Value in the Array
• Let’s consider that we have an array of number. This array consists of six elements
(57,4,35,2,12) and we want to get the highest or the maximum of these elements in
a variable called highest.
int [] numbers = {57,4,35,2,12};
int highest = numbers[0];
for (int i = 1; i < numbers.length; i++)
{
if (numbers[i] > highest)
highest = numbers[i];
}
System.out.print(highest);
21
Finding Smallest Value in the Array
• Let’s consider that we have an array of number. This array consists of six elements
(57,4,35,2,12) and we want to get the lowest or the smallest of these elements in a
variable called lowest.
int [] numbers = {57,4,35,2,12};
int lowest = numbers[0];
for (int i = 1; i < numbers.length; i++)
{
if (numbers[i] < lowest)
lowest = numbers[i];
}
System.out.print(lowest).
22
Shifting Arrays
• Write a program that Scanner keyboard = new Scanner(System.in);
int[] arr = {5, 10, 9, 17, 20};
takes an array and then System.out.println("Please enter the number of
shift this array left in a shifts");
int number_of_shifts = keyboard.nextInt();
circular way. The numbers for (int i = 0; i < arr.length; i++) {
of shifts should be System.out.print(arr[i] + " ");
}
determined by the user System.out.println("");
as an input. It is required int temp;
for (int j = 1; j <= number_of_shifts; j++) {
to print the original array temp = arr[0];
and each time the array is for (int i = 1; i < arr.length; i++) {
arr[i - 1] = arr[i];
shifted to the left. It is }
important to keep the arr[arr.length - 1] = temp;
for (int i = 0; i < arr.length; i++) {
values of the array. System.out.print(arr[i] + " ");
}
System.out.println("");
}
23
Reverse Arrays
• Write a program that reverse the array in the same array. In other words, consider an array
that consists of (5, 6, 3, 25, 12, 43) and it should be reversed to be (5, 6, 3, 25, 12, 43) in the
same array.
int[] arr = {5, 6, 3, 25, 12, 43};
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println("");
for (int i = 0, j = arr.length - 1; i < arr.length && j >= 0; i++, j--) {
if (i >= j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println("");
24
Search Arrays
• Write a program that take an array with the following values (5, 6, 3, 25, 12, 43). The
program should search for an item in the array. This item should be input from the user. If
the item is found that it should print “found” and get its index otherwise it will print “Not
found”. Scanner S = new Scanner(System.in);
System.out.println("Please enter a search item");
int searchitem = S.nextInt();
boolean found = false;
int itemindex = 0;
int [] arr = {5, 6, 3, 25, 12, 43};
for(int i = 0; i < arr.length; i++){
if(searchitem == arr[i]){
found = true;
itemindex = i;
break;
}
}
if(found == true){
System.out.println("The item is found at index " + itemindex);
}else{
System.out.println("Not found");
}
25
Sort Array
• Write a program that take an array with the following values (5, 6, 3, 25, 12, 43). The
program should print the array sorted in the following manner (3, 5, 6, 12, 25, 43).
int [] arr = {6,5,3,62,15,2,12};
int min;
int minindex = 0, temp;
for(int i = 0; i < arr.length; i++){
min = arr[i];
for(int j = i; j < arr.length; j++){
if(arr[j] <= min){
min = arr[j];
minindex = j;
}
}
temp = arr[i];
arr[i] = arr[minindex];
arr[minindex] = temp;
}
for(int i = 0; i < arr.length; i++){
System.out.print(arr[i] + " ");
}
26