'Coding has over 700 languages', '67% of programming jobs aren’t in the technology industry', 'Coding is behind almost everything that is powered by electricity'
Last Updated: Sep 26, 2023
Easy

Arrays

gp-icon
Data structures & algorithms (Beginner to Intermediate)
Free guided path
13 chapters
99+ problems
gp-badge
Earn badges and level up

Introduction

Data structures are used while coding in any programming language, they are used to store data and values of different types. Suppose, If we want to store the values of a number of objects, if the number is smaller, we can use normal variables like (var1,var2,...) but if the number is larger, it is not possible to do so using normal variables. In such a scenario, a data structure called array comes in handy, arrays are used to represent many instances in one variable. Arrays are one of the most widely used data structures available in almost every programming language. An array is defined as a collection of similar data items stored at contiguous memory locations. They can store values of primitive ( like int, float, char, etc.) and derived (structure, pointers, union) data types.

Also Read About, Sum of Digits in C, C Static Function

Declaring and Initializing an Array

By specifying the size of the array

// directly specifying the size
int array_1[5];

//using a variable to specify its size
 
int n=5;
int array_2[n];

 

Note: When using a variable to specify the size of an array, it should be taken care that the variable is initialized before array declaration, and the value of the variable should be a positive integer as the array can't be of negative size

By initializing elements of the array

//elements must be enclosed within the opening and closing curly braces separated by comma
int array[] = {1,2,3,4,5};
// the compiler creates an array of size 5
Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

By specifying the size and initializing elements

// compiler creates an array of size 5 and initialises the elements as specified by the programmer
int array[5] = {1,2,3,4,5};

 

In case the size of the array mentioned by the user is more than the number of elements specified, then the compiler initializes the array with the specified values and the remaining places are initialized with a value 0. 

Understanding array in detail

Index

Arrays have a fixed size, each element stored in the array has some index value associated with it. Indexing in an array starts from 0 to the (size of the array -1). While traversing arrays using loops, the upper and lower bounds of the index must be taken care otherwise, the compiler throws compilation error or garbage value. Using array index, we can print or change the value of that particular element at that index. Array index helps us to access the array elements randomly.

Example

#include<bits/stdc++.h>
using namespace std;

int main(){
    int a[5]={1,2,3,4,5};
    cout<<"Element at index 2 : "<<a[2]<<endl;
    cout<<"Element at index 1 : "<<a[1]<<endl;
    cout<<"Element at index 4 : "<<a[4]<<endl;
    cout<<"Element at index -8 :"<<a[-8]<<endl;

}

 

Output

9:36: warning: array index -8 is before the beginning of the array [-Warray-bounds]
    cout<<"Element at index -8 :"<<a[-8]<<endl;
                                  ^ ~~
Element at index 2 : 3
Element at index 1 : 2
Element at index 4 : 5
Element at index -8 :180444982

 

Elements in the array are stored at contiguous memory locations

As elements are stored at contiguous memory locations therefore the address of any particular index value can be easily calculated

Example

#include <bits/stdc++.h>
using namespace std;
  
int main()
{
    // to calculate address of any index in array
    // address of a[0] + sizeof(data_type)*(n - starting index)
    // where n is the position of element whose address is to be calculated

    int a[5];
  
    cout<<"Size of integer : "<<sizeof(int)<<endl;
  
    for (int i = 0; i < 5; i++)
        // & operator is used to get the address of variable
        cout << "Address a[" << i << "] is "<< &a[i]<<endl;
  
    return 0;
}

 

Output

Size of integer : 4
Address a[0] is 0x7ff7b9b8e400
Address a[1] is 0x7ff7b9b8e404
Address a[2] is 0x7ff7b9b8e408
Address a[3] is 0x7ff7b9b8e40c
Address a[4] is 0x7ff7b9b8e410

 

Ways to Traverse

Arrays can be easily traversed using any kind of loop. Arrays can be traversed from either left to right or right to left. 

Example

#include <bits/stdc++.h>
using namespace std;
  
int main()
{
  int a[5]={1,2,3,4,5};
  //to traverse from left to right
  cout<<"Traversing array from Left to Right : ";
  for(int i=0;i<5;i++)
        cout<<a[i]<<" ";

    cout<<endl;

    //to traverse from right to left
  cout<<"Traversing array from Right to Left : ";
    for(int i=4;i>=0;i--)
        cout<<a[i]<<" ";

}

 

Output

Traversing array from Left to Right : 1 2 3 4 5 
Traversing array from Right to Left : 5 4 3 2 1

Advantages 

  • Arrays support random access of elements. The array index is used for random access of array elements.
  • By using arrays, we need to code fewer lines and use fewer variables as it represents many instances in one variable.
  • All the elements of an array can be traversed either from left to right or right to left using just one loop.
  • In arrays, elements are stored at contiguous memory locations therefore, there is no extra memory being allocated. Hence using arrays avoids overflow or shortage of memory.
  • Arrays are versatile, that is, using arrays, other data structures like Linked-lists, stacks & queues, trees, etc., can be easily implemented.

Disadvantages

  • Array is a static data structure that is of a fixed size. An array cannot grow in size during runtime.
  • Making changes in an array-like insertion and deletion is difficult as elements are stored at contiguous locations; therefore, shifting operation is to be performed, which is costly.
  • If an array is declared with an inaccurate size, that is, if the size of the array is smaller than required, then it causes a problem, or if it is larger than required, then it causes wastage of memory.


You can also read about C dynamic array and  Short int in C Programming

Frequently Asked Questions

Ques: What will happen if we use the array after declaration before it is initialized?

Ans: if an array is declared and used before initialization, then the compiler will return garbage value or throw compilation error.

 

Ques: Why are arrays considered versatile?

Ans: Arrays are versatile because many other data structures like a tree, graphs, LinkedList, etc., can be easily implemented using arrays.
 

Ques: How much memory is required to store an array of type integer and size 5?

Ans: An integer variable requires 4 bytes. In order to declare an array of size 5 of type integer, we require 5*4, that is, 20 bytes of memory.

Key Takeaways

In this blog, we have covered the following topics:

  • We first discussed what arrays are how can we declare and initialize arrays?
  • Then we discussed the advantages and disadvantages of using arrays.

Many other data structures are used for different purposes like strings are used to represent a sequence of characters and many more.

In order to write a well-structured code, knowledge of functionsstructures, and different data types is very important.

Next article
Arrays in C Programming
Guided path
Free
gridgp-icon
Data structures & algorithms (Beginner to Intermediate)
13 chapters
109+ Problems
gp-badge
Earn badges and level up
Live masterclass