0% found this document useful (0 votes)
13 views31 pages

Lec 6

The document provides a comprehensive overview of arrays in Java, detailing their characteristics, types (single-dimensional and multi-dimensional), and methods for declaration, memory allocation, and initialization. It also covers accessing array elements, the use of the length property, and the for-each loop for iteration. Additionally, it includes examples of common array operations such as finding maximum and minimum values, calculating sum and average, searching, reversing, and sorting arrays.

Uploaded by

thakurparth270
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views31 pages

Lec 6

The document provides a comprehensive overview of arrays in Java, detailing their characteristics, types (single-dimensional and multi-dimensional), and methods for declaration, memory allocation, and initialization. It also covers accessing array elements, the use of the length property, and the for-each loop for iteration. Additionally, it includes examples of common array operations such as finding maximum and minimum values, calculating sum and average, searching, reversing, and sorting arrays.

Uploaded by

thakurparth270
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 31

Working with Arrays

• An array in Java is a data structure that allows you to store multiple values
of the same type in a single variable. Instead of declaring individual
variables for each value, you can use an array to group them together and
access them using their index.

• Key Features of Arrays in Java


• Fixed Size: Once an array is created, its size cannot be changed.
• Homogeneous: All elements in an array must be of the same data type.
• Zero-based Indexing: Array indexing starts from 0 (the first element is at
index 0).
• Efficient Access: Elements in an array can be accessed quickly using their
index.
• Stored in Contiguous Memory: Arrays are stored in contiguous memory
locations, which makes element access faster.
Types of array

• Array can be categorized into two categories -


1- Single Dimensional Array.
2- Multi Dimensional Array.

• 1- Single Dimensional Array -


• An array which contains only one subscript or dimension is
called single dimensional array. Creation of array involve
following three steps-
Declaring array.
• Allocating memory to array.
• Initializing array.
• Declaring Array - In java array can be declared in two ways -

• 1st form - type array_name[ ];
• 2nd form - type [ ] array_name;

• Here type can be any valid java data type or object type,
array_name can be any valid java identifier that you want to use for
your array name.

• For example -
• int arr[ ];
• float numbers[ ];
• double [ ] roll;

• At this step, there will be no physical array in memory. Right now


array_name will refer to null and does not contain any value.
• Allocating memory to array - Array will came into physical
existence after allocating memory to it. And we allocate
memory to array using new keyword as follows -
• array_name = new type[array_size];
• Here type should be the same as used in declaration and
array_size determines the number of elements array can
contain and it can be any integer value greater than zero.
• For example -
• arr = new int[5];
• numbers = new float[10];
• roll = new double[5];

• The first example will allocate 20 bytes (5*4 = 20) of storage for
array - 'arr'. Similarly second one will allocate 40 (10*4 = 40)
bytes and third one will allocate 40 (5*8=40) bytes.
• We can also combine the above two steps into one as follows
• int arr[] = new int[5];
• float numbers[] = new float[10];
• double[] roll = new double[5];
• Initializing array - Let us suppose that we have an array a with
5 integer elements -
int a[] = new int[5];
• It can be represent in memory like this -
• We can initialize an array in two ways -
• 1st form -
• array_name[index] = value;

• Example -
• int[0] = 2;
• int[1] = 4;
• int[2] = 6;
• int[3] = 8;
• int[4] = 10;

• 2nd form -
• type array_name[] = {list of values};
• Or
• type array_name[] = new type[]{list of values};
• Example -
• int a[] = {2,4,6,8,10};
• int a[] = new int[]{2,4,6,8,10}; // both are same
• Here array will be big enough to hold the number of elements
defined in braces { }. That is, in both the cases an array of 5 int
elements will be created and it can be represented in memory as
follows –

• In java array index always starts from 0. And also we cannot store
more values than the size of array, if we try to do that , a runtime
exception 'Array Index Out Of Bound' will occur. We can also assign
an array into another array as follows -
• int arr[] = {1,2,3,4};
• int b[];
• b = arr;
• Now array arr and b will point to the same int object and contain
same values.
• Accessing Array Elements - We can access array elements by using array index as follows
• int x = a[2];
• The above statement will take the 3rd element (element at 2nd index) of array "a" and assign to
variable x. So the value of x will be 6.

