0% found this document useful (0 votes)
3 views14 pages

Notes X Java Arrays SS

The document provides a comprehensive overview of arrays in Java, including their definition, features, types (single and multi-dimensional), and how to create and manipulate them. It explains key operations such as searching (linear and binary search) and sorting (bubble sort and exchange selection sort), along with example programs for practical understanding. Additionally, it covers the structure of two-dimensional arrays and the concept of diagonals in square matrices.

Uploaded by

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

Notes X Java Arrays SS

The document provides a comprehensive overview of arrays in Java, including their definition, features, types (single and multi-dimensional), and how to create and manipulate them. It explains key operations such as searching (linear and binary search) and sorting (bubble sort and exchange selection sort), along with example programs for practical understanding. Additionally, it covers the structure of two-dimensional arrays and the concept of diagonals in square matrices.

Uploaded by

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

Arrays

An array can be imagined as a collection of variables, all having a common name. Java array is
a collection of elements of a similar data type. In the RAM the elements of an array are stored
in a continuous memory location.

Suppose you have to store marks of 100 students. You will need 100 variables. It will be
difficult to name the variables and to remember the names. With arrays, you can store 10 or
50 or 100 or 1000 etc. values under a single name.

An array can be represented as a series of values arranged serially as shown below.

Features of Arrays

1. Array in Java is index-based. Like in Strings, the first element of the array is stored at the
index Number 0, 2nd element is stored at index no. 2 and so on.
2. An array name is written as: a variable name followed by a set of square brackets [ ].
Suppose our array name if ‘a’, we write the array as a[ ].
3. Like each house of colony is identified by its unique address, similarly each cell of an array
is identified by what is called Cell Reference or Cell Address.
4. The Cell Reference or Cell Address is the name of the array followed by the index number
of the cell in square brackets.
For example: the first element of the array is represented as a[0] (called ‘a of 0’), 2nd
element is a[1] ( called as ‘a of 1’ ) and so on.
5. Like we have the length of a String, we have the size of the array. The size of the array is an
integer (int) value.
To know the number of characters in a String, we have the length() function, and we write:
int len = s.length();

Similarly to know the number of cells in a array we write as:


int l = a.length;
That is ‘length’ without a set of brackets.

6. IMPORTANT POINT : So it is understood, that the last cell of an array will have the index
number equal to one less than its length( like in Strings).

Need of Arrays:
As a number of values are referred by a single name, it is easier to remember the array names

Types of Arrays
We have Single and MultiDimensional Arrays. MultiDimensional Arrays are 2D and 3D arrays.
We will only work on Single and 2D arrays.

SINGLE DIMENSIONAL ARRAY

Below is an example to Single dimensional array.

The elements or cells are arranged in a line represented horizontally or vertically. Each cell is
referenced by its Cell Address.

DOUBLE DIMENSIONAL ARRAY

Below is an example to Double dimensional array.


Here we have cells arranged in horizontal rows and vertical columns. The index numbers of
rows and columns starts with 0 (Zero). So the cell address consists of the array name followed
by row number and column number as shown above.

Creating ( Declaring )Arrays


You can create or declare an array by using the new operator with the following syntax –
Single Dimension

Syntax
dataType arrayName[] = new dataType[arraySize];
Example : int a[ ] = new int[ 10 ];

Here an array of name ‘a’ is declared of ‘int’ type which is of size 10, that is it can hold 10
integer numbers.

Double Dimension
Syntax
dataType arrayName[][] = new dataType[NoOfRows][NoOfCols];
Example : int m[ ][ ] = new int[ 3 ][ 4 ];

Here an array of name ‘m’ is declared of ‘int’ type which 3 rows and 4 columns.
What is /n and /t ?

First we will work only on SINGLE DIMENSIONAL ARRAYS.

Suppose we have to store natural numbers in an array. We can write:

