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++:
- Random access of elements using array index.
- Use of less line of code as it creates a single array of multiple elements.
- Easy access to all the elements.
- Traversal through the array becomes easy using a single loop.
- Sorting becomes easy as it can be accomplished by writing less line of code.
Disadvantages of an Array in C/C++:
- 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.
- 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:
- Array elements are accessed by using an integer index. Array index starts with 0 and goes till size of array minus 1.
- 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
Post a Comment