C - Arrays

A variable can hold only one literal value at a time, If you want to store 100 different values then you have to declare 100 different variables which is very difficult. To overcome this problem, C Language introduced the concept of an arrays.

An array can be defined as an collection of homogeneous (similar type) elements. For example, an integer array holds the elements of int types, a float array hold the elements of float types etc.

Some important points about C Arrays:

  1. Arrays are always stored in continuous memory allocation.
  2. An array can store multiple values which can be referenced by a single name followed by an index inside a square bracket '[]'.
  3. Array index is a number starting from 0, which will be increased by 1, till the maximum specified array size.
  4. Array index cannot be negative.
  5. An array can be an integer, float, character data type, can be initialized only once, during declaration time.

Arrays can be categorized into 2 categories:

  1. One Dimensional Array or 1D-Array
  2. Two Dimensional Array or 2D-Array

One Dimensional Array

A one-dimensional array is one directional array, which contain only one single row and multiple columns. One-dimensional array can be declared as follows:

data_type array_name[array_size];
int arr[5];
1D Array | ankitweblogic.com

Example 1: WAP to input 10 numbers in 1D-Array and print them. 1

#include<stdio.h>
void main()
{
	int a[10], i;
	printf("Enter 10 numbers: ");
	for(i=0;i<=9;i++)
    {
        scanf("%d", &a[i]);
    }
    printf("\nInput numbers are:\n");
    for(i=0;i<=9;i++)
    {
        printf("%d ",a[i]); //display array values
    }
}
Enter 10 numbers: 1 2 3 4 5 6 7 8 9 10
Input numbers are: 1 2 3 4 5 6 7 8 9 10

Array Declaration with Initialization

Array values can be input from user or can be declared directly.

int a[5] = {10,20,30,40,50}; //Declaration with Initialization
int a[] = {20,30,40,50,60}; //can define without specifing the size.

Example 2: WAP to initialize array elements. 1

#include<stdio.h>
void main()
{
    int i;
    int a[5] = {10,20,30,40,50}; //Declaration with Initialization
    printf("Array list is:\n");
    for(i=0;i<=4;i++)
    {
        printf("%d ", a[i]);
    }
}
Array list is: 10 20 30 40 50
Advantage of C Array
  1. Code Optimization: Less code to the access the data.
  2. Easy to traverse data: By using for loop, we can retrieve the elements of an array easily.
  3. Easy to sort data: To sort the elements of array, we need a few lines of code only.
  4. Random Access: We can access any element randomly using the array.
Disadvantage of C Array
  1. Fixed Size: Size of array cannot grow dynamically.
  2. Wastage of memory: Number of elements must be known in advance, otherwise enough space can be wasted.
  3. Some operations like Insertion and Deletions require extra time, because insertion and deletion requires enough shifting of elements.
Advertisement