What Are Arrays In C/C++?

What Are Arrays In C/C++?
What Are Arrays In C/C++?

Introduction 

In the programming world, Arrays play an essential role. Wanna know how? Suppose you have to store the mobile numbers of your friends using a C/C++ program.

It’s undeniable that you must have a number of friends. What will you do? Create separate variables for all of your friends? It will make the program look cluttered and messy. To avoid this issue, using arrays is the solution.

For a second, let’s jump into the imaginary anime world. In a school, we have classes and the respective students. Say, what if we don’t have classes for the students? Then, each student will be allotted to the individual section, the same as we declare the variables.

But, this would be so back-breaking and challenging for the school authorities to teach each student separately. To avoid such cases, classes are introduced just like an array, where we can define the number of students – as many as we want. This example precisely shows us the need for arrays.

Now, let’s dive deep into Arrays in C/C++.

What is an array in C/C++?

An array is a collection of variables of the same data type like integers, floating-point numbers, characters, or the derived data types like structure, pointers, etc.

Something to note is that we cannot group different data types in one array, i.e., we cannot have integers, characters, or float altogether in the same collection.

Hence, an array is known as a homogeneous data type. Moreover, array elements are stored in sequential or contiguous memory locations.

Here, since the array is of integer type, the first element will take four bytes from 2000 to 2003, the second element will take four bytes from 2004 to 2007, and so on. However, in the memory, the addresses are stored in Hexadecimal form. Just to make it easy, we are using these values for showcasing addresses. 

The critical point to notice here is that the array index starts from 0. So, to access the first element in an array, we can directly use arr[0]. Generally, to get the nth element, we use an index (n-1), where n is the size of an array. Simultaneously, we can access the elements by using the following index. 

blog banner 1

Moreover, we can access the array element in constant time, i.e., order of 1, O(1), by knowing the Base address. The base address of an array is the address value of the starting point of the array. It is usually the address of the first element of the array. In the above diagram, the base address is 2000.

Suppose we want to access the 4th element in the array.

Address( nth) = Base address + ( n x Size of the data type).
where, n = 4
Base address = 2000
Size of the data type = int = 4 bytes
Address( 4th ) = 2000 + ( 4 x 4)
= 2000 + 16
= 2016 ✅

Now, let’s see how to declare the Arrays in C/C++.

Syntax:

data_type  array_name [ array_size ];

For examples:

1. int arr[4];

In this case, we’d only declare the array of size 4; hence it will store garbage values as shown in the diagram.

2. int arr[3] = {1,2,3};

Declaration, as well as the Initialisation of the array, has taken place.

3. int arr[4] = { };

By convention, the values are 0’s due to the empty curly braces.

4. char arr[4] = {‘a’ ,’i’, ‘o’, ‘u’};

Since the char is 1 byte in C/C++ or any programming language, the first element starts from 200 to 201 and so on.

5. int arr[ ] = {0,8,7,6};

See, in this case, we haven’t specified the array size, which is also correct as we have initialised it with values.

6. float arr[3] = {6.8};

We’d specified only the first element; generally, the compiler assigns the default value when an array is created without assigning it any values.

7. int arr[5] = { [0..3] = 7 };

We can also initialise the array in this way.

8. int arr[3] = {0};

As of now, we’d discussed what could be the ways an array can be initialised or declared.

Let’s see the C/C++ codes for the same.

C

#include<stdio.h>
int main(){
    int example1[3];  // Garbage collected will be printed here
    for(int i=0 ;i<3; i++){
        printf("\nThe value at %d is %d",i+1,example1[i]);
    } 
     printf("\n------------------------------------");
    
    int  example2[4]={8,6,5,4}; // Assigning values
    for(int j=0 ;j<4; j++){
        printf("\nThe value at %d is %d",j+1,example2[j]);
    }
     printf("\n------------------------------------");
    
    float example3[6] = {6.8}; 
    for(int k=0 ;k<6; k++){
        printf("\nThe value at %d is %f",k+1,example3[k]);
    }
     printf("\n------------------------------------");
     
    char example4[5] = {'a','b','c','d'}; 
      for(int p=0 ;p<5; p++){
        printf("\nThe value at %d is %c",p+1,example4[p]);
    }
}

Output:

The value at 1 is 0
The value at 2 is 1078549623
The value at 3 is 32765
------------------------------------
The value at 1 is 8
The value at 2 is 6
The value at 3 is 5
The value at 4 is 4
------------------------------------
The value at 1 is 6.800000
The value at 2 is 0.000000
The value at 3 is 0.000000
The value at 4 is 0.000000
The value at 5 is 0.000000
The value at 6 is 0.000000
------------------------------------
The value at 1 is a
The value at 2 is b
The value at 3 is c
The value at 4 is d
The value at 5 is 

C++

#include<bits/stdc++.h>
using namespace std;
int main(){
    int example1[3];  // prints garbage collection as no assignment done here
    for(int i=0 ;i<3; i++){
        cout<<"The value at "<<i+1<<" is "<<example1[i]<<endl;
    }
     cout<<"------------------------------------"<<endl;
    
    int  example2[4]={8,6,5,4}; // assigned all the values
    for(int i=0;i<4;i++){
        cout<<"The value at "<<i+1<<" is "<<example2[i]<<endl;
    }
     cout<<"-------------------------------------"<<endl;
    
    float example3[6] = {6.8}; 
    for(int i=0;i<6;i++){
        cout<<"The value at "<<i+1<<" is "<<example3[i]<<endl;
    }
     cout<<"-------------------------------------"<<endl;
     
    char example4[6] = {'a','b','c','d'}; 
     for(int i=0; i<5;i++){
        cout<<"The value at "<<i+1<<" is "<< i[example4] <<endl;
    }
}

