Friday 26 December 2014

Functions

02:19 Posted by Hindustan News , No comments
A function is a module or block of program code which deals with a particular task. Making functions is a way of isolating one block of code from other independent blocks of code. Functions serve two purposes. They allow a programmer to say:"this piece of code does a specific job which stands by itself and should not be mixed up with anything else", and they make a block of code reusable since a function can be reused in many different contexts without repeating parts of the program text. In previous modules, main( ) itself is a pre-defined function.

Functions help us to organize a program in a simple way

Each function has a name or identifier by which is used to refer to it in a program. A function can accept a number of parameters or values which pass information from outside, and consists of a number of statements and declarations, enclosed by curly braces { }, which make up the doing part of the object. The declarations and `type of parameter' statements are formalities which will be described in good time.

Some Rules for writing functions:
The name of a function in C can be anything from a single letter to a long word. The name of a function must begin with an alphabetic letter or the underscore _ character but the other characters in the name can be chosen from the following groups:

a .. z       (any letter from a to z)
A .. Z     (any letter from A to Z)
0 .. 9       (any digit from 0 to 9)
_             (the underscore character)

Uses of C functions:
  • C functions are used to avoid rewriting same logic/code again and again in a program.
  • There is no limit in calling C functions to make use of same functionality wherever required.
  • We can call functions any number of times in a program and from any place in a program.
  • A large C program can easily be tracked when it is divided into functions.
  • The core concept of C functions are, re-usability, dividing a big task into small pieces to achieve the functionality and to improve understandability of very large C programs.

C function declaration, function call and function definition:
There are 3 aspects in each C function. They are,
  • Function declaration or prototype  - This informs compiler about the function name, function parameters and  return value’s data type.
                       Syntax: return_type function_name ( argument list );
  • Function call – This calls the actual function
                        Syntax: function_name ( arguments list );
  • Function definition – This contains all the statements to be executed.
                        Syntax:  return_type function_name ( arguments list )
                                      { Body of function; }
Example:
#include
// function prototype, also called function declaration
float square ( float x );                              
 
// main function, program starts from here
int main( )              
{
 
        float m, n ;
        printf ( "\nEnter some number for finding square \n");
        scanf ( "%f", &m ) ;
        // function call
        n = square ( m ) ;                      
        printf ( "\nSquare of the given number %f is %f",m,n );
 
}
 
float square ( float x )   // function definition
{
        float p ;
        p = x * x ;
        return ( p ) ;
}

Output:
Enter some number for finding square
2
Square of the given number 2.000000 is 4.000000

C - ARRAY

C Array is a collection of homogeneous value i.e. belongings to the same data type. You can store group of data of same data type in an array.
  • Array might be belonging to any of the data types.
  • Array size must be a constant value.
  • Always, Contiguous (adjacent) memory locations are used to store array elements in memory.
  • It is a best practice to initialize an array to zero or null while declaring, if we don’t assign any values to array. 
For example: If the user want to store marks of 100 students. This can be done by creating 100 variable individually but, this process is rather tedious and impracticable. These type of problem can be handled in C programming using arrays.

There are 3 types of C arrays. They are,
  1. One dimensional array
  2. Two dimensional array
  3.  Multidimensional array
One Dimensional Array:

Example:
#include
int main()
{
    int i;
    int arr[5] = {10,20,30,40,50};  
    // declaring and Initializing array in C
    //To initialize all array elements to 0, use int arr[5]={0};
    /* Above array can be initialized as below also
       arr[0] = 10;
       arr[1] = 20;
       arr[2] = 30;
       arr[3] = 40;
       arr[4] = 50;
    */
    for (i=0; i<5; i++)
    {
        //Accessing each variable
        printf("value of arr[%d] is %d \n", i, arr[i]);
    }
}
Output:
value of arr[0] is 10
value of arr[1] is 20
value of arr[2] is 30
value of arr[3] is 40
value of arr[4] is 50

Notes:
1.If number of values in list is less than the number of elements or size of array then only that many element will be initialized.The remaining elements will be set to zero automatically. If array is character type then remaining element will be NULL.
Ex:
        int a[5]={3,4,5};
        value of arr[0] is 3
        value of arr[1] is 4
        value of arr[2] is 5
        value of arr[3] is 0
        value of arr[4] is 0
2.The size may be omitted. In such case, the compiler allocates enough space for all initialized elements.
Ex:
        int counter[]= {1,1,1,1};
        It will works fine.

Two Dimensional Array: 

Example:
#include
int main()
{
    int i,j;
    // declaring and Initializing array
    int arr[2][2] = {10,20,30,40};
    /* Above array can be initialized as below also
       arr[0][0] = 10;   // Initializing array
       arr[0][1] = 20;
       arr[1][0] = 30;
       arr[1][1] = 40;
    */
    for (j=0;j<2;j++)
       {
          // Accessing variables
          printf("value of arr[%d] [%d] : %d\n",i,j,arr[i][j]);
       }
    }
}

Output:
value of arr[0] [0] is 10
value of arr[0] [1] is 20
value of arr[1] [0] is 30
value of arr[1] [1] is 40

Note:
1.Some different types initialization:
int table[2][3] = {0,0,0,1,1,1};
             It simply initialized first row with 0 and second row with 1.
int table[2][3] = {{0,0,0},{1,1,1}};
             In this only we specify curly braces to distinguish the rows.So it gives same result.
int table[2][3] ={
                            {0,0,0},
                             {1,1,1}
                           };
             It also same as above.Commas are required after each braces that closes off a row, except in the case of the last row.
int table[][3] = {{0,0,0},{1,1,1}};
            When the array is completely initialized with all values, explicitly, we need not specify the  size of the first dimension.
int table[2][3] = {{1,1},{2}};
            If values are missing in an initializer, they are automatically set to zero. In above example,it initialize first two element of the first row to 1, the first element of the second row to two, and all other elements to zero.
int table[2][3] ={{0},{0}};
            In above statement, all elements are to be initialized to zero.

Note: We discussed later about Multidimensional array after discussing about Pointer.