Sunteți pe pagina 1din 43

One Dimensional Array

The simplest form of an array is one-dimensional array. The


syntax to define an array is as follows.
type arr-name[size];
e.g. int s[10];
0 1 2 3 4 5 6 7 8 9

1. Write a program for the average of ten different students total marks.
2. Write a program to input 5 different values by using pointer without
using an array.
3. Write a program to input any 5 values using pointer and modify each
element by multiplying 10 at each address of pointer.
Implementation of 1D Array in Memory
In memory, 1d arrays are implemented by allocating a sequence of
addressed locations so as to accommodate all its elements. The
starting address of the very first element of the array is called
base address of the array.

Address of the arr[I] = Base_Address + ES(I-L)

Where ES is size of an array element.


L is the lower bound of the array.

Q.1 What will be the address of 5th element in a floating-point array


implemented in C++? The array is specified as amount[16].
The base address of array is 1058.
Sol: We have to calculate the address of amount[4].
ES = 4,
L = 0,
Base Address = 1058,
Address of amount[4] = 1058 + 4 (4-0) = 1058 + 16
=1074.
Implementation of 1D Array in Memory
OPERATION ON ARRAYS
1)Searching
a)Linear Search b)Binary Search
2)Traversal
3)Insertion
4)Deletion
5)Sorting
a)Insertion Sort b)Selection Sort c)Bubble Sort
6)Merging
TRAVERSAL
void main() OUTPUT:-
{ Array:-
int arr[10],i; 11,22,33,44,55,66,77,88,99,100
clrscr(); After Traversing:-
cout<<"Enter array elements"; 22,44,66,88,110,132,154,176,198,200.
for(i=0;i<10;i++)
{ cin>>arr[i];
}
cout<<"\n\nAfter Multiplying each
element of array by 2 we get\n\n";
for(i=0;i<10;i++)
{
arr[i]=2*arr[i];
cout<<"\n"<<arr[i];
}
getch();
}
Linear Searching
void main() for(i=0;i<10;i++)
{ {
int arr[10]; if(item==arr[i])
int i,item,found=0; {
clrscr(); found=1;
cout<<"Enter array elements"; cout<<"Item is present at
for(i=0;i<10;i++) location"<<i+1;
{ }
cin>>arr[i]; }
} if(found==0)
cout<<"Enter Element to be cout<<"Item is not present in
searched for"; the array";
cin>>item; getch();
}
BINARY SEARCH
void main() while(low<=high && found==0)
{ {
int size=6,arr[6]; mid=(low+high)/2;
int item,mid,low=0,high=size-1,found=0; if(item==arr[mid])
clrscr(); {
cout<<"Enter array elements in found=1;
Ascending Order"; cout<<"Element is found at
for(int i=0;i<size;i++) "<<mid+1<<" position";
{ }
cin>>arr[i]; else if(item>arr[mid])
} low=mid+1; //high=mid-1(for desc.)
cout<<"Enter Element to be searched else
for"; high=mid-1; //low=mid+1(for desc.)
cin>>item; }
if(found==0)
cout<<"Element is not found";
getch();
}
BINARY SEARCH[Function]
int Bin_Search(int arr[],int item,int size)
{
int mid,low=0,high=size-1,found=0;
while(low<=high && found==0)
{
mid=(low+high)/2;
if(item==arr[mid])
return mid;
else if(item>arr[mid])
low=mid+1; // high=mid-1 (in case of desc.)
else
high=mid-1; // low=mid+1 (in case of desc.)
}
return -1;
}
BINARY SEARCH[Calling Function]
void main()
{
int arr[10],elt,n=6,index;
clrscr();
cout<<"Enter array elements in Ascending Order";
for(int i=0;i<size;i++)
{ cin>>arr[i];
}
cout<<"Enter Element to be searched for";
cin>>elt;
index=Bin_Search(arr,elt,n);
if(index==-1)
cout<<"\nElement is not found";
else
cout<<"\nElement is found at location"<<index+1;
getch();
}
INSERTION
• Insertion of new element in the Array could be done in two
ways:-
• A) Unsorted:-The element in this case is inserted at the end
of array.
• B)Sorted:-The element is inserted at the specified position
by shifting rest of the elements accordingly.
INSERTION MECHANISM
UnOrdered Array:-Element is inserted at the end.
Ordered(Sorted) Array:- Element is inserted at the desired specified location.

Pos. Elt’s Pos. Elt’s Pos. Elt’s


0 10 0 10 0 10
1 12 1 12 1 12
2 23 2 23 2 23
3 25 3 25 3 25
4 31
← 4 4 29
5 39 5 31 5 31
6 43 6 39 6 39
7 45 7 43 7 43
8 50 8 45 8 45
9 9 50 9 50

Inserting 29 here Elements shifted Array after Insertion


i.e 5th position to create place
INSERTION[Finding Position Using Function]
int FindPos(int arr2[],int size,int item)
{ int pos;
if(item<arr2[0]) //first element
pos=0;
else
{
for(int i=0;i<size-1;i++)
{
if(item>=arr2[i] && item<arr2[i+1])
{
pos=i+1;
break;
}
}
if(item>arr2[size-1]) //last element
pos=size;
}
return pos;
}
INSERTION[Inserting Element By Calling Function]
void main()
{ int arr[10],N=6,elt,index; //N<10
clrscr();
cout<<"Enter array elements";
for(int i=0;i<N;i++)
{ cin>>arr[i]; }
cout<<"Enter Element to be inserted";
cin>>elt;
index=FindPos(arr,N,elt);
for(i=N;i>index;i--) //Making room for new elt.
{ arr[i]=arr[i-1]; //i.e By shifting Elts Downwards
}
arr[index]=elt; //item inserted.

N=N+1; //Array size increased.


cout<<"The New Array is:-";
for(i=0;i<N;i++)
cout<<"\n"<<arr[i];
getch();
}
DELETION
• The element to be deleted is first searched in the array
using Linear Search or Binary Search.
• If the search is successful, the element is removed and rest
of the elements are shifted upwards so as to keep the order
of array.
• If the elements are shifted upwards(this is the case we have
considered), then free space is available at the end of array
else at the beginning of array.
DELETION MECHANISM
Pos. Elt’s Pos. Elt’s Pos. Elt’s
0 10 0 10 0 10
1 12 1 12 1 12
2 23 2 23 2 23
3 25 3 25 3 25
4 31 ← 4 4 39
5 39 5 39 5 43
6 43 6 43 6 45
7 45 7 45 7 50
8 50 8 50 8
9 9 9

Deleting 31 from Elements removed Array after deletion of


here i.e 5th position elements
DELETION[Searching Element]
• Searching the Element first i.e its location using Linear Search
int LinSearch(int arr2[],int size,int item)
{
for(int i=0;i<size;i++)
{
if(arr2[i]==item)
return i;
}
return -1;
}
DELETION[Deleting Element]
void main() if(index==-1)
{ cout<<"\nElt is not present";
int arr[10],N=6,elt,index; else
clrscr(); {
if(N==0) for(i=index;i<N;i++)
{ cout<<"Underflow";exit(1);} {
cout<<"Enter array elts:-\n"; arr[i]=arr[i+1]; //shifting elts upwrds.
for(int i=0;i<N;i++) }
{ cin>>arr[i]; } N=N-1; //No. of Elements decreased by 1.

cout<<"Enter Elt to be del."; cout<<"\nArray after del.:-\n";


cin>>elt; for(i=0;i<N;i++)
index=LinSearch(arr,N,elt); cout<<"\n"<<arr[i];
}
2 Dimensional Array
A 2D Array represented as A[1..M,1..N] is an MxN table with M rows and N Columns
containing MxN Elements.
IMPLEMENTATION OF 2D ARRAY IN MEMORY
The Computer does not keep track of addresses of all the elements of the array but does keep
track of Base Address(Starting add. Of first elt.) and calculate address of the elements when
required.
1)Row Major Implementation:-
It stores the elements row wise i.e it stores first row then second row then third & so on.
For Ex:-

Formula for Address calculation of A[I,J] of order mxn [In Row Major form]:-
B+W[n(I-Lr)+(J-Lc)] where n are no. of cols.
In A[Lr : Ur , Lc : Uc] B is Base Address, W Element size in Bytes
Lr(Lower Bound of Row) Lr is Lowest Row Index and Ur is Highest row index [m=Ur-Lr+1]
Ur(Upper Bound of Col.) Lc is Lowest Col. Index and Uc is Highest Col. Index .[n=Uc-Lc+1]
EX:- A[-3..5,-2..7]
Problems in Row Major Implementation
For Numericals in 2D Array you always need to have no. of rows and cols. i.e m and
n.You will be given Array in two forms as:-
i) A[4..7,-1..3]
Here you have given elements of 1st row 1st Element(4) and Last row 1st
Element(7).Similarly, you have 1st col. 1st Element(-1) and Last col. 1st Element(3).
ii) A[10x5] Here you have given No. of rows as 10 and No. of Col.s as 5 directly.

Q1:-A 2D Array A[4..7,-1..3] requires 2 words of storage for each elt..If array is stored
in Row Major form,Calculate the address of A[6,2].Given Base address as 100.
Ans:-Here in B+W[n(I-Lr)+(J-Lc)],
B=100, W=2,I=6.J=2
Lr=4,Ur=7,So m(No. of Rows=Ur-Lr+1=7-4+1=4) i.e m=4
Lc=-1,Uc=3,So n(No. of Cols=Uc-Lc+1=3-(-1)+1 i.e n=5
So, Address of A[6,2]= 100+2[5(6-4)+(2-(-1))]=100+2[10+3]=100+26=126.
Q2:-A 2D Array X[10X5] in which each element takes 2 bytes to store.If X[1,1] begins
at address 150.Find location of X[3,4].Implementation is Row-Major.
Ans:- 176.
2)Column Major Implementation:-It stores the elements Column wise i.e it
stores first Col. then second Col. then third & so on.For Ex:-

Formula for Address calculation of A[I,J] of order mxn [In Column Major form]:-
B+W[(I-Lr)+m(J-Lc)] where m are no. of rows.
In A[Lr : Ur , Lc : Uc] B is Base Address, W Element size in Bytes
Lr is Lowest Row Index and Ur is Highest row index [m=Ur-Lr+1]
Lc is Lowest Col. Index and Uc is Highest Col. Index .[n=Uc-Lc+1]
Problems in Column Major Implementation:-
Q1:-In Array A[-20..20,10..35] requires 1 Byte of storage.If array is stored in Col. Major
Implementation with starting address as 500,determine the location of A[0,30].
Ans:-Here B=500, W=1, Lr=-20,Lc=10,I=0,J=30
m=Ur-Lr+1=20-(-20)+1=41.
Address of A[0,30]= B+W[(I-Lr)+m(J-Lc)]= 500+1[(0-(-20)+41(30-10)]=500+[20+(41x20)]=1340.
More Problems:-
Q1:-In Array A[-15..20,20..45], each element requires 1 byte of storage.If the array is
stored in Column Major form having beginning address as 1000, determine the
location of A[0,40].
Ans:-1735.

Q2:-Given a 2D Array having order as 3x4


How would Array implemented in memory if
a)Row Major technique is used.
b)Column Major technique is used.
ADDITION & DIFFERENCE OF MATRICES[2D ARRAY]
ADDITION OF MATRICES[2D ARRAY]
void main() cout<<"\nSum of 1st array and 2nd array
{ int i,j,a[2][2],b[2][2],c[2][2]; is:-\n";
clrscr(); for(i=0;i<2;i++)
cout<<"\nEnter 1st array elements\n"; {
for(i=0;i<2;i++) for(j=0;j<2;j++)
{
{
for(j=0;j<2;j++)
c[i][j]=a[i][j]+b[i][j];
{ cin>>a[i][j];
} cout<<c[i][j];
cout<<"\n"; cout<<"\t";
} }
cout<<"\nEnter 2nd array elements\n"; cout<<"\n";
for(i=0;i<2;i++) }
{ getch();
for(j=0;j<2;j++) }
{ cin>>b[i][j];
}
cout<<"\n";
}
Product Of Matrices
If A[M,N] & B[P,Q] are two matrices(2 D Arrays) and we need to find
AXB then
i)Check Whether the two Arrays are compatible for multiplication or not.
If N==P then only the two Arrays are Multiplicable else Not.
Secondly,the new resultant Product Array formed will be of the order MXQ.
Product of Matrices
void main() for(i=0;i<m;i++)
{ int i,j,a[10][10],b[10][10],c[10][10],m,n,p,q; { for(j=0;j<q;j++)
clrscr(); {
cout<<"Input rows & Col. of 1st Matrix c[i][j]=0;
m,n\n"; for(int k=0;k<n;k++)
cin>>m>>n; { c[i][j]=c[i][j]+(a[i][k]*b[k][j]);
cout<<"Input rows & Col. of 2nd Matrix }
p,q\n"; }
cin>>p>>q; }
if(n==p) cout<<"\nProduct of both arrays is:-\n";
cout<<"\nMatrix can be Multiplied"; for(i=0;i<m;i++)
else { for(j=0;j<q;j++)
cout<<"\nMatrix cannot be Multiplied"; { cout<<c[i][j]<<"\t“; }
cout<<"\nEnter 1st array elements\n“; cout<<"\n";
i.E a[i][j] }
cout<<"\nEnter 2nd array elements\n";
i.E b[i][j]
TRANSPOSE OF MATRIX

cout<<"\nTranspose of Given Matrix is-


\n";
void main()
for(i=0;i<2;i++)
{ int i,j,a[2][2],b[2][2],c[2][2];
{
clrscr();
for(j=0;j<2;j++)
cout<<"\nEnter 1st array elements\n";
{
for(i=0;i<2;i++)
b[i][j]=a[j][i];
{
cout<<b[i][j];
for(j=0;j<2;j++)
cout<<"\t";
{
}
cin>>a[i][j];
cout<<"\n";
}
}
cout<<"\n";
getch();
}
}
Sorting In Array
Sorting of an array means arranging the array elements in a specific order
(either ascending or descending order). There are several sorting techniques
are available (Selection sort, bubble sort, quick sort, heap sort, insertion sort
etc.) We will discuses here only for selection sort, bubble sort and insertion
sort.

Selection Sort:
The basic idea of a selection sort is to repeatedly select the smallest key in
the remaining unsorted array.(Firstly 1st position is checked and fixed with
the shortest Elt. and then 2nd position is checked & so on).
Selection Sort
#include<iostream.h> void main()
#include<conio.h> {
void SelSort(int AR[], int size) clrscr();
{ int AR[50],ITEM,N,index;
int temp,pos; cout<<"Enterarray elements"<<endl;
for (int i=0; i<size;i++) for (int i=0; i<10; i++)
{ {
for (int j=i+1; j<size; j++) cin>>AR[i];
{ }
if (AR[i]>AR[j]) SelSort(AR,10);
{ cout<<endl<<"The sorted array is as
follows"<<endl;
temp=AR[i];
for (i=0; i<10; i++)
AR[i]=AR[j];
{
AR[j]=temp;
cout<<AR[i]<<" ";
}
}
}
getch();
}
}
}
Bubble Sort
The basic idea of a selection sort is to compare two adjoining values
and exchange them if they are not in proper order. The example
below can describe it.

Notice that:-In Bubble Sort the greatest element is settle down as


the bottom most element on every pass where as in Selection Sort
the Shortest Element is Placed at the start on Every Pass.

Also in Bubble sort as the largest element is placed at the bottom it


is removed from any comparison further likewise the shortest
element is removed in case of Selection Sort.

We have used the following Condition in our loop:-


i<(size - 1) – i :- It is used because on every iteration bottom most
position get fixed and no need to check this value in next iteration.
So, as i increases no. of comparisons decreases.
The following Loop is used in Bubble Sort:-

for (int i=0; i<size; i++) for(int i=0;i<7;i++)


{ {
for (int j=0; j<(size - 1) - i; j++) for(j=0;j<6-i;j++)
if (AR[j] >AR [j + 1])
{
temp = AR [ j ];
AR [ j ] = AR [ j + 1 ];
AR [ j + 1 ] = temp;
}
}

I) if(AR[0]>AR[1]) II) if(AR[1]>AR[2]) III) if(AR[2]>AR[3])


{ { {
temp=AR[0]; temp=AR[1]; temp=AR[2];
AR[0]=AR[1]; AR[1]=AR[2]; AR[2]=AR[3];
AR[1]=temp; AR[2]=temp; AR[3]=temp;
} } }

i.e if(13>24) i.e if(24>5) interchange i.e if(24>19) interchange


Cond fails
So no change.
Bubble Sort
Bubble Sort:
#include<iostream.h> void main()
#include<conio.h> {
clrscr();
void BubbleSort (int AR[], int size)
{ int AR[ 50 ], ITEM, N, index;
int temp, ctr = 0;
cout<<“How many elements ..?”<<endl;
for (int i=0; i<size; i++) cin>>N;
{
cout<<“Enter array elements”<<endl;
for (int j=0; j<(size - 1) - i; j++)
{ for (int i=0; i<N; i++)
{
if (AR[j] >AR [j + 1]) cin>>AR [ i ];
{ }
temp = AR [ j ];
AR [ j ] = AR [ j + 1 ]; BubbleSort (AR,N);
AR [ j + 1 ] = temp;
} cout<<“The sorted array is as follows\n”;

} for (i=0; i<N; i++)


{
cout<<“Array after iteration–“<<++ctr<<“–is:“; cout<<AR [ i ]<<“ “<<endl;
}
for (int k = 0; k < size; k++)
cout<<AR [k]<<“ “<<endl; getch();
}
}
}
Insertion Sort:
Suppose an array A with n elements A[1], A[2],…A[N] is in memory. The
insertion sort algorithm scans A from A[1] to A[N], inserting each elt. A[K]
into its proper position in the previously sorted subarray A[1], A[2],…A[k-1].
Suppose we have the following Array[Taking A[0] as Minimum No. INT_MIN.
Insertion Sort:
Insertion Sort:
#include<iostream.h> void main()
#include<conio.h> {
#include<limits.h> //for INT_MIN clrscr();

void InsSort (int AR[], int size) int AR[ 50 ], ITEM, N, index;
{ cout<<“How many elements ..?”<<endl;
int temp, j; cin>>N;
AR [0] = INT_MIN ;
for (int i = 1; i < size; i++) cout<<“Enter array elements”<<endl;
{
temp = AR [i]; for (int i=0; i<N; i++)
j = i – 1; {
while (temp < AR [ j ]) cin>>AR [ i ];
{ }
AR [ j + 1 ] = AR [ j ];
j--; InsSort (AR, N);
}
AR [ j + 1 ] = temp; cout<<“The sorted array is as follows\n”;
cout<<“Array after pass – “<<i<<“-is”;
for (i=0; i<N; i++)
for (int k =1; k <= size; k++)
{
{
cout<<AR [ i ]<<“ “<<endl;
cout<<AR [ k ]<<“ “<<endl;
}
}
}
getch();
}
}
// AR [ j + 1 ] = AR [ j ]; This line is used
To change the current scanning elt to next
if the previous elt. Is placed to the right
Position.
Merging of Arrays:
Merging means combining elements of two arrays to form a new array.
Simplest way of merging two arrays is that first copy all the elements of
one array into new array and then copy all the elements of other array
into new array. If you want the resultant array to be sorted, you can
sort the resultant array. Another popular technique to have a sorted
resultant array is sorting while merging – Merge Sort.
Merge Sort.
Example of Merge Sort
If
M=4 and A[i]=11,22,33,44 (Already Sorted)

N=3 and B[j]=6,16,26 (Already Sorted)

Then C[k]=6,11,16,22,26,33,44. (Also Sorted)

Note:- If A[i] & B[j] are not sorted the sort them first using
any of the sorting method described earlier as
Selection,Bubble or Insertion.
MERGE SORT
void merge(int A[],int M,int B[],int N,int C[]) void main()
{ {
int i=0, j=0, z=0; clrscr();
while((i<M) && (j<N)) int A [50], B [50], C [50], MN =0,M,N;
{ cout<<“Limit of First Array?”<<endl;
if(A[i]<B[j]) cin>>M;
{ cout<<“Enter array elements”<<endl;
C[z]=A[i]; for (int i=0; i<M; i++)
i++;z++; {
} cin>>A[ i ];
else if(A[i]>B[j]) }
{ cout<<“Limit of Second Array?”<<endl;
C[z]=B[j]; cin>>N;
j++; z++; cout<<“Enter array elements”<<endl;
} for (int i=0; i<N; i++)
} {
if(i>=M) //i.e if A[i] ends 1st while cmprng cin>>B[ i ];
{ }
for(int k=0;k<N-j;k++) MN = M + N;
C[z+k]=B[j+k]; merge ( A, M, B, N, C)
} cout<<“Array after merging”<<endl;
else //i.e if j>=N or B[j] ends 1st for (int i=0; i<MN; i++)
{ {
for(int k=0;k<M-i;k++) cout<<C [ i ];
C[z+k]=A[i+k]; }
getch();
} }
}
Example of Merge Sort
If M=4 and A[i]=11,22,33,44 (Already Sorted)
N=3 and B[j]=6,16,26 (Already Sorted)
While(i<4 && j<3)
{ if(11<6)
1)11<6 c[z]=6 i=0,j=1,z=1
2)11<16 c[z]=6,11 i=1,j=1,z=2
3)22<16 c[z]=6,11,16 i=1,j=2,z=3
4)22<26 c[z]=6,11,16,22 i=2,j=2,z=4
5)33<26 c[z]=6,11,16,22,26 i=2,j=3,z=4 Now j<N cond. Fails, so
if(i>=M) i.e 2>=4 false so ctrl goes to else part i.e j>=N (3>=3)
For(int k=0;k<M-i;k++) i.e for(int k=0;k<2;k++) i.e loop for rest of elts of A[i]
C[z+k]=A[i+k] i.e now assign remaining elts of A[i] as it is to C[z].