Output:

The value at 1 is 32767
The value at 2 is -1423211173
The value at 3 is 21845
------------------------------------
The value at 1 is 8
The value at 2 is 6
The value at 3 is 5
The value at 4 is 4
-------------------------------------
The value at 1 is 6.8
The value at 2 is 0
The value at 3 is 0
The value at 4 is 0
The value at 5 is 0
The value at 6 is 0
-------------------------------------
The value at 1 is a
The value at 2 is b
The value at 3 is c
The value at 4 is d
The value at 5 is 

Taking input from the user using for loop

C

#include<stdio.h>
int main(){
    int n, arr[n];
    printf("Enter the size of an array:\n"); 
    scanf("%d",&n);
    printf("Enter the array elements:\n"); 
    for(auto i=0;i<n;i++){
        scanf("%d",&arr[i]);
    }
    for(auto i=0;i<n;i++){   // printing the array elements
        printf("\n Value at %d is %d",i+1,arr[i]);
    }
}

Output:

Enter the size of an array:
4
Enter the array elements:
4 5 6 7
 Value at 1 is 4
 Value at 2 is 5
 Value at 3 is 6
 Value at 4 is 7

C++

#include<bits/stdc++.h>
using namespace std;
int main(){
    int n, arr[n];
    cout<<"Enter the size of an array:"<<endl;  
    cin>>n;
    cout<<"Enter the array elements:"<<endl; 
    for(auto i=0;i<n;i++){
        cin>>arr[i];
    }
    for(auto i=0;i<n;i++){  // loop for printing the array elements
        cout<<"Value at "<<i+1<<" is "<<arr[i]<<endl;
    }
}

Output:

Enter the size of an array:
3
Enter the array elements:
4 78 23
Value at 1 is 4
Value at 2 is 78
Value at 3 is 23

Types of Arrays in C/C++

There are two types of arrays in C/C++

  • One dimensional array
  • Multidimensional array
    • Two-dimensional array 
    • Three-dimensional array
    • Four-dimensional array
    • Five-dimensional array, etc.

We’d discussed the 1-D array so far. Let’s have a look at Multidimensional arrays.

Multidimensional arrays in C/C++

Multidimensional arrays use more than one subscript to describe the array elements.

[ ] [ ] [ ] [ ]  [ ] …….

Two-dimensional arrays use two subscripts, one to represent the row value and the second to represent the column value like [ row ], [ col ]

It’s mainly used for Matrix Representation. Now, let’s have a look at the Declaration of 2-D arrays.

data_type  array_name [ rows ] [ columns ];

For example:

int num[3] [2];

Initialisation of 2-D arrays in C/C++:

data_type  array_name [ rows ] [ columns ] = {values};

For example:
int num [3] [2] = { 1, 2, 3, 4, 5 };
OR
int num [ ] [ ] = { 1, 2 , 3 , 4, 5 };

Advantages of using Arrays in C/C++

  • Code that uses arrays is more organised and readable.
  • Arrays represent multiple data items of the same type using a single name.
  • In arrays, the elements can easily be accessed using the indices.
  • Arrays help in code optimisation.

Disadvantages of using Arrays in C/C++

  • Insertion and deletion operations are too costly in arrays.
  • Wastage of memory happens here since arrays are fixed in size.
  • If there is enough space present in the memory but not in contiguous form, you will not be able to initialise the array.
  • It is not possible to increase the size of the array once you have declared the array.

Frequently Asked Questions

What is an array in C++? Explain with examples.

In C++, an array is a kind of data structure that can store multiple values of the same type. For example, Suppose a class has 67 students, and we need to store the grades of all of them. Instead of creating 67 separate variables, we can simply create an array of size 67: double grade[67];

How many types of arrays are there in C++?

There are many types of arrays in the C++ programming language:
1. 1-D array, which is sometimes known as Vector.
2. 2-D array, which is known as Matrix.
3. Multidimensional array.
A. Three-dimensional array
B. Four-dimensional array
C. Five-dimensional array, etc.

How are arrays classified?

Arrays are classified as homogeneous data structures because they store elements of the same type. We cannot have primitive data types together in a single array. Instead, arrays can store numbers, strings, boolean values (true and false), characters, objects, and so on individually.

Why do we need an array?

Arrays are best for storing multiple values in a single variable · Arrays are better at processing many values efficiently. We can easily access the array elements by using the indices. Arrays are the most used data type in any programming language.

What is the relationship between pointer and array in C?

Array in C is used to store elements of the same types, whereas Pointers are address variables that store the address of a variable. The array variable also has an address that a pointer can point to, and the array can be navigated using a pointer.

What is array decay in C?

The loss of type and dimensions of an array is known as array decay. It occurs when we pass the array into a function by pointer or value. The first address is sent to the array, which is a pointer. That is why the size of the array is not the original one.

How do you pass an array by reference in C++?

C++ does not allow passing an entire array as an argument to a function. However, You can pass a pointer to an array by specifying the array’s name without an index.

Key Takeaways

To summarise, an array is an indexed collection of data elements of the same type. The constraint of the same type is an important one because arrays are stored in consecutive memory cells. Every cell must be the same type (and, therefore, the same size). Arrays are classified as a homogeneous type.

The same elements are objects of the same type placed in interactive memory areas that can be individually targeted using a reference to a different identifier. 

I hope now you have a clear idea of Arrays in C/C++. If you found this article obliging, share it with your friends and make their coding journey fruitful.

By Alisha Chhabra