Array




Array:

Difference between Array and Structure:
                              Array
                              Structure
1.      In array memory is static. We define the memory on declaration of array.
1.      In structure, memory is dynamic.
2.      It uses subscript to access elements.
2.      It uses Dot operator to access elements.

3.      Array is a base pointer and it points to base location
3.      Structure is not a pointer type.
4.      Array is collection of homogenous data.
4.      Structure is collection of heterogenous data.
5.      Array is derived data type.
5.      Structure is user defined data type.



·        In C languages, user can design a set of similar data types. When we need to store more than 1 value of similar data type, we use Array.
·        In c language, a simple variable can store only one value at a time. If we change the value, then previous value will be lost.
·        Suppose you have to work with 100 numbers, Imagine the difficulty and time taken to type in names of 100 variables names. Array is here for rescue. But it does not mean that if we need only two variables and we are using Array.


To know about the Array, let we go through a simple example.

Simple Array Program:
“Suppose you have to sum ‘n’ number of integers. If you are thinking of taking ‘n’ number of variables and then you will sum all these ‘n’ variables…..you are inviting trouble with memory. That’s exactly what array is meant for!!” 
               In this example, we will demonstrate the sum of ‘n’ number of values using array.

#include <stdio.h>
#include <conio.h>

int main()
{
               int sum=0,i;      
               // Array Declaration
               int arr[10];
               for(i=0;i<10;i++)
               {
                              printf("Enter the Value \t:");
                              scanf("%d",&arr[i]);
               }
               for(i=0;i<10;i++)
               {
                              sum=sum+arr[i];
               }

               printf("\n\n   Sum of All Numbers    %d\n\n",sum);
               return 0;  
}




Output :



This sample program having some new parts, Let take a look into it:
1.      Array Declaration:
2.      Accessing Array Elements.
3.      Entering values to Array elements.
4.      Fetching Array Elements value.

1.      1Array Declaration:
To begin with Array we should know how to declare Array:
Syntax:    

                dataType arrayName[size]; 

         -       dataType refers to which type of array you want to declare (int, char, float etc).
         -       arrayName is user defined name of array.
         -       Size refers to number of elements which a array should have.

Note:
   When we declare an array in C language, it allocates continues memory for that element.
So for our sample program case it will allocate 20 blocks of memory. Memory size may be dependent on compiler.

2.      2. Accessing  Array Elements:
        Once the array is declared, let see how to access each element of array.
·        In array we access the elements by subscript values.
·        Subscript is a number in brackets following the array name.
·        In array this numbers starts from 0. It means if you defined size of array as 10, then your subscripts value will be between 0-9.
·        Suppose we want to access 3rd element, then we will use arr[2]. By accessing array is such a way makes array very efficient and useful.

3.      3. Entering values in Array Elements:
-        Enter values in array is as similar as we use a simple variable to store variable.
-        We use (&) operator to read value, as similar we use to read value of a variable.

4. Fetching array Elements value:
-        Fetching of elements is also similar like fetching from a variable.
-        We use arrayName with subscript to get the value of that element. 



Array Initialization:
     We can also initialize the array at time of declaration.Lets have simple example to demonstrate this. We will look into these two examples.
Example 1:








#include <stdio.h>
#include <conio.h>


void main()
{
               int arr[10]={1,2,3,4,5,6};
               int i;
              
               for(i=0;i<6;i++)
               {
                              printf("Value \t: %d\n",arr[i]);
               }


}





In this example we define size of array as 10 , but the values in curly braces is only 6. So what will be the other 4 values? Other 4 will be garbage values. So the first 6 values of array will be user defined values and other will be garbage values.
  So if we declare a array, then we should take care of garbage values, else it will produce some unexpected results.

Example 2:

#include <stdio.h>
#include <conio.h>

void main()
{
               int arr[]={1,2,3,4,5,6};
               int i;
              
               for(i=0;i<6;i++)
               {
                              printf("Value \t: %d\n",arr[i]);
               }
}





In this example we did not define size of array and put some values in curly braces. So the size of elements will be total number of values in those curly braces. In this type of declaration, compiler counts the total values and assign the memory accordingly.
                      These two methods are use to initialize the array, So which method is a good method ?

Let see –
In first example we declare the size of array as 10, but we really require 6 elements. Then there will be wastage of memory in first case. While in second method, compiler assigns the memory on compile time. So their will not be memory loss.