a[ 0 ] = 1 ;
a[ 1 ] = 2 ;
a[ 2 ] = 3 ;
a[ 3 ] = 4 ;
a[ 4 ] = 5 ;
and so on…..
What happens for 50 or 1000 values? We have to write so many lines….

So instead we write this assignment in a loop as shown in the following example:

Now, a simple question

Q: Write a program to declare an array of size 10, store first 10 Natural Numbers in it, and
print the array.

import java.io.*;
public class arrfirst
{
public static void main(String args[]) throws IOException
{
int a[ ]= new int[10];
int x;
for( x = 0 ; x <= 9 ; x++ )
{
a[x] = x+1;
}

for( x = 0 ; x <= 9 ; x++ )


{
System.out.print(a[x] + " ");
}
}
}

V Important Note:
In the above example we have used 2 for loops. It can be done in one loop, BUT IT IS NOT
DONE LIKE THAT. It could be done in one loop here, but not possible in other examples of
arrays. As we go on with the examples, you will understand.
Now try this program:
Q. Write a program to declare an array of size 10, input values into it and print the largest and
smallest numbers in the array.

We have two important operations in arrays:


Searching and Sorting.

Searching is done by two types:


Linear Search and Binary Search

Sorting is also done by two types:


Bubble Sort and Exchange Selection Sort.

SEARCHING
As the name suggests, Searching means to input a value (called search value) and look if it is
present in the array. The search value is matched with the cells of the array. If the value is
found, then the search operation is successful, otherwise it fails.

TYPES OF SEARCHING

LINEAR SEARCH:
Here the search value is matched with each and every value in the cells. The matching starts
with the leftmost cell and one-by-one proceeds towards the right cell. If the search value is
found, the operation is stopped and further cells will not be checked. If the search value is not
found in any of the cells, a message ig given as “Search Value not found”.

Concept of Flag in Programming


Flag is not a reserved word, but is a variable used as a signal. It acts as a switch – OFF or ON.
For example in a set of numbers there is a condition, which we know, will be true only for a
single value in that range. First we initialize the value of ‘flag’ to 0 (zero ie OFF). We run the
loop for that range. If that condition is met, we store 1 to ‘flag’ (ie success or ON). At the end
of the loop, we check the value of ‘flag’. If ‘flag’ value is 1, then we know the condition was
met. If the value didn’t change from 0, we know, the condition was never met with.

Program of Linear Search uses the concept of flag.


// Find search Value in an Array
// by Linear Search Technique

import java.io.*;
public class arrlinearsrch
{
public static void main(String args[]) throws IOException
{

int a[]= new int[10]; // Declaring an array


int x, m, flag=0;

Scanner sc = new Scanner(System.in);


System.out.println("Enter 10 values ... ");

for(x=0; x<=9; x++)


{
a[x]=sc.nextInt(); // Inputting values
into the array
}

System.out.println("Enter number to searched ");


m=sc.nextInt();

for(x=0; x<=9; x++)


{
if(a[x] == m)
{
flag=1;
break;
}
}
if(flag==1)
System.out.println("Number found at position : "+ x+1);
else
System.out.println("Sorry. Search Value NOT Found");
}
}

BINARY SEARCH
The most important condition for this type of search is the array should be sorted, that is the
values of the array must be arranged in either the ascending or descending order.
In this type of search, the array is divided into two (binary is two) halves. The leftmost cell is
the Lower value (denoted by L), and the rightmost cell is the Upper value (denoted by U). The
center cell is the Middle cell (denoted by M).

Search Method: First search value is compared with the middle cell. If it is there, our search is
successful.
If the search value is less than the item in the middle cell, it means that our value lies in the
left half. (Because the array is sorted). Consequently the cells in the right half are ignored
because the values will not be there.
Similarly, if the search value is more than the item in the middle cell, it means that our value
lies in the right half. (Because the array is sorted). Consequently the cells in the left half are
ignored because the values will not be there.

