Menu Close

Arrays in C

Arrays:

  • Array is a collection of same type elements under the same identifier referenced by index number.
  • Arrays are widely used within programming for different purposes such as sorting, searching and etc.
  • Arrays are of two types single dimension array and multi-dimension array. 
  • Each of this array type can be of either static array or dynamic array.
  • Static arrays have their sizes declared from the start and the size cannot be changed after declaration.
  • Dynamic arrays that allow you to dynamically change their size at runtime, but they require more advanced techniques such as pointers and memory allocation.
Syntax:
      datatype identity [size];

For example
      int arr[5]; 
  • Here int specifies the type of the variable and the word arr specifies the name of the variable.
  • The number 5 tells the number of elements of type int that will be in the array and is called the dimension of the array.
  • Array elements get consecutive memory locations.
  • Array variable stores base address of memory block
  • Array elements can be processed using index
  • Array index starts with 0 to size-1
  • Address of the first element is called the base address and it is also the start address of an array.
  • The address of the ith element is given by the following formula,
    • Addressi = base_address + i*size_of_element

Initializing Arrays

  • Initializing of array is very simple in c programming.
  • The initializing values are enclosed within the curly braces in the declaration and placed following an equal sign after the array name.
  • Here is an example which declares and initializes an array of five elements of type int.
    • int arr [5] = {1, 2, 3, 4, 5};

If the array variable is local and int type, all the elements initializes with garbage values as follows:

#include<stdio.h>
int main()
{
	int arr[5],i;
	printf("Elements are :\n");
	for(i=0 ; i<5 ; i++)
	{
		printf("%d\n", arr[i]);
	}
}

If the variable is Global, all the elements initializes with default values as follows:

#include<stdio.h>
float arr[5];
int main()
{
	int i;
	printf("Elements are :\n");
	for(i=0 ; i<5 ; i++)
	{
		printf("%f\n", arr[i]);
	}
}
  • We can assign values directly to array variable.
  • If we assign at least one value, other elements initializes with default values.
#include<stdio.h>
int main()
{
	int arr[5]={10,20};
	int i;
	printf("Elements are :\n");
	for(i=0 ; i<5 ; i++)
	{
		printf("%d\n", arr[i]);
	}
}