Modular Programming In C: User-Defined Functions,return types,Call By Value/Reference,Libraries,Variable Length Arguments With Examples

Understanding Module And Function In C

C is "Modular Programming Language". A module is an interface which is a collection of data and sub-programs. 

For example ".h" header file that contains data and sub-programs. We import header in our application and use it's sub-programs. We do not worried about how header file's sub-programs have been implemented. Header file is also known as library file. 

Module hides it's implementation and only allow other modules to use it. Sub-programs in module are known as functions. First we will learn how to create user-defined functions In "C".

Creating User-Defined Function -

Function or Method is a block to perform any task. The benefits of function are less and clean coding which is essential part of any program.

C provides many pre-defined functions, every function has it's own meaning and use. Pre-defined functions are defined in header files (.h).

Same as pre-defined function we can also create our own sub-programs once and
use them anywhere.


Syntax : -


//Function Declaration

Function_prototype Function_name ( arguments )


//Function Definition

Function_prototype Function_name ( arguments )


Task implementation


return statement


Function_Prototype : - 

As we know that function is sub-program and it can be call from anywhere in the application. Application may have dependency
 on function's output. 

The type of result or output of the function that may required by the application is called "Function Prototype". Function Prototype is the data-type of result returning to other module.


Function_Name : -

It is the name of function and it follows same naming convention rules as variables. Please click on the link to see naming convention rules.
Naming Convention Rules

It is recommended as per coding standards that function name should start with lowercase.
  
Function_Argument : -

Function arguments are the variables that takes values from other programs for example: we call pre-defined printf function to print something. 

We can also send "N" numbers of arguments as well, will discuss about it later in this chapter.

#Program 1

Write a program to print a table of any number using user-defined function.

# include <stdio.h>


void printTable ( int num ); //Function Declaration


void main ( ) {


int num;


printf (" Please enter any number");

scanf("%d", &num);


printTable (num); // Function call, not returning any value


}


//Function Definition

void printTable ( int num )  {


for (int i = num ; i<=num*10 ; i=i+num ) {


printf ("%d\n",i);

// no return keyword
}


}

Here we are writing a function to get table of any number.

First declare the function body. function would be of void type because function is not returning any result. Function printing the table.

Function will have one argument to accept number from user.

Implement the table logic in Function definition.

Now its time to call function, here main() is calling, it will pass number value to function. 


#include <stdio.h>


int getAddition (int a, int b);


void main() {


int num1, num2, sum;


printf("Enter 1st number \n");

scanf("%d",&num1);


printf("Enter 2nd number \n");

scanf("%d",&num2);


sum = getAddition (num1,num2);


printf(" Sum of number - %d\n",sum);

}


int getAddition (int a, int b){


return a+b;

}

Here In the above example function returning int value (addition of two numbers), so the function prototype would be int and main() getting this result in sum variable.

Call By Value And Call By Reference In Function -

Assume that we have a function to get the square of any number. We will pass a number to the function and function will return square of the number. 

Function does operation on number and then returns the result, but actual number will remain same because we send copy of the number not actual variable. This is called "Call by Value" and when we send actual variable i.e. the memory address of the variable to function then actual variable will get changed with new value. This is call "Call By Reference".

Default way of passing values to function is call by value and call by reference is achieved by pointer. For more understanding on pointer click on the link

Call by Value Example :

#include <stdio.h>


int getSquare (int number);


void main() {


int num, square;


printf("Enter any number -\n");


scanf("%d",&num);


square = getSquare(num);


printf("The actual number is - %d\n\n",num);


printf("The square of the number is - %d\n",square);


}


int getSquare (int number){


  number  = number * number;

  return number;

}


Call By Reference Example :


#include <stdio.h>


int getSquare (int *ptr);



void main() {


int num, square;


printf("Enter any number -\n");


scanf("%d",&num);


square = getSquare(&num);


printf("The actual number is - %d\n\n",num);


printf("The square of the number is - %d\n",square);


}


int getSquare (int *ptr){


  *ptr =  *ptr * *ptr;
  

  return *ptr;

}



Module Handling / User-Defined Header File 

As you have learnt how to create functions and use, In the above example function scope is local (function written in same .c file) so that any other module can not use this function. If we create a specific module or header file or library then function scope would be global.

1. Create a file and save this file with .h extension

2. Write function's definition in the file. No need to give function's declaration. 

3. Import header file in .c file.

4. Call the methods.



area.h    //File name


int getRectangleArea (int length, int width ) {


return length *width ;

}


int getSquareArea (int side ) {


return side*side ;

}


int getCircleArea (float radius ) {


return 3.14 * radius * radius ;

}


MainApp.c   //FileName 


# include <stdio.h>

# include <area.h>


void main ( ) {


int length, width, side;

float radius;


printf ("Please enter length and width ");

scanf ("%d%d", &length ,&width );

printf ("\nArea of rectangle is -%d",getRectangleArea(length, width));


printf ("Please enter side ");

scanf ("%d", &side );

printf ("\n Area of square is - %d" , getSquareArea (side) );


printf ("Please enter radius ");

scanf ("%f", &radius );

printf ("\n Area of circle is - %f" , getCircleArea (radius) );


}



Note Here I am calling methods from printf(), we can also get result in variable and can print variable's value.


Variable Length Of Arguments In Function -

This is another important topic in this chapter, Usually we pass specified number of arguments to function but sometimes it may be a case that we do not know how many arguments we should pass it may decide at run-time. This topic gives solution for such problems.

It is known as "Variable Length Arguments", It is represented by ... (3 dots) in function's argument.

It is mandatory that all arguments should be of same data-type.


There are some Macros in C va_list , va_start , va_arg, va_end are used to handle variable length arguments, all are defined in "stdarg.h" header file.


Note: Macro is the block of coding like function. Macro processed before actual compilation (ctrl+F9) by the pre-processor directives.   

#Program 2

Write a program to send "N" numbers of marks and find the total.

# include <stdio.h>



//Funtion Declaration

int getResult (int count , ... );



void main ( ) {


int totaMarks = getResult (50,60,80,20,70);


printf( "Your total marks - %d ", totaMarks );


}


//Funtion Definition

int getResult (int count , ... ) {


int sum = 0;

va_list marksList;



for ( int i=1; i <=count; i++ ) {


sum = sum + va_args (marksList, int);


}


va_end (marksList);

return sum;


}


1. The main() calling getResult function for "N" numbers of marks.

2. In the function implementation - 

  va_list  - Holds information about the arguments.

  va_start - Initialize the list variable with arguments to be used.

  va_args - Fetches values from argument list

  va_end - It ends the process on list variable which was initialized by macro. 

No comments

Powered by Blogger.