ARRAY in C++

Page Contents:

What is the definition of Array?
Syntax of array in C++
Examples Using Arrays
Sorting of an Array in C++
Searching array in C++
2-D ARRAY in C++
Pointer vs Array

What is the definition of Array?

Array in C
Array in C
  • It is a collection of multiple data of the same data type. for example, we can have an array of int type data or float type data. an array has a static memory allocation i.e memory size once allocated for an array cannot be changed. It’s Index starts from 0 to n number of index.
  • It is a consecutive group of memory locations that all have the same name and the same type. To refer to a particular location or element in the array, we specify the name of the array and the position number of the particular element in the array

Syntax of array in C++

Arrays occupy space in memory. The programmer specifies the type of each element and the number of elements required by an array as follows:

type arrayName[arraySize];

Where the compiler reserves the appropriate amount of memory

Examples Using Arrays

1.Declaring an Array and Using a Loop to Initialize the Array’s Elements

#include<iostream>
using std::cout;
using std::endl;
#include<iomanip>
using std::setw;
int main()
{
int n[10];
for(int i=0;i<10;i++)
n[i]=0;
cout<<"Element"<<setw(13)<<"Value"<<endl;
for(int j=0;j<10;j++)
cout<<setw(7)<<j<<setw(13)<<n[j]<<endl;
return 0;
}

OUTPUT:

Element   Value  
0           0
1           0
2           0
3           0
4           0
5           0
6           0
7           0
8           0
9           0

2.Initializing an Array in a Declaration with an Initializer

#include<iostream>
using std::cout;
using std::endl;
#include<iomanip>
using std::setw;
int main()
{
int n[10]={32,27,64,18,95,14,90,70,60,37};
cout<<"Element"<<setw(13)<<"Value"<<endl;
for(int i=0;i<10;i++)
cout<<setw(7)<<i<<setw(13)<<n[i]<<endl;
return 0;
}

OUTPUT:

Element    Value
0            32
1            27
2            64
3            18
4            95
5            14
6            90
7            70
8            60
9            37

3.Display a program Using Character Arrays to Store and Manipulate Strings

#include<iostream>
using std::cout;
using std::cin;
using std::endl;
int main()
{
char string1[20];
char string2[]"string literal";
cout<<"Enter the string\"hello there":";
cin>>string1;
cout<<"string1 is:"<<string1
    <<"\nstring2 is:"<<string2;
cout<<"\nstring1 with spaces between characters is:\n";
for(int i=0;string1[i]!='\0';i++)
cout<<string1[i]<<' ';
cin>>string1;
cout<<"\nstring1 is:"<<string1<<endl;
return 0;
}

OUTPUT:

Enter the string "hello there":hello there
string1 is:hello
string2 is:string literal;
string1 with sapaces between characters is:
h e l l o
string1 is:there

4.Display a program using Static Local Arrays and Automatic Local Arrays

#include<iostream>
 using std::cout;
 using std::endl;
 void staticArrayInit(void);
 void automaticArrayInit(void);
 int main()
 {
  cout<<"First call to each function:\n";
  staticArrayInit();
  automaticArrayInit();
  cout<<"\n\nSecond call to each function:\n";
  staticArrayInit();
  automaticArrayInit();
  cout<<endl;
  return 0;
 }
 void staticArrayInit(void)
  {
  static int array1[3];
  cout<<"\nValues on entering staticArrayInit:\n";
  for(int i=0;i<3;i++)
  cout<<"array1["<<i<<"]="<<array1[i]<<" ";
  cout<<"\nValues on existing staticArrayInit:\n";
  for(int j=0;j<3;j++)
  cout<<"array1["<<j<<"]="
      <<(array1[j]+=5)<<" ";
      }
      void automaticArrayInit(void)
      {
          int array2[3]={1,2,3};
          cout<<"\n\nValues on entering automaticArrayInit:\n";
          for(int i=0;i<3;i++)
          cout<<"array2["<<i<<"]="<<array2[i]<<" ";
          cout<<"\nValues on existing automaticArrayInit:\n";
          for(int j=0;j<3;j++)
          cout<<"array2["<<j<<"]="
              <<(array2[j]+=5)<<" ";
          }

OUTPUT:

First call to each function: Values on entering staticArrayInit: array1[0]=0 array1[1]=0 array1[2]=0 Values on existing staticArrayInit: array1[0]=5 array1[1]=5 array1[2]=5 Values on entering automaticArrayInit: array2[0]=1 array2[1]=2 array2[2]=3 Values on existing automaticArrayInit: array2[0]=6 array2[1]=7 array2[2]=8 Second call to each function: Values on entering staticArrayInit: array1[0]=5 array1[1]=5 array1[2]=5 Values on existing staticArrayInit: array1[0]=10 array1[1]=10 array1[2]=10 Values on entering automaticArrayInit: array2[0]=1 array2[1]=2 array2[2]=3 Values on existing automaticArrayInit: array2[0]=6 array2[1]=7 array2[2]=8

