Different ways to declare array in C

In this article, we are going to learn Different ways to declare array in C. We can declare the arrays in C by using 3 different ways. As you can see in the below 3 programs we are declaring the array using 3 different methods.

Program 1 to Declare an array in C language


In this example, we are declaring an array variable with size 5. later we are asking the user to enter the elements of this array. The size of this array is fixed to 5 at the time of declaration itself.

#include <stdio.h>
int main()
{
  
  int arr[5];

  printf("Enter array elements:\n");
  for(int i=0;i<5;i++)
  {
    scanf("%d", &arr[i]);
  }
  
  printf("The Array elements are:\n");
  
  for(int i=0; i<5; i++) 
  {
     printf("%d ", arr[i]);
  }

  return 0;
}

Output

Please Enter 5 array elements:
1
2
3
4
5
The elements entered are:
1 2 3 4 5 

Program 2 to declare an array in C language


In this example, we are declaring an array of size 5 and also we are assigning the values at the time of initialization itself.This is method with fixed element values at the time of declaration.

#include <stdio.h>
int main()
{
  int arr[5] = {1, 2, 3, 4, 5};
  
  printf("The elements of the array are: ");
  for(int i=0; i<5; i++) 
  {
     printf("%d ", arr[i]);
  }

  return 0;
}

Output

The elements of the array are: 1 2 3 4 5

Program 3 to declare an array in C language


In this example, we are declaring the array with empty square brackets and leaving it to the complier to calculate the size based on the number of elements assigned to this array.But remember this assignation has to be done at the time of declaration itself.

#include <stdio.h>
int main()
{
  int arr[] = {1, 2, 3, 4, 5};
  
  printf("The elements of the array are: ");
  for(int i=0; i<5; i++) 
  {
     printf("%d ", arr[i]);
  }

  return 0;
}

Output

The elements of the array are: 1 2 3 4 5