// Program to depict the usage of Binary Search Technique.


// It is assumed that the list of numbers in an array is stored in
// ascending order.

import java.io.*;
class binsearch3
{
public static void main(String args[]) throws IOException
{
int num[] =new int[10];
int m,L,U,mid=0,pos;

Scanner sc = new Scanner(System.in);


System.out.print("\nEnter any ten numbers as elements of an array in");
System.out.println(" ascending order ");
for (int i=0;i<10;i++)
{
num[i]=sc.nextInt();
}
System.out.println("Enter number to searched ");
m=sc.nextInt();
L = 0;
U = 9;
pos = -1;
int flag=0;
while ((L<= U))
{
mid = (L+U)/2;
if (num[mid] == m)
{
flag=1;
break;
}
else
if (num[mid]<m)
L = mid + 1;
else
U = mid - 1;
}
if (flag==1)
{
System.out.print("The element "+m+" lies in the array");
System.out.println(" at "+ (mid+1) +" position");
}
else
System.out.println("The element does not lie in the array");
}
}

SORTING
Sorting means to arrange the values in a certain order, either ascending or descending.

BUBBLE SORT TECHNIQUE

Visualization
https://www.youtube.com/watch?v=Cq7SMsQBEUw
Bubble sort is an algorithm that compares the adjacent elements and swaps their positions if
they are not in the intended order. The order can be ascending or descending.
How Bubble Sort Works?
Starting from the first index, compare the first and the second elements. If the first element is
greater than the second element, they are swapped.

Now, compare the second and the third elements. Swap them if they are not in order.

The above process goes on until the last element.

The same process goes on for the remaining iterations. After each iteration, the largest
element among the unsorted elements is placed at the end.
In each iteration, the comparison takes place up to the last unsorted element.

The array is sorted when all the unsorted elements are placed at their correct positions.

EXCHANGE SELECTION SORT TECHNIQUE

2D ARRAYS
Now let’s see the two dimensional arrays in detail. 2D arrays are also referred to as Matrices
(Matrix). We will call then DDA (Double Dimensional Array).
2D Arrays can be of following types:
SQUARE ARRAYS: Here the number of rows will be equal to number of columns.
RECTANGULAR ARRAYS: Here the number of rows and number of columns will be unequal.
As there are rows and columns in 2D arrays, we need nested loops for access the array.
In 2D arrays, we don’t say length, but we say size of the array.
For example, if we say size of the 2D array is 10x20 ( said as 10 by 20 ), it means the array has
10 rows and 20 columns. This array will be written as a[10][20].

Q: Write a program to declare an DDA of size 4x5, store Natural Numbers in it, and print the
array.

import java.io.*;
public class arrfirst
{
public static void main(String args[]) throws IOException
{
int a[][]= new int[4][5];
int r, c, t=1;
for( r = 0 ; r <= 3 ; r++ )
{
for( c = 0 ; c <= 4 ; c++ )
{
a[r][c] = t++;
}
}

for( r = 0 ; r <= 3 ; r++ )


{
for( c = 0 ; c <= 4 ; c++ )
{
System.out.print(a[r][c] + "\t");
}
}
}
}
DIAGONALS OF SQUARE MATRIX:
A square matrix has two diagonals.
Left Diagonal and Right Diagonal

Left Diagonal
The cell references of the left diagonal:
1. The row index is equal to the column index.
2. The cells above the left diagonal will have row index less than column index.
3. The cells below the left diagonal will have row index more than column index.

Right Diagonal
The cell references of the right diagonal:
1. The sum of the row index and column index is equal to the number of rows/columns minus
one.
2. The cells above the right diagonal will have sum of the row and column index less than
number of rows/columns minus one.
3. The cells above the right diagonal will have sum of the row and column index greater than
number of rows/columns minus one.
This is a table which shows the relation for the cells above, below, on and above,
on and below or on the Left and the Right diagonals:

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy