Array - Devbhoomi

FREE JOB ALERT & ONLINE TUTORIALS

Hot

Post Top Ad

Sunday 5 November 2017

Array

Array is collection of similar data type. for example array of int type data or float. important thing to note is array can only have data of same type only. we cannot have combination of different data type.
Important points about Array
  • index of array starts with zero (0).
  • index of last element in array is n-1, where n is the size of the array
  • array has static memory allocation. i.e memory size once allocated for an array cannot be changed.
Array declaration syntax :

    datatype array_name [array_size];

Example :

    //int is datatype, a is array name, 10 is size of array
    int a[10];
    ..
    float f[13];
    char name[15];
    double d[8];

Array initialization

    int a[10] = { 2,3,4,5,6,7,8,9,10,11};

    // initialize to 1,2,0,0,0...
    int a[10] = { 1, 2 };

    // all elements 0
    int a[10] = { 0 };

    char name[15] = "Yogesh";

Accessing elements of array

    #include <stdio.h>

    int main ()
    {
    int a[10] = { 2,3,4,5,6,7,8,9,10,11};
    int i = 0;

    int lengthOfArray = sizeof(a)/sizeof(int);

    printf("Length of array is : %d"\n,lengthOfArray);

    for(i = 0;i < lengthOfArray; i++)
    {
    printf("array element at index[%d] = %d\n",i,a[i]);
    }
    return 0;
    }
Output :
 Length of array is : 10
 array element at index[0] =  2
 array element at index[1] =  3
 array element at index[2] =  4
 array element at index[3] =  5
 array element at index[4] =  6
 array element at index[5] =  7
 array element at index[6] =  8
 array element at index[7] =  9
 array element at index[8] =  10
 array element at index[9] =  11

No comments:

Post a Comment

Post Top Ad