Arrays
What are Arrays?
The arrays are a collection of elements of the same data type allocated in an adjacent memory location. It is a group of related data items having the same data type.
A collection of variables of the same type that are referred to using a common name is called an array and every element is access through an index associate with that element.
Why do we need arrays?
It helps to represent a large number of elements using a single variable. It also makes accessing elements faster easy to store in memory location using the index of the array that represents the location of an element in the array.
Declaration of array
The array must be declared before they are used. The general form of array declaration is,
data_type array_name[array_size];
Example
int marks[5];
Initialization of Array in C.
After declaring the array it must be initialized.
Array declaration by initializing elements
int marks[]={20,30,40,50,60};
Array declaration by specifying the size and initializing elements.
int marks[5]={20,30,40,50,60};
Advantages of an Array
- To sort the elements of the array, we need a few lines of code only.
- Arrays represent multiple data items of the same type using a single name.
- Traversal through the array becomes easy using a single loop.
Disadvantages of an Array
- Insertion and deletion of elements can be costly since the elements are needed to be managed in accordance with the new memory allocation
- The number of elements to be stored in an array should be known in advance.
- Allocating more memory than the requirement leads to wastage of memory space and less allocation of memory also lead to a problem
Program in C
#include<stdio.h> int main(){ int i=0; int marks[5]={20,30,40,50,60}; //declaration and initialization of array for(i=0;i<5;i++){ printf("%d \n",marks[i]); } return 0; }
Output
20 30 40 50 60
Program in 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
Program in Python
import array as arr a = arr.array('i', [1, 2, 3]) print ("The new created array is : ", end =" ") for i in range (0, 3): print (a[i], end =" ") print() b = arr.array('d', [2.5, 3.2, 3.3]) print ("The new created array is : ", end =" ") for i in range (0, 3): print (b[i], end =" ")
Output
The new created array is : 1 2 3 The new created array is : 2.5 3.2 3.3
Program in Java
class GFG { public static void main (String[] args) { int[] arr; arr = new int[5]; arr[0] = 10; arr[1] = 20; arr[2] = 30; arr[3] = 40; arr[4] = 50; for (int i = 0; i < arr.length; i++) System.out.println("Element at index " + i + " : "+ arr[i]); } }
Output
Element at index 0 : 10 Element at index 1 : 20 Element at index 2 : 30 Element at index 3 : 40 Element at index 4 : 50