5.Display the Program Summing the Elements of an Array

#include<iostream>
using std::cout;
using std::endl;
int main()
{
const int arraySize=10;
int a[arraySize]={1,2,3,4,5,6,7,8,9,10};
int total=0;
for(int i=0;i<arraySize;i++)
total += a[i];
cout<< "Total of array element values is"<< total<<endl;
return 0;'
}

OUTPUT:

Total of array element value is 55

6.Passing array to the function in C++

#include<iostream> 
 using namespace std; 
 void printArray(int arr[5]); 
 int main() 
 { 
 int arr1[5] = { 10, 20, 30, 40, 50 }; 
 int arr2[5] = { 5, 15, 25, 35, 45 }; 
 rintArray(arr1); //passing array to function 
 printArray(arr2); 
 } 
 void printArray(int arr[5]) 
 { 
 cout << "Printing array elements:"<< endl; 
 for (int i = 0; i < 5; i++) 
 { 
 cout<<arr[i]<<"\n"; 
 } 
 } 

OUTPUT:

 Printing array elements:                                                              
 10                                                                                    
 20                                                                                    
 30                                                                                    
 40                                                                                    
 50                                                                                    
 Printing array elements:                                                              
 5                                                                                     
 15                                                                                    
 25                                                                                    
 35                                                                                    
 45 

7.Example of accessing an array in C++

#include<iostream> 
 using namespace std;
  #include 
 using std::setw;
 int main () {
 int n[ 10 ]; // n is an array of 10 integers
 // initialize elements of array n to 0          
    for ( int i = 0; i < 10; i++ ) {
       n[ i ] = i + 100; // set element at location i to i + 100
    }
    cout << "Element" << setw( 13 ) << "Value" << endl;
 // output each array element's value                      
    for ( int j = 0; j < 10; j++ ) {
       cout << setw( 7 )<< j << setw( 13 ) << n[ j ] << endl;
    }
 return 0;
 }

OUTPUT:

     Element     Value
       0          100
       1          101
       2          102
       3          103
       4          104
       5          105
       6          106
       7          107
       8          108
       9          109 

Sorting of an Array in C++

Sorting data(placing the data into some particular order such as ascending or descending) is one of the most important computing applications. A bank sorts all checks by account number so that it can prepare an individual bank statement at the end of each month. Telephone companies sort their lists of accounts by the last name and, within that, by the first name to make it easy to find a phone number. Virtually every organization must sort some data and, in many cases, massive amounts of data. Sorting data is an intriguing problem that has attracted some of the most intense research efforts in the field of computer science

#include<iostream>
using std::cout;
using std::endl;
#include<iomanip>
using std::setw;
int main()
{
const int arraySize=10;
int a[arraySize]={2,6,4,8,10,12,89,68,45,37};
int hold;
cout<<"Data item in original order\n";
for(int i=0;i<arraySize;i++)
cout<<setw(4)<< a[i];
for(int pass=0;pass< arraySize-1;pass++)
for(int j=0;j<arraySize-1;j++)
if(a[j]>a[j+1])
{
hold=a[j];
a[j]=a[j+1];
a[j+1]=hold;
}
cout<<"\n Data items in ascending order\n";
for(int k=0;k<arraySize;k++)
cout<< setw(4)<<a[k];
cout<< endl;
return 0;
}

OUTPUT:

Data items in original order
2 6 4 8 10 12 89 68 45 37
Data items in ascending order
2 4 6 8 10 12 37 45 68 89

Searching array in C++

  • Linear search
  • Binary search

1.Linear Search

The linear search compares each element of an array with a search key. Because the array is not in any particular order, it is just as likely that the value will be found in the first element as the last. On average, therefore, the program must compare the search key with half the elements of the array. To determine that a value is not in the array the program must compare the search key to every element in the array

#include<iostream>
using std::cout;
using std::cin;
using std::endl;
int linearSearch(const int[],int,int);
int main()
{
const int arraySize=100;
int a[arraySize];
int searchKey;
for(int i=;i<arraySize;i++)
a[i]=2+i;
cout<<"Enter integer search key";
cin>>searchKey;
int element=linearSearch(a,searchKey,arraySize);
if(element !=-1)
cout<<"Found value in element"<< element<< endl;
else
cout<<"Value not found"<<endl;
return 0;

}
int linearSearch(const int array[],int key,int sizeofArray)
{
for(int j=0;j<sizeofArray;j++)
if(array[j]==key)
return j;
return -1;
}