• Example –
Example -
Putting together all the above code, here is the program that create, initialize and access the array.
public class Call {

public static void main(String[] args) {

int a[] = new int[5]; // declaring and allocating memory


System.out.println("Enter array elements");
for(int i=0;i<5;i++) // Normally we use loop to initialise array.
{
a[i] = Integer.parseInt(System.console().readLine());
}
for(int i =0;i<5;i++)
{
System.out.println(a[i]);
}
}
}
• length property -
• We can find the size of an array by using length property as follows -
• array_name.length;
• It will return allocated size of array.
• Example 1 -
public class Call {

public static void main(String[] args) {

int a1[] = new int[5];


int[] a2 = new int[10];
double a3[] = {1.1,2.1,3.1,4.1};
char[] a4 = {'a','b'};
System.out.println("Length of a1 array = "+ a1.length);
System.out.println("Length of a2 array = "+ a2.length);
System.out.println("Length of a3 array = "+ a3.length);
System.out.println("Length of a4 array = "+ a4.length);

}
}
• Example 2 -
public class Call {

public static void main(String[] args) {

int a[] = new int[5];


for(int i=0;i< a.length;i++)
{
a[i] = Integer.parseInt(System.console().readLine());
}
for(int i =0;i< a.length;i++)
{
System.out.println(a[i]);
}
}

}
• for each loop -
• This style of for loop is added in jdk1.5. It is mainly used to iterate through the elements of
arrays and collections. It is called "for each" because it iterate through each element of
array or collection.
• Syntax -
• for(data_type:array|collection name)
• Here data_type should be of the same type as data type of elements of array or collection.
For example if array contains integer type elements then data_type should be integer and
if it contains some object type element then data_type should be of that type.
• Example -
public class Call {
public static void main(String[] args) {

int a[] = {1,2,3,4,5};


System.out.println("Array elements are :");
for(int i : a)
{
System.out.println(i);
}
}
}
2 - Multidimensional Array -

