Thursday, 30 August 2018

About Array

Often in programming we need to store values of similar data type, to do so we might require multiple variable declarations and that would be tedious to deal with. 
To ease this task, we can take help of Arrays.
  • An Array is a collection of similar type of values or similar Data Types.
  • Data is stored in continuous memory locations.
  • These values can be referred by single variable and the index number (position number).
  • The index number always starts with ZERO.
  • To access the elements of array we use FOR loop.
In C Language we have:
  •     Single Dimentional Array
    • <datatype>  <varName>[<size>];
  •     Multi Dimentional Array
    • <datatype>  <varName>[<size>][<size>]...; 
Limitations:
  • Size or count of values must be known in prior.
  • Arrays are not resizable
  • This leads to memory wastage if requirement is less than the size 
Array based on Data Type
  • Character Array: When we need to store more than one character or string we have use 'char' type array. These arrays have a terminating called 'null' character represented as '\0'. We can create a character array in following ways:
                    A)  Declaration of Array:
                        char Arr1[20];
                        initialization of array:
                        Arr1[0] = 'a';    Arr1[1] = 'b';
                        Arr1[2] = 'c';    Arr1[3] = 'd';
                        Arr1[4] = 'e';    Arr1[5] = 'f';
                        Arr1[6] = '\0';

                    B)  Declaration and Initialization(array initializer):
                        char Arr2[]={'a','b','c','d','e','f','\0'};

                    B)  Declaration and Initialization(string initializer):
                        char Arr3[]="Vilas";

                    D) Declaration and then accepting string from user:
                        char Arr3[20];
                        scanf("%s", arr3);  //don't use '&' before 'arr3'


  • Integer Array : These arrays don't have terminator character. The last element (value) of the array would have index number as SIZE -1. Ways to create 'int' type array:
           A)  Declaration of Array:
                    int arr1[6];
                    initialization of array:
                    arr1[0] = 11;    arr1[1] = 22;
                    arr1[2] = 33;    arr1[3] = 5;
                    arr1[4] = 65;    arr1[5] = 8;

           B)  Declaration and Initialization(Array initializer):
                   int arr2[]={10, 20, 30, 40, 50, 60};

           C) Declaration and then accepting numbers from user:
                   int arr3[5];
                   int i;
                   for(i=0; i<5; i++)
                        scanf("%d", &arr3[i]);


            *** Same is for 'float' and 'double'

0 comments:

Post a Comment

Introduction to C# .NET

It  is  pure  object  oriented  programming  language.  Also  it  is  Event Driven Programming Language. It is case sensitive. ...