ARRAY
- 2 types of data: Primitive and Non Primitive
- Primitive: int, char, float, double
- Non Primitive/Composite: Array (derived from primitive)
What is an array?
- It's a data structure created in memory to store a large amount
of data.
Properties:
1) It has a fixed size.
2)The values are of similar type (either int, double, char or string).
3) The data can be accessed with the help of index number.
4)Index number always starts from 0.
5)If the size of array is n, then the index number starts from
0 to n-1.
6)The values are always stored in a linear fashion(means one
after other).
- Why need arrays?
For ex:
Topic: Array Prepared by Ashwini Y.
I want 10 numbers from a user and display those 10 numbers.
for(int i=1;i<=10;i++)
{
n=[Link]();
}
for(int i=1;i<=10;i++)
{
[Link](n);
}
What is the output??
Ans: Only the last number will be printed.
Arrays:
-
Here, a[0], a[1], a[2].. are known as subscripts/Index
numbers.
- 2 types of arrays:
1) Single dimensional array :
Topic: Array Prepared by Ashwini Y.
a[], here a is single subscripted variable
2)Double dimensional array:
a[][], here a is double subscripted variable
- Creating arrays: (Because it is non primitive, so we have to
create it)
int a[]=new int[10];
char c[]=new char[35];
double d[]=new double[20];
String s[]=new String[10];
- Storing and accessing array elements:
1) Using direct assignment:
int a[]={1,56,3,4,70};
2)Using parameterised input:
psvm(int a[])
3) Using scanner class:
int a[]=new int[10];
a[2]=5;
a[5]=a[2]*2;
- Note: The subscript/index number always starts from 0.
- Program: WAP to accept 10 numbers and then print them.
Ans: import [Link].*;
public class PrintNumbers
{
public static void main(String args[])
Topic: Array Prepared by Ashwini Y.
{
Scanner sc = new Scanner([Link]);
[Link]("Enter 10 numbers:");
int a[]=new int[10];
for(int i=0;i<10;i++)
{
a[i]=[Link]();
}
[Link]("Array Elements are:");
for(int i=0;i<10;i++)
{
[Link](a[i]);
}
}
}
- Program: Accept 10 numbers in Single Dimensional array.
Display the array elements at even subscript.
Ans: import [Link].*;
public class PrintNumbers
{
public static void main(String args[])
{
Scanner sc = new Scanner([Link]);
[Link]("Enter 10 numbers:");
int a[]=new int[10];
Topic: Array Prepared by Ashwini Y.
for(int i=0;i<10;i++) //i are the index numbers
{
a[i]=[Link]();
}
for(int i=0;i<10;i=i+2)
{
[Link](a[i]);
}
}
}
- Program: Accept 10 numbers in a single dimensional array.
Display the greatest number of the array.
Ans: import [Link].*;
public class PrintNumbers
{
public static void main(String[] args)
{
Scanner sc = new Scanner([Link]);
[Link]("Enter 10 numbers:");
int a[]=new int[10];
for(int i=0;i<10;i++)
{
a[i]=[Link]();
}
int max=a[0];//lets store the first value in max
Topic: Array Prepared by Ashwini Y.
for(int i=1;i<10;i++)// i=1 because max already has 0th value
{
if(a[i]>max)
{
max=a[i];
}
}
[Link](max);
}
}
- WAP to Find the Sum of 5 Array Elements.
import [Link].*;
class ArraySum
{
public static void main(String args[])
{
Scanner sc = new Scanner([Link]);
int a[] = new int[5];
int sum = 0;
[Link]("Enter 5 integers:");
for (int i = 0; i < 5; i++)
{
a[i] = [Link]();
sum += a[i];
}
[Link]("Sum of elements = " + sum);
}
Topic: Array Prepared by Ashwini Y.
}
- Program to Count Even and Odd Numbers in an Array of 10
elements.
import [Link].*;
class CountEvenOdd {
public static void main(String args[])
{
Scanner sc = new Scanner([Link]);
int a[] = new int[10];
int evenCount = 0, oddCount = 0;
[Link]("Enter 10 integers:");
for (int i = 0; i < 10; i++)
{
a[i] = [Link]();
if (a[i] % 2 == 0)
{
evenCount++;
}
else
{
oddCount++;
}
}
[Link]("Even numbers count = " + evenCount);
[Link]("Odd numbers count = " + oddCount);
}
}
Topic: Array Prepared by Ashwini Y.
- Program: Accept 10 numbers in SDA. Create another array to
store the squares of this array. Display both the arrays in the
given format:
Array 1 Array 2
4 16
3 9
. .
. .
5 25
Ans: import [Link].*;
public class PrintNumbers
{
public static void main(String[] args)
{
Scanner sc = new Scanner([Link]);
int a[]=new int[10]; //to store 10 numbers
int b[]=new int[10]; //to store their squares
[Link]("Enter 10 numbers in Array a:");
for(int i=0;i<10;i++)
{
a[i]=[Link](); //to input the numbers
b[i]=a[i]*a[i]; //to find their squares
}
[Link]("Array 1 \t Array 2");
for(int i=0;i<10;i++)
Topic: Array Prepared by Ashwini Y.
{
[Link](a[i]+"\t"+b[i]);
}
}
}
- Accept the name, physics, chemistry and math marks of
25 students. The display a list of the given data with
Total and Average.
import [Link].*;
class StudentMarks
{
public static void main(String args[])
{
Scanner sc = new Scanner([Link]);
String name[] = new String[25];
int physics[] = new int[25];
int chemistry[] = new int[25];
int maths[] = new int[25];
int total[] = new int[25];
double average[] = new double[25];
// Input section
for (int i = 0; i < 25; i++)
{
[Link]("Enter name of student " + (i + 1) + ":");
name[i] = [Link]();
[Link]("Enter Physics marks:");
physics[i] = [Link]();
Topic: Array Prepared by Ashwini Y.
[Link]("Enter Chemistry marks:");
chemistry[i] = [Link]();
[Link]("Enter Maths marks:");
maths[i] = [Link]();
total[i] = physics[i] + chemistry[i] + maths[i];
average[i] = total[i] / 3.0;
}
// Display section
[Link]("\n---------------------------------------------------------
-----");
[Link]("%-15s %-8s %-8s %-8s %-8s %-8s\n", "Name",
"Physics", "Chem", "Maths", "Total", "Average");
[Link]("------------------------------------------------------------
--");
for (int i = 0; i < 25; i++)
{
[Link]("%-15s %-8d %-8d %-8d %-8d %-8.2f\n",
name[i], physics[i], chemistry[i], maths[i], total[i],
average[i]);
}
}
}
—----------------------------------------------------------------------------------
Searching techniques:
Topic: Array Prepared by Ashwini Y.
1) Linear Search/sequential search
2)Binary Search
Linear Search Binary Search
1) It works on sorted and 1) It works only on sorted
unsorted, both types of array elements.
array elements.
2)Search begins at the start 2) An array is divided into halves
of an array. and then the desired data item
is searched either in the first half
or second half.
- Program: Input 10 numbers in [Link] enter a number and
search whether it is present in the given array or not using
linear search technique.
Ans: import [Link].*;
public class PrintNumbers
{
public static void main(String args[])
{
int n,flag=0;
Scanner sc = new Scanner([Link]);
int a[]=new int[10];
[Link]("Enter 10 numbers");
for(int i=0;i<10;i++)
{
a[i]=[Link]();
Topic: Array Prepared by Ashwini Y.
}
[Link]("Enter a number to search");
n=[Link]();
for(int i=0;i<10;i++)
{
if(a[i]==n)
{
flag=1; //flag is an indicator. It will be on and off
break;
}
}
if(flag==1)
{
[Link]("Search Successful");
}
else
{
[Link]("Search Unsuccessful");
}
}
}
- Program: Input 10 numbers in [Link] enter a number and
search whether it is present in the given array or not using
binary search technique.
Ans: import [Link].*;
public class PrintNumbers
{
Topic: Array Prepared by Ashwini Y.
public static void main(String args[])
{
int mid,n,flag=0;
Scanner sc = new Scanner([Link]);
int a[]=new int[10];
[Link]("Enter 10 numbers");
for(int i=0;i<10;i++)
{
a[i]=[Link]();
}
[Link]("Enter a number to search");
n=[Link]();
int l=0,u=9;//l is lower limit, u is upper limit
while(l<=u)
{
mid=(l+u)/2;
if(a[mid]==n)//if the middle number is same as n
{
flag=1;
break;
}
if(n>a[mid])//if n is bigger than middle number then shift l
{
l=mid+1;
}
Topic: Array Prepared by Ashwini Y.
if(n<a[mid])//if n is smaller than middle number then shift u
{
u=mid-1;
}
}
if(flag==1)
{
[Link]("Search Successful");
}
else
{
[Link]("Search Unsuccessful");
}
}
}
—----------------------------------------------------------------------------------
Sorting Techniques:
1)Selection Sort: This is a combination of searching and sorting.
It sorts the array by repeatedly finding the minimum
element(for ascending order).
2)Bubble Sort: This is a comparison- based algorithm, i.e
comparing each pair of adjacent items and swapping them, if
they are placed in the wrong order.
Selection Sort Bubble Sort
Finds smallest element & places it Swaps elements if they are
at correct position in wrong order
Topic: Array Prepared by Ashwini Y.
Moves the smallest element to the Moves the largest element
front to the end
Fewer swaps More swaps
- Program to arrange 10 numbers in ascending order using
selection sort.
Idea:
In each step, find the smallest number in the unsorted part of the
array and place it at the correct position.
How it works:
Suppose the array is:
[ 5, 3, 8, 1, 4 ]
Step Action Result
Step 1 Find the smallest number in the whole array (→ [ 1, 3, 8, 5, 4 ]
1) and swap with 1st element
Step 2 Find the smallest number in remaining part (→ [ 1, 3, 8, 5, 4 ]
3, already correct)
Step 3 Find the smallest in remaining (→ 4), swap with [ 1, 3, 4, 5, 8 ]
3rd element
Ans: import [Link].*;
public class PrintNumbers
Topic: Array Prepared by Ashwini Y.
{
public static void main(String args[])
{
Scanner sc = new Scanner([Link]);
int i,j,min,temp;
int a[]=new int[10];
[Link]("Enter 10 numbers");
for(i=0;i<10;i++)
{
a[i]=[Link]();
}
for(i=0;i<10;i++)
{
min=i;
for(j=i+1;j<10;j++) // for the next elements in the array.
{
if(a[j]<a[min])
{
min=j;
}
}
temp=a[i];
a[i]=a[min];
a[min]=temp;
}
Topic: Array Prepared by Ashwini Y.
[Link]("Sorted Array:");
for(i=0;i<10;i++)
{
[Link](a[i]);
}
}
}
- Program to arrange 10 numbers in ascending order using
bubble sort.
Idea:
Compare pairs of numbers and swap them if they are in the wrong
order.
Biggest numbers bubble up to the end of the array.
How it works:
Array:
[ 5, 3, 8, 1, 4 ]
We compare numbers in pairs:
● 5 & 3 → swap → [ 3, 5, 8, 1, 4 ]
● 5 & 8 → correct → [ 3, 5, 8, 1, 4 ]
● 8 & 1 → swap → [ 3, 5, 1, 8, 4 ]
● 8 & 4 → swap → [ 3, 5, 1, 4, 8 ]
Now 8 is at the end ✔ (largest number)
Topic: Array Prepared by Ashwini Y.
Next round:
Keep repeating until no swaps are needed.
Ans: import [Link].*;
public class PrintNumbers
{
public static void main(String args[])
{
Scanner sc = new Scanner([Link]);
int i,j,temp;
int a[]=new int[10];
[Link]("Enter 10 numbers");
for(i=0;i<10;i++)
{
a[i]=[Link]();
}
for(i=0;i<10;i++) // this is for no. of rounds
{
for(j=0;j<(9-i);j++) // this is for 2 adjacent elements
{ -i is used because we do not want to
compare with the last element.
if(a[j]>a[j+1])
{
temp=a[j];
a[j]=a[j+1];
Topic: Array Prepared by Ashwini Y.
a[j+1]=temp;
}
}
}
[Link]("Sorted Array:");
for(i=0;i<10;i++)
{
[Link](a[i]);
}
}
}
—----------------------------------------------------------------------------------
Double dimensional array:
- It is used to store the data in the form of rows and columns.
- m[3][4], here 3 are rows and 4 are columns.
Array Type Data Type Format
Integer array int int m[][]=new int[3][4];
Character array char char m[][]=new char[3][4];
String array String String m[][]=new String[3][4];
Floating point float float m[][]=new float[3][4];
array
- Storing and accessing array elements:
1) Using direct assignment:
int a[][]={{2,4,6},{5,6,7},{10,2,3}};
char c[][]={{‘a’, ‘c’},{‘d’, ‘e’},{‘r’, ‘t’}};
Topic: Array Prepared by Ashwini Y.
String s[][]={{“&”, “*”},{“%”, “#”}};
2)Using Scanner object:
Scanner sc=new Scanner([Link]);
int a[][]=new int[3][5];
for(int i=0;i<3;i++)//this is for rows
{
for(j=0;j<5;j++)//this is for columns
{
a[i][j]=[Link]();
}
}
- Program: Input integers in DDA of size 3x4. Display the
following:
i) Array in matrix format
ii) sum of all the elements
Ans: import [Link].*;
public class PrintNumbers
{
public static void main(String args[])
Topic: Array Prepared by Ashwini Y.
{
Scanner sc = new Scanner([Link]);
int a[][]=new int[3][4];
int i,j,sum=0;//i=rows,j=columns
[Link]("Enter elements:");
for(i=0;i<3;i++)
{
for(j=0;j<4;j++)
{
a[i][j]=[Link]();
sum=sum+a[i][j];
}
}
for(i=0;i<3;i++) //this for is to print the elements in matrix form
{
for(j=0;j<4;j++)
{
[Link](a[i][j]);
}
[Link]();
}
[Link]("Sum of all the elements: "+sum);
}
}
Topic: Array Prepared by Ashwini Y.
- Program: Input integers in DDA of size 4*3(4 rows and 3
columns).
Display the following:
a)Sum of each row
b)Sum of each column
Ans: import [Link].*;
public class matrix
{
public static void main(String args[])
{
Scanner sc=new Scanner([Link]);
int a[][]=new int[4][3];
int i,j,sumr,sumc;
[Link]("Enter elements:");
for(i=0;i<4;i++)
{
for(j=0;j<3;j++)
{
a[i][j]=[Link]();
}
}
//row-wise sum
for(i=0;i<4;i++)
{
Topic: Array Prepared by Ashwini Y.
sumr=0;//making sumr as 0 so that in every loop previous
value of sumr should not be repeated.
for(j=0;j<3;j++)
{
sumr=sumr+a[i][j];//in every iteration value of i will remain
same, j will change
}
[Link](sumr);
}
//column-wise sum
for(j=0;j<3;j++)
{
sumc=0;
for(i=0;i<4;i++)
{
sumc=sumc+a[i][j];//in every iteration value of j will remain
same, i will change
}
[Link](sumc);
}
}
}
- Program: WAP to input elements in 4X4 DDA. Calculate and
display
a)Sum of all elements in the left diagonal
b)Sum of all elements in the right diagonal
Ans: consider this example:
Topic: Array Prepared by Ashwini Y.
Index number of left diagonal: 00,11,22,33 - Means here, the row
index no. and column index no. are
same.
Index number of right diagonal: 03,12,21,30 - Means here, the
addition of row index no. and
column index no is 3.
Here, 3 is size of matrix-1; 4-1=3
Ans: import [Link].*;
public class matrix
{
public static void main(String args[])
{
Scanner sc=new Scanner([Link]);
int a[][]=new int[4][4];
int i,j;
int sumleft=0,sumright=0;
Topic: Array Prepared by Ashwini Y.
[Link]("Enter array elements:");
for(i=0;i<4;i++)
{
for(j=0;j<4;j++)
{
a[i][j]=[Link]();
}
}
//for calculating the sum of left and right diagonals
for(i=0;i<4;i++)
{
for(j=0;j<4;j++)
{
if(i==j) //00,11,22,33
{
sumleft=sumleft+a[i][j];
}
else if(i+j==3) //03,12,21,30
{
sumright=sumright+a[i][j];
}
else
{
[Link](" ");
}
}
}
[Link]("Sum of left diagonal elements: "+sumleft);
[Link]("Sum of right diagonal elements:"+sumright);
Topic: Array Prepared by Ashwini Y.
}
}
OR
import [Link].*;
public class matrix
{
public static void main(String args[])
{
Scanner sc=new Scanner([Link]);
int a[][]=new int[4][4];
int i,j;
int sumleft=0,sumright=0;
[Link]("Enter array elements:");
for(i=0;i<4;i++)
{
for(j=0;j<4;j++)
{
a[i][j]=[Link]();
}
}
//for calculating the sum of left and right diagonals
for(i=0;i<4;i++)
{
sumleft=sumleft+a[i][i]; //00,11,22,33
Topic: Array Prepared by Ashwini Y.
sumright=sumright+a[i][3-i]; //03,12,21,30
}
[Link]("Sum of left diagonal elements: "+sumleft);
[Link]("Sum of right diagonal elements:
"+sumright);
}
}
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
Program: Write a program to accept 10 states and 10 capitals of a
country in two different single dimensional arrays.
Now, enter a state of the country to display its capital.
If it is present then display its capital otherwise, display a relevant
message.
Sample input: enter the state and the capital
Bihar
Patna
West Bengal
Kolkata and so on------------
Sample Output: enter the state whose capital is to be searched:
West Bengal
The capital is Kolkata
Ans: import [Link].*;
public class Capital
{
public static void main(String args[])
{
Scanner in = new Scanner([Link]);
int i,a=0,flag=0;
String st;
Topic: Array Prepared by Ashwini Y.
String m[]=new String[10];
String n[]=new String[10];
for(i=0;i<10;i++)
{
[Link]("Enter states in the cell :");
m[i]=[Link]();
[Link]("Enter capital in the cell :");
n[i]=[Link]();
}
[Link]("Enter the states whose capital to be
searched");
st=[Link]();
for(i=0;i<10;i++)
{
if(m[i].equals(st))
{
flag=1;
a=i;
}
}
if(flag==1)
{
[Link]("The capital is "+n[a]);
}
else
{
[Link]("The state"+st+ "is not found at any location");
}
Topic: Array Prepared by Ashwini Y.
}
}
****************************************************************************
Topic: Array Prepared by Ashwini Y.