• An array which has more than one dimension is called multidimensional array.
• Double Dimensional Array (2D array) - 2D Array is the most general form of
multidimensional array. It contains 2 dimensions, first dimension represents the
number of rows and second one represents number of columns in each row. It
is also called matrix or table. We can declare an array as follows -
• data_ type array_name[ ][ ];
• Here type can be any valid java data type and array_name will be any valid java
identifier. For example -
• int arr[ ][ ];
• Here we define a 2D array of integers named arr.
• A 2D Array can be declared using any of the following forms -
• 1- data_type array_name[ ][ ]; for example - int arr[ ][ ];
• 2- data_type[ ] array_name[ ]; for example - int[ ] arr[ ];
• 3- data_type[ ][ ] array_name; for example - int [ ][ ] arr;
• All the statements are equivalent; you can use any of them.
We can allocate memory to array arr as follows -
• arr = new int[3][4];
• This statement define an array arr containing 3 rows and 4
columns and will allocate 48 byte (3*4 = 12(elements)*4 = 48
bytes) of memory storage to array arr. It can be represented
as follows -
• Initializing 2D Array - We can initialize a 2D Array either one by one or by using a single statement as follows -
• Example 1 -
public class Call
{
public static void main(String[] args) {

int arr[][] = new int[2][3];


System.out.println("Enter array elements");

// Initialising Arry elements one by one


for(int r=0; r < arr.length; r++) // arr.length will return the number of rows in arr
{
for(int c=0; c < arr[r].length;c++) // arr[r].length will return the number of columns in each row r.
{
arr[r][c] = Integer.parseInt(System.console().readLine());
}
}

// Accessing array elements -


for(int r[]: arr) // It will return and copy a complete row in array r of integers at a time.
{
for(int c : r) // It will return each columns in row r and copy that in c.
{
System.out.print(c);
}
System.out.println();
}

• Note - for accessing the array elements we can either use for each loop style as we use above or we can use simple for loop style as used to initialize
array elements.
• Example 2
public class Call {

public static void main(String[] args) {

// Declaring and initialising array


int arr[ ][ ] = {{1,2,3}, // This will declare an array containing 2 rows and 4 columns.
{4,5,6}};

// Accessing array elements -


for(int r[]: arr)
{
for(int c : r)
{
System.out.print(c);
}
System.out.println();
}
}
}
Jagged Array

• A jagged array in Java is a 2D array where the rows can


have different lengths. Unlike a regular 2D array, where all
rows have the same number of columns, a jagged array
allows each row to have a variable number of elements.
• Following is the declaration of jagged array containing 4
elements each of which is a 1D array of integers -
• Int arr[ ][ ] = new int[4][ ];
• arr[0] = new int[3];
• arr[1] = new int[4];
• arr[2] = new int[2];
• arr[3] = new int[1];
• Here array arr contain 4 elements (row), first element is an array arr[0]
containing 3 elements (columns) , second element is an array arr[1]
containing 4 elements and so on.
• We can also declare and initialise a jagged array in single line as follows
-
int arr[][] = {{1,2,3},
{4,5,6,7,8},
{10,11}};

• A jagged array arr containing 3 rows, 1st row containing 3 elements, 2nd
row containing 4 elements, 3rd row containing 2 elements.
• Example -
public class Call {

public static void main(String[] args) {

int arr[][] = {{1,2,3},


{4,5,6,7,8},
{10,11}};
System.out.println("Array elements are :-");

for(int r=0;r< arr.length;r++)


{
for(int c=0;c< arr[r].length;c++)
{
System.out.print(arr[r][c]+" ");
}
System.out.println();
}
}

}
• Practice Problems –
• Find Maximum and Minimum in an Array-
public class MaxMinArray {
public static void main(String[] args) {
int[] numbers = {12, 4, 19, 33, 7};
int max = numbers[0];
int min = numbers[0];

for (int num : numbers) {


if (num > max) max = num;
if (num < min) min = num;
}

System.out.println("Maximum: " + max);


System.out.println("Minimum: " + min);
}
}
• Sum and Average of Array Elements –
public class SumAverage {
public static void main(String[] args) {
int[] numbers = {5, 10, 15, 20, 25};
int sum = 0;

for (int num : numbers) {


sum += num;
}

double average = (double) sum / numbers.length;


System.out.println("Sum: " + sum);
System.out.println("Average: " + average);
}
}
• Search an Element – (Linear Search)
public class SearchArray {
public static void main(String[] args) {
int[] numbers = {3, 8, 15, 6, 11};
int target = 15;
boolean found = false;

for (int i = 0; i < numbers.length; i++) {


if (numbers[i] == target) {
System.out.println("Element found at index: " + i);
found = true;
break;
}
}

if (!found) {
System.out.println("Element not found");
}
}
}
• Reverse an Array –
public class ReverseArray {
public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4, 5};

System.out.println("Original array:");
for (int num : numbers) {
System.out.print(num + " ");
}

System.out.println("\nReversed array:");
for (int i = numbers.length - 1; i >= 0; i--) {
System.out.print(numbers[i] + " ");
}
}
}
• Sort an Array (Bubble Sort) –
• Bubble Sort is a simple sorting algorithm that repeatedly steps
through the array, compares adjacent elements, and swaps them if
they are in the wrong order. This process is repeated until the array is
sorted.
• Steps of Bubble Sort:
• Start with the first element of the array.
• Compare the current element with the next one:
– If the current element is greater than the next, swap them.
– Otherwise, leave them as is.
• Move to the next pair of elements and repeat the comparison.
• Continue until the end of the array, completing one "pass."
• After each pass, the largest unsorted element "bubbles" to its correct
position.
• Repeat the process for the remaining unsorted portion of the array
until no swaps are needed (the array is sorted).

