Arrays

The array is a type of data structure that can easily store a collection of elements of the same type. It is used to store a collection of data. In an array instead of declaring a separate variable for each number like number 1, number 2, you can declare only one array variable like numbers and then use it as numbers[0], numbers[1], etc.

 

Here is a syntax to declare an array in C programming.

type arrayName [ arraySize ];

 

In the above syntax, the array size must be greater than 0.

for example

double balance[10];

 

To access array elements watch this example

 

double salary = balance[9];

 

Here is a C program to clear your concepts in the array.

 

Program:

#include <stdio.h>

 

int main () {

 

   int n[ 10 ]; /* where n is an array of 10 integers */

   int i,j;

 

   /* To initialize an elements of array n to 0 */         

   for ( i = 0; i < 10; i++ ) {

      n[ i ] = i + 105; /* TO set an element at location i to i + 100 */

   }

   

   /* Print each array element's value as an output */

   for (j = 0; j < 10; j++ ) {

      printf("Element[%d] = %d\n", j, n[j] );

   }

 

   return 0;

}

 

Output:

Element[0] = 105 

Element[1] = 106 

Element[2] = 107 

Element[3] = 108 

Element[4] = 109 

Element[5] = 110 

Element[6] = 111 

Element[7] = 112    

Element[8] = 113 

Element[9] = 114  

 

In C language there are many types of array. Let's know in brief about this array.

Concept

 Description

  • Multi-dimensional arrays

C usually supports multidimensional arrays. The simplest form of the multidimensional array is the two-dimensional array.

  • Passing arrays to functions

You can pass to the function a pointer to an array by adding the array's name without an index.

  • Return array from a function

C language allows a function to return an array.

  • Pointer to an array

You can easily generate a pointer to the first element of an array by simply specifying the array name, without any index.