OUTPUT:

Enter integer search key:36
Found value in element 18

For invalid search key

Enter integer search key:37
Value not found

2.Binary Search

The linear searching method works well for small arrays or for unsorted arrays. However, for large arrays, linear searching is inefficient. If the array is sorted, the high-speed binary search technique can be used.

The binary search algorithm eliminates one-half of the elements in the array being searched after each comparison. The algorithm locates the middle element of the array and compares with the search key. If they are equal, the search key is found, and the array subscript of that element is returned. Otherwise, the problem is reduced to searching one-half of the array. If the search key is less than the middle element of the array, the first half of the array is searched; otherwise, the second half of the array is searched. If the search key is not the middle element in the specified subarray(a piece of the array), the algorithm is repeated on one-quarter of the original array. The search continues until the search key is equal to the middle element of a subarray or until the subarray consists of one element that is not equal to the search key

#include<iostream>
using std::cout;
using std::cin;
using std::endl;
#include<iomanip>
using std::setw;
int binarySearch(const int[],int ,int ,int ,int );
void printRow(const int[], int, int, int, int );
int main()
{
const int arraySize=15;
int a[arraySize];
int key;
for(int i=0;i<arraySize;i++)
a[i]=2*i;
cout<< "Enter a number between 0 and 28:";
cin>> key;
printHeader(arraySize);
int result=binarySearch(a,key,0,arraySize-1,arraySize);
if(result!=-1)
cout<<'n'<< key<<"found in array element"<<result<<endl;
else
cout<< '\n'<< key<< "not found"<<endl;
return 0;
}
int binarySearch(const int b[], int searchKey, int low, int high, int size)
{
int middle;
while(low<=high)
{
middle=(low+high)/2;
printRow(b,low,middle,high,size);
if(searchKey==b[middle])
return middle;
else
if(searcj=Key<b[middle])
high=middle-1;
else
low=middle+1;
}
return -1;
}
void printHeader(int size)
{
cout<<"\nSubscript:\n";
for(int j=0;j<size;j++)
cout<<setw(3)<<j<<' ';
cout<<'\n';
for(int k=1;k<=4*size;k++)
cout<<'-';
cout<<endl;
}
void printRow(const int b[], int low, int mid, int high, int size)
{
for(int m=0;m<size;m++)
if(m<low||m>high)
cout<<" ";
else
if(m==mid)
cout<<setw(3)<<b[m]<<'*';
else
cout<<setw(3)<<b[m]<<' ';
cout<<endl;
}
include
 using std::cout;
 using std::cin;
 using std::endl;
 include
 using std::setw;
 int binarySearch(const int[],int ,int ,int ,int );
 void printHeader(int);
 void printRow(const int[], int, int, int, int );
 int main()
 {
 const int arraySize=15;
 int a[arraySize];
 int key;
 for(int i=0;ii; cout<< "Enter a number between 0 and 28:"; cin>> key; printHeader(arraySize); int result=binarySearch(a,key,0,arraySize-1,arraySize); if(result!=-1) cout<<'n'<< key<<"found in array element"<size;k++) cout<<'-'; cout<high)
 cout<<" ";
 else
 if(m==mid)
 cout<<setw(3)<<b[m]<<'*';
 else
 cout<<setw(3)<<b[m]<<' ';
 cout<<endl;
 }#include<iostream>
using std::cout;
using std::cin;
using std::endl;
#include<iomanip>
using std::setw;
int binarySearch(const int[],int ,int ,int ,int );
void printRow(const int[], int, int, int, int );
int main()
{
const int arraySize=15;
int a[arraySize];
int key;
for(int i=0;i<arraySize;i++)
a[i]=2*i;
cout<< "Enter a number between 0 and 28:";
cin>> key;
printHeader(arraySize);
int result=binarySearch(a,key,0,arraySize-1,arraySize);
if(result!=-1)
cout<<'n'<< key<<"found in array element"<<result<<endl;
else
cout<< '\n'<< key<< "not found"<<endl;
return 0;
}
int binarySearch(const int b[], int searchKey, int low, int high, int size)
{
int middle;
while(low<=high)
{
middle=(low+high)/2;
printRow(b,low,middle,high,size);
if(searchKey==b[middle])
return middle;
else
if(searcj=Key<b[middle])
high=middle-1;
else
low=middle+1;
}
return -1;
}
void printHeader(int size)
{
cout<<"\nSubscript:\n";
for(int j=0;j<size;j++)
cout<<setw(3)<<j<<' ';
cout<<'\n';
for(int k=1;k<=4*size;k++)
cout<<'-';
cout<<endl;
}
void printRow(const int b[], int low, int mid, int high, int size)
{
for(int m=0;m<size;m++)
if(m<low||m>high)
cout<<" ";
else
if(m==mid)
cout<<setw(3)<<b[m]<<'*';
else
cout<<setw(3)<<b[m]<<' ';
cout<<endl;
}

