CLANGUAGE UNIT II


 Array
(Numeric Array) is the collection of the homogenous data types that is the similar type of data get stored in contiguous memory locations to allotted by the compiler while executing the array. An array can be accessed by its indices which are given by the compiler accordingly. If we declare the array like int a[10] then allocation takes place in the following ways :


An array of all types of data can be declared easily like fundamental data types or derived data types and user-defined data types.


Reason for using Arrays :

Arrays mean a group of homogenous or similar types of data is if we want to work on a large number of data of similar type then declaring of variables we must have to work hard to manage such quantity of data. like int a1,a2,a3,a4,a5,a6,a7,a8,a9,a19;

or we can declare it using int a[10]; statement


Types of Array :

Depending on the number of square brackets used, the array is one dimension, two Dimension, and multi-dimension types.
In 1d array the declaration  should be  int a[5];
In 2d array the declaration should be   int a[3][4];
In multi D array the declaration should be int a[2][3][4];


How to declare and initialize the Array

An array can be declared both statically and dynamically .  for example :

Static initialization :   int x[10];

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

In such a type of declaration, the array limit is automatically assigned by the compiler by counting the number of elements initialized.


Properties  of Array :

  • The array is a linear and homogenous  data structure or we can say Array is the fixed-sized sequentially collection of the elements of similar data type
  • Memory allocation is contiguous that is depending upon the type of data size of the next element automatically increased by the size of the type of data.
  • It is also called a subscripted variable.
  • index of the array starts from 0 that is the lower bound of the array is 0  and the upper bound is less than 1, for example, int a[10]   it means the lower bound is 0 and the upper bound is 10-1=9.
  • Array's name itself is a pointer.
  • All the elements of the array share the same name but they differ from each other on the basis of the index value and value they initialized.
  • Amount of the memory required to store the array depends upon the type of data and size  that is the number of elements
          TOTAL BYTES = SIZE OF(DATA TYPE) * SIZE OF ARRAY(INDEX)

  • Once the array is created we cannot reallocate the memory or change the memory allocation
  • The initial value of an uninitialized array is garbage as it belongs to the automatic storage class if no other prefix is added to it( like register extern or static).

     

      

Advantages of Using Arrays :

  • Random access of the elements of the array is very easy as elements can be accessed using the index of the array.
  • A large number of elements can be stored without declaring a large number of names of the variable.
  • All operations like LIFO or FIFO traversal is easily presentable.
  • Used to represent all types of lists
  • other data structures like heap stack queues can be represented using the array

   

   

   Limitations  of  Arrays 

  • Fixed memory blocks are created 
  • insertion and deletion are costly as the insertion need to reshuffle elements and deletion also need the same.                   

  

Applications  of  Arrays 

  • Contiguous memory allocation
  • indexed storage
  • Grouping of similar variables
  • mathematical operation on a matrix

Representation of Array
The array can be represented  by row-major and column-major representation .let we discuss them:
  • Row major representation: The row of the elements of the array can be printed first  and then the second row for example 
    int a[][]={1,2,3,
                     4,5,6
                     7,8,9};
    row-major representation  {1,2,3,
                                                 4,5,6
                                                 7,8,9} 
    Calculating the address of the elements of the array  (1 d array )
    the formula is Address of a[i]=B+W*(i-LB)  where 
    i=index of the element whose address to be found
    B=base address
    W=Storage size of a single element or size of type of data
    LB=Lower Bound of the array

    Calculating the address of the elements of the array (2d array) (Row major)

    Address of A[I][J] = B + W * ((I – LR) * N + (J – LC))

    I = Row Subset of an element whose address to be found,
    J = Column Subset of an element whose address to be found,
    B = Base address,
    W = Storage size of one element stored in an array(in byte),
    LR = Lower Limit of row/start row index of the matrix(If not given assume it as zero),
    LC = Lower Limit of column/start column index o
    f the matrix(If not given assume it as zero),
    N = Number of columns given in the matrix.
  • Column major representation : The column elements of the array printed first like 
        {1,4,7
          2,5,8
          3,6,9}
    Calculating the address of the elements of the array(2d array)(Column major)
    Address of A[I][J] = B + W * ((J – LC) * M + (I – LR))

    I = Row Subset of an element whose address to be found,
    J = Column Subset of an element whose address to be found,
    B = Base address,
    W = Storage size of one element stored in any array(in byte),
    LR = Lower Limit of row/start row index of the matrix(If not given assume it as zero),
    LC = Lower Limit of column/start column index of the matrix(If not given assume it as zero),
    M = Number of rows given in the matrix.



Functions in C:

Generally, functions are small piece of dependent code which has certain functionality and depends upon the main function for its execution. A function may call again and again depending upon the need of that code.

Advantages of Functions :

  • Since a function is a small piece of code capable of performing any action thus by calling it again and again we can easily avoid the rewriting of the code .
  • A large problem can be divided into samll modules called the function
  • basics of the modular programming enhance the testing practices 
  • Function call may cause to move the control of program in another direction by keeping the address of its line of code into the stack pointer then return back after executing the function starts from same point may cause little bit overhead in the program
  • inline functions may cause addition of the function code depending upon certain conditions to the main function while executing the program which may cause expansion of program at the runtime.
  • Function may cause the program divion of  work.