However if (i>=M) then assign remaining elts of B[j] as it is to C[z].


BOARD Questions:-
Q1:-WAF in C++ which accepts an array and its size as arguments and swap the elements of
every even location with its following odd location.
Hint :- Use loop as for(int i=0;i<size;i+=2);

Q2:- Write a Function in C++ which accepts an integer array(1D) and its size as an argument
and exchange the values of first half side elements with the second half side elements of the
array.
For Ex:- if A[i]=2,4,1,6,7,9,23,10 the B[j]=7,9,23,10,2,4,1,6.
Hint:- Use mid=size/2. And for(i=0;i<mid;i++)

Q3:-Write a function in C++ to print the sum of all the values which are either divisible by 2 or
are divisible by 3 present in a 2D Array passed as the Argument to the function.
Hint :-Use if A[i][j]%2==0 and A[i][j]%3==0.

Q4:-WAF in C++ which accepts an integer array(2D) and its size as an argument and
Displays the elements which lie on diagonals.
Hint:- Use cout<<A[i][i] and cout<<cout<<A[i][n-(i+1)]

Q5:-WAF in C++ to print the product of each col. Of a 2D Array passed as the argument of the
fn.
Q6. An Array A[15][20] is stored in along the row(i.e Row Major form) with each element
Occupying 4 Bytes.Find out the Base address and the address of the element A[3][2], if the
Location of A[5][2] is stored at the address 1500.
Hint:-Initially take Lr=Lc=0.
Ans:-1092, 1340.

Q7. Find out the total number of elements and the total size of following arrays.{ Assuming
that each element consumes 4 bytes }
– Z[7]
– Y[-3…7]
– X[5] [4]
– W[-2..2][5..8]
Ans: a. Element: 7,Size : 28 bytes
b. Element: U-L +1 = 7-{-3}+1 =11, Size: 11 x 4 = 44 bytes.
c. Element: 5x 4 =20; Size : 20x 4 = 80 bytes
d. Rows = 2-{-2}+1 = 5, Cols. = 8 – 5 + 1 = 4, Elements :5 x 4 =20; Size=80 bytes
Q1:-In Array A[-15..20,20..45], each element requires 1 byte of storage.If the array is stored in
Column Major form having beginning address as 1000, determine the location of A[0,40].

Q2:-Given a 2D Array having order as 3x4.How would Array implemented in memory if


a)Row Major technique is used. b)Column Major technique is used.

Q3. An Array A[15][35] is stored in along the column(i.e Column Major form).Find out the Base
address and the address of the element A[2][5], if the Location of A[5][10] is stored at the
address 4000.
Hint:-Initially take Lr=Lc=0.

Q4:-An Array Arr[40][10] is stored in memory along column with each element Occupying
4 Bytes.Find out the address of Arr[3][6], if the location Arr[30[10] is stored at 9000.
Hint:- Initially take Ir=Ic=0 Ans:-7280.

Q5:- An Array Arr[20][15] is stored in memory along column with each element Occupying
8 Bytes.Find out the Base address and Address of Arr[2][3], if the element Arr[4][5] is
stored at Address 1000.(Ans:-168, 663).

S-ar putea să vă placă și