C++ - SPLessons

C++ Arrays

Chapter 18

SPLessons 5 Steps, 3 Clicks
5 Steps - 3 Clicks

C++ Arrays

C++ Arrays

shape Description

CPP Arrays are the collection of similar type of elements stored in continuous memory address whose range is defined before the declaration. The elements in array can be selectively updated.

For Example, if wanted to store marks of a student, to list all the employees in a company. An array is a variable that contains more values.

Declaring an array

shape Syntax

To declare an array in C++, type and number of elements are required by an array has to specify as follows. CPP Arrays must be declared before using in the program.

data_type array_name[size of the array];

where

Data type of an array defines the type which the elements belong to. All the array elements declared under braces are of same data type.
Array name is used to access the array whenever required.
Size is always defined in [] and the user can give it which denotes the number of elements present in the array.For example: arr[3], arr[5] etc.

Initializing an Array

shape Syntax

An array should be initialized at compile-time or run-time. If not initialized, compiler takes the garbage value.

data_type array_name[array size]={element1,element2,element3,…};

The size of the array and number of elements in {} must be same.

Eg:

shape Program

#include <iostream>
using namespace std;
int main()
{
    int x, i;
    float number[100], sum=0.0, avg;
    cout << "Enter the numbers"; cin >> x;
    while (x>10 || x<=0)
    {
        cout << "Error! number should in range of (1 to 10)"<< endl;
        cout << "Enter the number again: "; cin >> x;
    }
   for(i=0; i<x; ++i)
   {
      cout << i+1 << ". Enter number: "; cin >> number[i];
      sum+=number[i];
   }
   avg=sum/x;
   cout << "Average = " << avg;
   return 0;
}

Output:

Enter the numbers10
1. Enter number: 1
2. Enter number: 2
3. Enter number: 3
4. Enter number: 4
5. Enter number: 5
6. Enter number: 6
7. Enter number: 7
8. Enter number: 8
9. Enter number: 9
10. Enter number: 10
Average = 5.5

Compile Time Initialization

shape Declarations

This is similar to the normal Variable Initialization which means that the array elements are declared before execution of program. Declaration can be done in two ways.

i) Declaring the size: In this, size of CPP Arrays is specified before compilation.

Eg:int a[3]={1,2,3,4};

In the above example, the size of the array is declared as 3 which the user fixes it and this is taken by the compiler. It also assigns the values to the elements in serial order starting from 0. Like,

(ii) Not Declaring the size:  Here, the size is not specified. It can be considered when  number of entries are unknown.

Eg: int a[]={1,2,3,4};

In the above example, the size of array is not declared. So, the compiler counts the number of elements inside the braces itself and stores it.

Run-time Initialization

shape Description

This can be used when the user wants to input the values to the elements.

  • cin function is used to read the given values by the compiler.
  • When large number of entries are given run-time initialization is used

Multi-dimensional Arrays

shape Description

If one-dimensional arrays are extended, multi-dimensional arrays are obtained which consists of rows and columns and looks like a matrix. The memory location address also adds to the previous element address. They are also referred to as “array of arrays“.

shape Syntax

data_type array_name[d1][d2][d3]….[dn];

where d1=first dimension
d2=second dimension
.
.
dn=last dimension

Eg:
int a[2][3] : The example denotes that there are 2 rows and 3 columns.A total of 2×3=6 elements of integer data type. The memory location is 4000 for 1st element, 4002 for 2nd element…so on since it is of integer data type.

float b[3][3][3] : The example denotes that there are 3 tables,3 rows and 3 columns. A total of 3x3x3=27 elements of float data type.The memory location is 4000 for first element, 4004 for second element…so on since it is of float data type.

shape Example

#include<iostream>
using namespace std;
int main()
{
   int a,b,x,y, matrix1[10][10], matrix2[10][10], sum[10][10];
 
   cout << "Enter the number of rows and columns of matrix "; cin >> a >> b;
   cout << "Enter the elements of first matrix\n";
 
   for ( x = 0 ; x < a ; x++ )
   {
      for ( y = 0 ; y < b ; y++ ) { cin >>matrix1[x][y];
      }
   }
   cout << "Enter the elements of second matrix\n";
 
   for ( x = 0 ; x < a ;x++ )
   {
      for (y = 0 ; y < b ; y++ ) { cin >> matrix2[x][y];
       }
   }
   for ( x = 0 ; x < a ; x++ )
   {  
      for ( y = 0 ; y < b ; y++ )
      {
         sum[x][y] = matrix1[x][y] + matrix2[x][y];
      }
   }
 
   cout << "Sum of entered matrices:-\n";
 
   for ( x = 0 ; x < a ; x++ )
   {
    for ( y = 0 ; y< b ; y++ )
    {
       cout << sum[x][y] << "\t";
     }
      cout << endl;
   }
 
   return 0;
}

Output:

Enter the number of rows and columns of matrix 2
2
Enter the elements of first matrix
1
2
3
4
Enter the elements of second matrix
5
6
7
8
Sum of entered matrices:-
6       8
10      12

Passing Arrays to Functions

shape Description

Passing an entire array as function arguments at a time is not possible in C++. But, pointer of the array can be passed by specifying its name without giving the size of array.

shape Example

#include <iostream>
using namespace std;
double getAverage(int arr[], int size);
int main ()
{
   int a[7] = {1, 2, 3, 10, 25,15,18};
   double average;
   average = getAverage( a,7 ) ;//passing array as an argument
   cout << "Average value is: " << average << endl; 
   return 0;
}
double getAverage(int arr[], int size)
{
  int    i, sum = 0;       
  double average;          
  for (i = 0; i < size; ++i)
  {
    sum =sum + arr[i];
  }
  average = double(sum) / size;
  return average;
}

Output:

Average value is: 10.5714

shape More Info

An array can be returned from a function but not all the elements at a time. But, by using pointers, array can be returned without mentioning the size of array.

Local variables are also not returned when they are declared in a particular function. So, to overcome this problem, “Static” keyword must be used before the local variable.

shape Example

#include <iostream>
#include <cstdlib>
using namespace std;
int * getRandom( )
{
  static int a[10];
  for (int i = 0; i < 10; ++i)
  {
    a[i] = rand();
  }
  return a;
}

int main ()
{
   int *b;
   b= getRandom();
   for ( int i = 0; i < 10; i++ )
   {
       cout << "*b + " << i << ") : ";
       cout << *(b + i) << endl;
   }
   return 0;
}

Output:

*b + 0) : 41
*b + 1) : 18467
*b + 2) : 6334
*b + 3) : 26500
*b + 4) : 19169
*b + 5) : 15724
*b + 6) : 11478
*b + 7) : 29358
*b + 8) : 26962
*b + 9) : 24464

String arrays

shape Description

Strings using arrays can be used when it is known how many characters are given in the array.This process of assigning characters during compile time is known as “Static Allocation“.

shape Syntax

char String_variable_name[size];

For Eg:

char c[]={‘s’, ‘p’,’l’,’e’,’s’,’s’,’o’,’n’,’s’,’\0′};

(or) the above example can also be represented as

char c[10]=”splessons”;

Summary

shape Key Points

  • CPP Arrays are stored in continuous memory location. But once the size is declared, it cannot be changed.
  • Array index start with ‘0’ and end with ‘size-1’
  • Arrays are “One-dimensional and Multi-dimensional”

shape Programming
Tips

  • While implementing, when ‘n’ number of variables of same data type are required, then go for an array.
  • One can use #define to specify Array size if you want to change the size of the array.