Syntax of the Function :

A function has the following part : 
  • return type: A function only return single value of  any data type or it may return the address of any data type.
  • Name of the function: name of the function is an identifier and it follow all the naming conventions that are followed by the variable names 
  • Arguments list : The argument of the function should be any type of the data ,address or pointers .for example :
      <return type><ideniier>(<arguement list>); 

Important Terms Regarding the Functions :

  • Function Declaration: A function declaration statement is also known as the prototype of the function as it contains the function header without any code. The function header includes the:   return type, function name, and arguments list as mentioned in the next para.
  • Function call: The calling of function takes place according to the need as the calling must take place in the main function.


Types of the Functions :

basically, functions are of two types: 
1. inbuild functions: The functions which are already defined and linked to the library of C language are called the inbuild functions as the different header files are the collection of the different functions which we can directly use by including the header file in our program for example if we want to use the exit() function which is inbuild in process.h header file then we must have to include that file before using that function.
2. user-defined functions: User-defined functions are those functions that are defined in a particular program properly so that we can use that function at that program. that is there is a method for how to define the function in a program we have to follow the steps to define the function.
first, we have to declare the prototype of the function in which we have to mention the name of the function and its return type and arguments list. then we can call the function in the main function then after the main function we can define that function.
for example :
#include<stdio.h>
void add();
void main()
{
printf("\nIn the main function ");
add();
}
void  add()
{
printf("\nIn the add function ");
}
here is the function in which we first declare the prototype of the function it means we have to tell the compiler that we are using such format function then call at the main function -- fits the compiler check the prototype of the function then search the definition of the function if everything ok then execution takes place of the function will show the result.\
Another type of  defining the user-defined function is without giving a prototype we can define a function globally just after the header file and thus direct calling takes place such as 
#include<stdio.h>
void  add()
{
printf("\nIn the add function ");
}
void main()
{
printf("\nIn the main function ");
add();
}
here the function is without the prototype thus while calling the function it is directly executed.

Types of the Function On the basis of Arguments and Return Value

  • No argument and No return value : Such functions have no argument and no retrning any value.like 
    #include<stdio.h>
    void display();
    void main()
    { printf("\nThis is the main function ");
    display();
    }
    void display ()
    { printf("\nThis is the display fumction and must be called in the main function.");
    }
    During the execution of the program 
  • Argument but no return value
  • No argument but the return value
  • Argument and return value 


Formal Argument and Actual Argument

A parameter is an optional list of variables in functions that are used to pass the values from one function or module to another function.such parameters value either passed through the main function or given as default value in the function prototype or the defination of the function for example :
#include<stdio.h>
void add(int a,it b=100);
int main(){
add(300,200);   //  function call
add(400);          // function call
}
void add(int x,int y)
{
printf(""\nSum=%d",x+y);
}
the value of the parameter given while writing the prototype of the function is called the formal argument and the argument which is given while calling the function is called the actual argument.
Actual arguments always overwrite the formal argument.
during the second call, the function has only one value given at the time of calling depicts that the second value is the default value . There is no need to mention the second value as it was already given in the function.

Local and global variables :

Local variables

Global variables

I t is generally declared inside a function body.

· If it isn’t initialized at the time of declaration a garbage value is stored in it.

· It is created when the function begins its execution.

· It is lost when the function is terminated.

· Data sharing is not possible since the local variable/data cannot be accessed outside the function.

· Parameters need to be passed to local variables so that they can access the value in the function.

· It is stored on a stack unless mentioned otherwise.

· They can be accessed using statements inside the function where they are declared.

· When the changes are made to the local variable in a function, the changes are not reflected in the other function.

 

· It is declared outside the function.

· If it isn’t initialized, the value of zero is stored in it as default.

· It is created before the global execution of the program.

· It is lost when the program terminates.

· Data sharing is possible since multiple functions can access the global variable.

· They are visible throughout the program, hence passing parameters is not required.

· It can be accessed using any statement within the program.

· It is stored on a specific location inside the program, which is decided by the compiler.

· When changes are made to the global variable in one function, these changes are reflected in the other parts of the program as well.




Recursion :

A function calling itself either directly or indirectly is called the recursion and the function doing such activity is called the recursive function. using recursion some problems like tower of hanoi DFS etc problems can be solved very easily.
Working : Every problem is further divided into the smaller problems based on the condition as the further division is not possible until the required condition not met.
like  
int factorial(int x){
if(x==0)
return 1;
else
return x*factorial(x-1);
}

suppose we have to pass the value 5 int the variable x then  
 5*factorial(5-1)
        then 4*factorial(4-1)
                then 3*factorial(3-1)
                        then 2*factorial(2-1)
                                    then 1*factorial(1-1)
                                                now if condition became true it means return 1 in place of 0
now LIFO multiplication takes place 
1*1*2*3*4*5 and result is return to the main function .

No comments:

Post a Comment