Skip to main content

Declaring Arrays in C

Array declaration in C

  • An array declaration or statement refers to the creation of an array.
  • The declaration specifies the type of elements the array will contain, the name of the array, and the size of the array.

Syntax of array in C

The syntax for declaring an array in C is as follows:

data_type array_name[array_size];

where:

  • data_type: is the data type of the elements that the array will store, such as int, float, char, etc.

  • array_name: is the name you assign to the array.

  • array_size: is an integer value that specifies the number of elements the array can store.

For example:

To declare an array of 10 integers, you would write:

int numbers[10];

You can also initialize the elements of the array at the time of declaration.

For example:

int numbers[5] = {1, 2, 3, 4, 5};

This declares an array numbers of 5 integers and initializes its elements with the values 1, 2, 3, 4, and 5.

Array Declaration of different data types

Here are some examples of array declarations for different data types:

Integer Array

int numbers[10];

Floating Point Array

float decimals[5];

Character Array

char letters[20];

Double Precision Floating Point Array

double precision_decimals[10];

Boolean Array

_Bool flags[8];

Array Declaration - Example

#include <stdio.h>

int main()
{
int i;
int numbers[10]; // declare an array of 10 integers

// initialize the elements of the array
numbers[0] = 10;
numbers[1] = 20;
numbers[2] = 30;
numbers[3] = 40;
numbers[4] = 50;
numbers[5] = 60;
numbers[6] = 70;
numbers[7] = 80;
numbers[8] = 90;
numbers[9] = 100;

// print the elements of the array
printf("The numbers are:\n");
for (i = 0; i < 10; i++)
{
printf("%d ", numbers[i]);
}

return 0;
}
Output:

Explanantion

  • In the main function, we declare an array of 10 integers named numbers. We then use a series of statements to initialize the elements of the array with the values 10, 20, 30, and so on.

  • Then, we use a for loop to print the elements of the array. The for loop starts by initializing the variable i to 0, and it continues until i is equal to 10.

  • In each iteration of the loop, we print the value of numbers[i] to the screen.