Chapter12 Array Single Dimension
Chapter12 Array Single Dimension
com
Array
An array is a collection of data elements of same data type. It is described by a
single name and each element of an array is referenced by using array name
and its subscript no.
Declaration of Array
Type arrayName[numberOfElements];
For example,
int Age[5] ;
float cost[30];
Examples:
cout << age[4]; //print an array element
age[4] = 55; // assign value to an array element
cin >> age[4]; //input element 4
Arrays as Parameters
At some moment we may need to pass an array to a function as a parameter.
In C++ it is not possible to pass a complete block of memory by value as a
parameter to a function, but we are allowed to pass its address.
For example, the following function:
void print(int A[])
accepts a parameter of type "array of int" called A.
In order to pass to this function an array declared as:
int arr[20];
we need to write a call like this:
print(arr);
Here is a complete example:
#include <iostream>
using namespace std;
void Merge(int A[], int B[], int C[], int N, int M, int &K)
{
int I = 0, J = 0;
K = 0;
while (I < N && J < M)
{
if (A[I] < B[J])
C[K++] = A[I++];
else if (A[I] > B[J])
C[K++] = B[J++];
else
{
C[K++] = A[I++];
J++;
}
}
int T;
for (T = I; T < N; T++)
C[K++] = A[T];
for (T = J; T < M; T++)
C[K++] = B[T];
}