OUTPUT:

Enter a number between 0 and 28:5                                                                                               Subscript:                                                                                     0   1   2   3   4   5   6   7   8   9  10  11  12  13  14  ---------------------------------------------------------                                                                     0   2   4   6   8  10  12  14* 16  18  20  22  24  26  28                                                                      0   2   4   6*  8  10  12                                                                                                      0   2*  4                                                                                                                          4*                                                                                                                           5not found                                                                                          

2-D ARRAY in C++

2D Array is constructed from a number of rows and the number of the column is used to solve the real-time problem.

1.addition of 2 d array in C++

#include<iostream> 
using namespace std;
int main()
{
    int r, c, a[100][100], b[100][100], sum[100][100], i, j;
    cout << "Enter number of rows (between 1 and 100): ";
    cin >> r;
    cout << "Enter number of columns (between 1 and 100): ";
    cin >> c;
    cout << endl << "Enter elements of 1st matrix: " << endl;
    // Storing elements of first matrix entered by user.
    for(i = 0; i < r; ++i)
   for(j = 0; j < c; ++j)
       {
           cout << "Enter element a" << i + 1 << j + 1 << " : ";
           cin >> a[i][j];
       }
    // Storing elements of second matrix entered by user.
    cout << endl << "Enter elements of 2nd matrix: " << endl;
    for(i = 0; i < r; ++i)
       for(j = 0; j < c; ++j)
       {
           cout << "Enter element b" << i + 1 << j + 1 << " : ";
           cin >> b[i][j];
       }
    // Adding Two matrices
    for(i = 0; i < r; ++i)
        for(j = 0; j < c; ++j)
            sum[i][j] = a[i][j] + b[i][j];
    // Displaying the resultant sum matrix.
    cout << endl << "Sum of two matrix is: " << endl;
    for(i = 0; i < r; ++i)
        for(j = 0; j < c; ++j)
{
            cout << sum[i][j] << "  ";
            if(j == c - 1)
                cout << endl;
        }
    return 0;
}

OUTPUT:

Enter number of rows (between 1 and 100): 2
Enter number of columns (between 1 and 100): 2

Enter elements of 1st matrix:
Enter element a11: 1
Enter element a12: 2
Enter element a21: 3
Enter element a22: 4

Enter elements of 2nd matrix:
Enter element b11: 1
Enter element b12: 2
Enter element b21: 3
Enter element b22: 4

Sum of two matrix is:
2  4
6  8 

Pointer vs Array

Arrays and pointers are intimately related in C++ and may be used almost interchangeably. An array name can be thought of as a constant pointer. Pointers can be used to do any operations involving an array sub-scripting

Assume the following declarations:

int b[5];
int *bPtr;

Because of the array name(without a subscript) is a pointer to the first element of the array, we can set bPtr to the address of the first element in array b with the statement

bPtr=b;

This is equivalent to taking the address of the first element of the array as follows:

bPtr=&b[0];

Array element b[3] can alternatively be referenced with the pointer expression

*(bPtr+3)

The 3 in the preceding expression is the offset to the pointer. When the pointer points to the beginning of an array, the offset indicates which element of the array should be referenced, and the offset value is identical to the array subscript. The preceding notation is referred to as pointer/offset notation. The parentheses are necessary because of the precedence of * in higher than the precedence of +. Without the parentheses, the above expression would add 3 to the value of the expression *bPtr.Just as the array elements can be referenced with a pointer expression, the address can be written with the pointer expression

bPtr+3

The array name can be treated as a pointer and used in pointer arithmetic. For example, the expression

*(b+3)

also refers to the array element b[3].In general, all subscripted array expressions can be written with a pointer and an offset. In this case, pointer/offset notation was used with the name of the array as a pointer.b still points to the first element in the array.

Pointers can be subscripted exactly as arrays can. For example, the expression

bPtr[1]

refers to the array element b[1]; this expression uses pointer/subscript notation.

Remember that an array name is essentially a constant pointer, it always points to the beginning of the array. Thus the expression

b +=3

is invalid, because it attempts to modify the value of the array name with pointer arithmetic.

Translate »