ARRAYS IN C

Arrays in C Programming Language is a type of data structure that can store a fixed-size subsequent collection of elements of the same kind. It is required to store a set of data, but it is usually more beneficial to consider an array as a set of variables of the same type.

Alternatively, of declaring each variable, such as num0, number1, …, and num99, you represent one array variable such as numbers and use num[0], num[1], and num[99] to represent individual variables. An index accesses a specific element in an array.

All arrays consist of adjacent memory locations. The lowest address corresponds to the first element and the highest address to the last item.

HOW TO DECLARE AN ARRAY IN C PROGRAMMING LANGUAGE?

To declare an array in C, you need to specify the type of the elements and the number of items needed by an array as follows −

type array_Name [ array_Size ]; 

This is called a single-dimensional array.

HOW TO ACCESS AN ARRAY ELEMENT?

An element is obtained by indexing the array name. This is done by placing the index of the element within square brackets after the name of the array. For example −

double salary = balance[9];

The above statement will take the 10th element from the array and assign the value to the salary variable. The following example Shows how to use all the three above mentioned concepts viz. declaration, assignment, and accessing arrays

SAMPLE CODE:

#include <stdio.h>
 
int main () {

   int n[ 10 ]; /* n is an array of 10 integers */
   int i,j;
 
   /* initialize elements of array n to 0 */         
   for ( i = 0; i < 10; i++ ) {
      n[ i ] = i + 100; /* set element at location i to i + 100 */
   }
   
   /* output each array element's value */
   for (j = 0; j < 10; j++ ) {
      printf("Element[%d] = %d\n", j, n[j] );
   }
 
   return 0;
}

When the above code is compiled and executed, it produces the following result −

Element[0] = 100
Element[1] = 101
Element[2] = 102
Element[3] = 103
Element[4] = 104
Element[5] = 105
Element[6] = 106
Element[7] = 107
Element[8] = 108
Element[9] = 109

Leave a Reply

Shopping cart