top of page

Arrays in C/C++



Arrays

An array is a collection of similar data items stored at contiguous memory locations and elements can be accessed randomly using indices of an array. They can be used to store collection of primitive data types such as int, float, double, char, etc., of any particular type. To add to it, an array in C/C++ can store derived data types such as the structures, pointers etc.


Given below is the picture representation of an array.



Syntax:


Single -Dimensional Array: The ArraySize must be integer constant greater than Zero and type can be any valid C Data Type.

type ArrayName [ ArraySize ];
double balance [10];


Example:

#include <iostream>
#include <string>
using namespace std;

int main() {
  string cars[4] = {"Volvo", "BMW", "Ford", "Ferrari"};
  cout <<"Output of Cars[2] array is " <<" " << cars[2];
  return 0;
}

Output:




Loop through Array

You can loop through the array elements with the for loop.


Example:

#include <iostream>
#include <string>
using namespace std;

int main() {
  string Fruits[4] = {"Apple", "Mango", "Banana", "Orange"};
  for(int i = 0; i < 4; i++) 
  {
    cout << Fruits[i] << "\n";
  }
  return 0;
}

Output:



Advantages of an Array:

  1. Random access of elements using array index.

  2. Use of less line of code as it creates a single array of multiple elements.

  3. Easy access to all the elements.

  4. Traversal through the array becomes easy using a single loop.

  5. Sorting becomes easy as it can be accomplished by writing less line of code.


Disadvantages of an Array:

  1. Allows a fixed number of elements to be entered which is decided at the time of declaration. Unlike a linked list, an array in C is not dynamic.

  2. Insertion and deletion of elements can be costly since the elements are needed to be managed in accordance with the new memory allocation.



The Tech Platform

0 comments

Recent Posts

See All

Commentaires


bottom of page