Ch7 Array
An array is a collection of variables of similar
datatype.
10 names: std1,std2,……..std10.-> seprate 10 var.
creation -> memory occupy.
As a result program of large file size.
A[0] B[1] C[2] D[3]
100(base) 101 102 103………… .
. . . . . .
DATA STRUCTURE
Q What is an Array?
Q need of array?
Q Advantages of Array ?
Q Array vs objects.
Declaration:
Syntax:
DataType Arr_name[] = new type[size];
Datatype[] name= new type [size];
Creation of array:
1) int arr[]=new int[10]; Class sum
{ int arr[];
2) int arr[]; Sum()
{
Constructor /main Arr=new int[10];
arr= new int[10]; }
}
why array index start with Zero?
1gb =1000mb=1024 mb
Operation in Array :
Insert / Delete
We require Loop -> for loop (dect; cond;
update(++/--) )
int arr[]= new int[5];
for(int i =0;i<5;i++)
{
arr[i]= value;
S.o.p(arr[i]);
}
Linear Search (one by one comparing )
Binary Search(Divide & Conq.)
Sorting:
1. Selection short(arr[0]-> smallest, compare ,
pointer change a)
2. Bubble Short(Swaping of elements)
“LINEAR SEARCH”
1,2,3,4,5,6,7,8,9
If (arr[1]==8??)
Success SOP print pos.
Else
Error !!! Not found.
Target = 8
Linear search program
import [Link].*;
class Linear
{
int arr[];
public Linear()
{arr = new int[5];
}
void input()
{
Scanner obj =new Scanner([Link]);
[Link]("Enter the elements:");
for(int i=0;i<5;i++)
{
arr[i]= [Link]();
}
}//fn input closed
void show()
{
[Link]("Your Array:");
for(int i=0;i<5;i++)
{
[Link](arr[i]+" ");
}
[Link](" ");
}//fn show closed
void srch()
{
Scanner s1 =new Scanner([Link]);
[Link]("Enter Element to search:");
int trg= [Link]();
int flag=0, pos=0;
for(int i=0;i<5;i++)
{
if(arr[i]==trg)
{
flag++;
pos=i+1;
break;
}// if closed
}// for closed
if(flag==1)
[Link]("Success:) Element found at pos "+pos);
else
[Link]("Error!!!Not Found" );
}//scrch closed
public static void main()
{
Linear a1 =new Linear();
[Link]();
[Link]();
[Link]();
}//main
}//class