Passing Array elements to Function:

Array elements can be passed to function by two methods-
a.      Pass by value
b.      Pass by reference
It is same way we pass a variable to function. Because a single array element behave as variable only.
As we know in pass by value, we pass value of element and in pass by reference, we pass address of element. Lets demonstrate by example:

Pass by value:

  #include <stdio.h>
  #include <conio.h>

  void square(int choice);   // function declaration

  void main()
  {
               int arr[]={1,2,3,4,5,6};   // array initialization
               int i;
               for(i=0;i<6;i++)
               {
                              square(arr[i]);   //calling function display
               }
  }

  void square(int choice)
  {
               printf("\t%d\n",choice*choice);

  }




This is a simple demonstration of how to pass a variable or array element by value.

Pass by reference:


  #include <stdio.h>
  #include <conio.h>

  void square(int *choice);                // function declaration

  void main()
  {
               int arr[]={1,2,3,4,5,6};      //array initialization
               int i;
               for(i=0;i<6;i++)
               {
                              square(&arr[i]);
               }
  }

  void square(int *choice)               // function definition     
  {
               printf("\t%d\n",*choice * *choice);

  }






This is a demonstration of pass by reference example. In this example, we pass address of variable or array element to function. To pass address of variable to function, we use reference operator (&).
In display function, argument is not a simple variable, it’s a Pointer variable.
              What will happen, if we simply use a variable here ? Let see….


  #include <stdio.h>
  #include <conio.h>

  void square(int *choice);                // function declaration

  void main()
  {
               int arr[]={1,2,3,4,5,6};      //array initialization
               int i;
               for(i=0;i<6;i++)
               {
                              square(&arr[i]);
               }
  }

  void square(int choice)               // function definition     
  {
               printf("Input  :   %d\n",choice);
  }

In this example, we are not printing square of the number, we will display only the value, which is passed to that function. Let have a look to output –




Printed values are not desired value, which we pass to function. Is it garbage values? No, because if we look at output, it’s having increment of 4 in each value (compiler dependent value). This is address of array element. Element 0 located at 1310568, and each element is having 4 bytes memory. So the next element located at 1310572 and so on. We will discuss about pointer in pointer section.

Passing Entire array to Function:
 We can also pass entire array to a function. If we want to pass entire array, then we must pass length of array. Because If we did not pass length of array, we can’t find length of array in function, this may add some garbage values to our logic or some values may be truncated.
               Entire Array can be pass by reference only. If we need to send array to function , then we need to send address of first element of array and by using first element address, we can find other elements also.
               First element address also can be send by two ways. We will demonstrate both methods here.    
Example 1:


 #include <stdio.h>
 #include <conio.h>

 void square(int[],int);                // function declaration

 void main()
 {
               int arr[]={1,2,3,4,5,6};      //array initialization
               square(arr,6);
 }

 void square(int choice[],int n)               // function definition     
 {
               int i=0;
               for(i=0;i<n;i++)
                              printf("\t%d\n",choice[i]*choice[i]);
 }



Output:






In example 1, to pass address of first element to function, we are passing array name. In C, array name refers to address of first element. So if we pass array name to a function, actual we are passing address of first element.
               In function, we define another array in formal parameters. We need this array because now this array will point to the memory location, which we are passing into function. This can be better explained by this image –

So now in square function, we can perform our operations. Remember, If we make changes in values, then it will also reflect to array (arr) of main function.

Example 2:

  #include <stdio.h>
  #include <conio.h>

  void square(int*,int);                // function declaration

  void main()
  {
               int arr[]={1,2,3,4,5,6};      //array initialization
               square(&arr[0],6);
  }

  void square(int *choice,int n)               // function definition     
  {
               int i=0;
      for(i=0;i<n;,i++)
       {
               printf("\t%d\n",*choice);
       }
  }






In example 2, we are passing address of first element by using Address of operator (&). So we pass &arr[0] to function. by this way we also get address of first element only.
             But formal parameter of function is not array (In example 1, it was array), It is a pointer variable. So now this pointer variable will point to first element of array. To iterate through all values of array, we need this pointer variable to point next memory locations one by one. We will increment the value of pointer variable by 1 and it will point to next location. This can be more explained by this image –


Comments

Popular posts from this blog

Disable or enable proxy for Internet explorer or Chrome

chm viewer unable to show contents

3 prisoners and 5 hats puzzle