Skip to main content

ARRAY

 Array in C/ C++:-



Array declaration by  initializing elements:-
    // Array declaration by initializing elements
    int arr[] = { 10, 20, 30, 40 }

    // Compiler creates an array of size 4.
    // above is same as "int arr[4] = {10, 20, 30, 40}"


Advantages of an Array in C/C++: 
  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 in C/C++: 
  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.

Accessing Array Elements: 
  1. Array elements are accessed by using an integer index. Array index starts with 0 and goes till size of array minus 1.
  2. Name of the array is also a pointer to the first element of array.

Example:- 
➤//C
#include <stdio.h>
int main()
{
int arr[5];
arr[0] = 5;
arr[2] = -10;
arr[3 / 2] = 2; // this is same as arr[1] = 2
arr[3] = arr[0];

printf("%d %d %d %d", arr[0],
arr[1], arr[2], arr[3]);

return 0;
}
//Output: 5 2 -10 5

➤//C++
#include <iostream>
using namespace std;

int main()
{
int arr[5];
arr[0] = 5;
arr[2] = -10;

// this is same as arr[1] = 2
arr[3 / 2] = 2;
arr[3] = arr[0];

cout << arr[0] << " " << arr[1] << " " << arr[2] << " "
<< arr[3];

return 0;
}
//Output: 5 2 -10 5


Comments