• Unsorted Array: {5, 3, 8, 6, 2}
• Pass 1:
• Compare 5 and 3 → Swap → {3, 5, 8, 6, 2}
• Compare 5 and 8 → No Swap → {3, 5, 8, 6, 2}
• Compare 8 and 6 → Swap → {3, 5, 6, 8, 2}
• Compare 8 and 2 → Swap → {3, 5, 6, 2, 8}
• After Pass 1: The largest element 8 is in its correct position.
• Pass 2:
• Compare 3 and 5 → No Swap → {3, 5, 6, 2, 8}
• Compare 5 and 6 → No Swap → {3, 5, 6, 2, 8}
• Compare 6 and 2 → Swap → {3, 5, 2, 6, 8}
• After Pass 2: The second largest element 6 is in its correct position.
• Pass 3:
• Compare 3 and 5 → No Swap → {3, 5, 2, 6, 8}
• Compare 5 and 2 → Swap → {3, 2, 5, 6, 8}
• After Pass 3: The third largest element 5 is in its correct position.
• Pass 4:
• Compare 3 and 2 → Swap → {2, 3, 5, 6, 8}
• After Pass 4: The array is fully sorted.
public class BubbleSortExample {
public static void main(String[] args) {
int[] numbers = {5, 3, 8, 6, 2};

System.out.println("Original Array:");
for (int num : numbers) {
System.out.print(num + " ");
}

// Bubble Sort Algorithm


for (int i = 0; i < numbers.length - 1; i++) {
boolean swapped = false; // Track if any swaps occurred in this pass

for (int j = 0; j < numbers.length - i - 1; j++) {


if (numbers[j] > numbers[j + 1]) {
// Swap numbers[j] and numbers[j + 1]
int temp = numbers[j];
numbers[j] = numbers[j + 1];
numbers[j + 1] = temp;
swapped = true;
}
}

// If no swaps occurred, the array is already sorted


if (!swapped) {
break;
}
}

System.out.println("\nSorted Array:");
for (int num : numbers) {
System.out.print(num + " ");
}
}
}
• Find the Second Largest Element
• Initialize two variables:
– largest to hold the largest element.
– secondLargest to hold the second largest element.
• Traverse the array:
– If the current element is greater than largest,
update secondLargest to largest and then update
largest to current element.
– If the current element is not equal to largest and
greater than secondLargest, update secondLargest.
• At the end of the traversal, secondLargest will
contain the second largest value.
public class SecondLargest {
public static void main(String[] args) {
int[] numbers = {12, 35, 1, 10, 34, 1};

// Edge case: Ensure the array has at least two elements


if (numbers.length < 2) {
System.out.println("Array must have at least two distinct elements.");
return;
}

// Initialize variables
int largest = Integer.MIN_VALUE;
int secondLargest = Integer.MIN_VALUE;

// Traverse the array


for (int number : numbers) {
if (number > largest) {
// Update secondLargest before updating largest
secondLargest = largest;
largest = number;
} else if (number > secondLargest && number != largest) {
// Update secondLargest if number is smaller than largest but greater than secondLargest
secondLargest = number;
}
}

// Check if secondLargest was updated


if (secondLargest == Integer.MIN_VALUE) {
System.out.println("No second largest element found (all elements are equal).");
} else {
System.out.println("The second largest element is: " + secondLargest);
}
}
}
• Binary Search –
• Binary Search is an efficient algorithm for finding an element in a sorted
array. The main idea is to repeatedly divide the search interval in half:
• Initial Step: Start with the middle element.
• Comparison:
– If the middle element is the target, return its index.
– If the target is smaller than the middle element, the target must be in the left
half of the array, so update the right pointer to be the element just before the
middle.
– If the target is larger than the middle element, the target must be in the right
half of the array, so update the left pointer to be the element just after the
middle.
• Repeat the process until the left pointer surpasses the right pointer,
which means the element is not present in the array.
• Conditions for Binary Search:
• The array must be sorted.
• It works on both ascending and descending sorted arrays, but you need
to handle the comparison conditions appropriately.
public class BinarySearchWithoutFunction {
public static void main(String[] args) {
// Sorted array
int[] numbers = {1, 3, 5, 7, 9, 11, 13, 15, 17, 19};

// Target element to search


int target = 7;

// Initialize left and right pointers


int left = 0;
int right = numbers.length - 1;
int mid = 0;
boolean found = false;

// Perform binary search


while (left <= right) {
// Find the middle index
mid = (left + right) / 2;

// If the target is found at mid


if (numbers[mid] == target) {
System.out.println("Element " + target + " found at index " + mid);
found = true;
break; // Exit the loop if found
}
// If target is smaller than mid element, narrow the search to the left half
else if (numbers[mid] > target) {
right = mid - 1;
}
// If target is larger than mid element, narrow the search to the right half
else {
left = mid + 1;
}
}

// If element is not found


if (!found) {
System.out.println("Element " + target + " not found in the array.");
}
}
}

You might also like