C-Programming

Functions

In C programming a large and complex problem can be divided into smaller sub-program which is called as module in C. These modules are called functions .Whenever the size of program becomes large and complex debugging, testing and maintaining the program turns out to be very difficult. Thus a program is divided into functional parts known as   function which works independently. They can be coded independently and can be combined to form the complex program. A C program must consist of a function called main ( ) which indicates the beginning of the program execution. Besides there can be other functions .They can be called from main( ). Whenever the function is called the control of the program is transferred to the first statement in the function and after all the statements in the function are executed, control returns to the calling function.

Function in C programming can be classified into two categories namely Library functions and User defined function. The library functions are already predefined and stored on the system library e.g. printf( ) and scanf( ). The user defined functions are created by the user while writing the program. In the library functions, the name of the functions are fixed i.e, we can not change the function name as our requirement but in the case of user defined functions, we can give the name for the function as our requirement except the keywords and library function’s name. These functions can also become a part of system library. Our study here will be centralized on user defined functions.

 Major advantages of using such functions can be highlighted as follows:

1). Use of functions reduces code redundancy (code duplication). This means that if we have to do same task for more than one time then simply we can call the function which reduces the length of the program.

2). Debugging testing and maintaining the program becomes much easier.

3). A function can be reused. i.e. new programs can be developed with the help of these codes.

4).Use of function increases the modularity of the program.

5). Readability of the program increases .i.e. the program becomes easy to read.

6). This makes the execution work fast.

 

Structure of a function

The general structure of a function is as follows.

function_name (argument list);

argument declaration;

{

local variable declaration;

statements;

return (expression);

}

Function prototype:

 

All the functions must be declared before they used in the program. The prototype of the function tells in advance about the characteristics of the function used in the program. From the function prototype we can know the type of the arguments that takes the function and the return type of the function (i.e. the type data that the function returns). The function prototype is of the form:

return_type function_name (type arg1, type arg2…type arg n);

Here, return_type indicates the data type to the variable returned by the function; Function name indicates the name of the function .type indicates the data type of the argument and arg1, ag2 etc indicates the arguments that are passed  to the function .

Function definition

 It is the actual body of the function. In fact it starts with the function header which is similar to the function prototype but it doesn’t end with a semicolon. It defines the type of the value that the function returns, its parameters and the statements that are executed when the function is called.

Its general form is as follows:

return_type function_name (type arg1,type arg2……………type  arg n)

{

statements;

return (expression);

}    

We can write the code for function definition after or before the main( ) function. If we have written the function definition before the main( ) function then there is no need of function prototype OR function definition. But if we have written after the main( ), then we should declare the function before main( ).

                             Function call:

A function can simply be called by using the name of the function in the statement and by supplying the arguments. The function in which the function call statement is contained is called calling function and the function which is called by the calling function is called the called function.

Formal argument and Actual argument:

Those argument contained by the called function is called actual argument. This means the arguments we supply while calling a function is formal argument.

Those argument contained in the function definition is called the formal argument. This should be carefully noted that the type of the formal argument and the actual argument should be identical in the same order.

All of these three terminologies such as function prototype, function definition and function call can be well understood with the help of following example. Let us consider a program to calculate the area of rectangle using function.

#include<stdio.h>

#include<conio.h>

void main( )

{

float area,lenth,breadth;

    return type                        formal argument

float calcarea(float x,float y);   // This is function prototype

printf(“Enter the length and breadth of the rectangle”);

scanf(“%d%d”,&length,&breadth);

area= calcarea(length,breadth);   

                               actual argument

    /*This is function calling. Here the function calcarea( ) is the called function and main() through we are calling the function is calling function.*/

printf(“The area of rectangle is %d”,area);

getch();

}

float calcarea(float x,float y)    //This is function definition.

{

return (x*y);   /* The function returns the product of length and breadth to the calling function, which is the area of rectangle*/

}                     

Explanation of the program:

Here main() is the calling function and calcarea() is the called function .As when the function is  called from main( ). The program control is transferred to the called function i.e. calcarea( ). Here calcarea() is the function which calculates the  area of the rectangle and returns the value to the main( ). The area thus calculated is assigned to the variable called area in the main( ) . This value is displayed on the screen as output of the program.

 

                   Passing argument to the function  

 

The process of supplying the required data to the function to perform task is called passing arguments in function. In a function arguments can be passed by following two methods:

1) Passing argument by value

2) Passing argument by reference

The process of   passing actual value of the variable to a function is known as passing argument by value. Here a copy of variable is made and then passed to the function as argument in the function.  In passing argument to a function by this method , the changes made to the parameters of the function have no effect on the variables in the calling function .The changes that takes place is only on the copies  so as the  calling function only acts upon the copies the original content of the variable is saved on the calling function.

Where as if the reference of address is passed to the function as argument (by using pointers which represents the address or reference of the data), this method is known as passing argument by reference. Here the address of the argument is passed. So the change that takes place in the called function affects the variables in the calling function because the address of the variable is same for both called and calling function. The function which is called by reference can change the value of the variable used in the call. Thus calling a function by reference provides a mechanism by which a function can change the stored values in the calling function.

Let us consider the following two examples to understand the passing of argument by value and by reference.

/* passing by value*/

#include<stdio.h>

#inlcude<conio.h>

void swap(int, int);  //global function declaration

void main()

{

    int a=10,b=20;

    swap(a,b);       //function calling

    printf(“\n a=%d b=%d”,a,b);

}

void swap(int a,int b)    //function definition

{

    int temp;

    temp=a;

    a=b;

    b=temp;

}

The output of the program will be:   a=10  b=20

(The values of the variables are not exchanged)

/*if the same program is written by the concept of Passing arguments by Reference then the program will be:*/

#include<stdio.h>

#include<conio.h>

void swap(int *, int *);

void main()

{

    int a=10,b=20;

    swap(&a,&b); //passing the argument with their address

printf(“\n a=%d b=%d”,a,b);

}

void swap(int *a, int *b)

{

    int temp;

    temp=*a;

    *a=*b;

    *b=temp;

}

The output of the program will be a=20& b=10 (The values are exchanged).

          In the example of passing argument by value, swap is done only on the copies of the variables a & b, but in the passing by reference, swap is done on the original variables themselves because the address of the variables is passed down to the function.

Return value

          A function may or may not return back any to the calling function. If it does, it is done through return statement.

 The return statement takes the following form

        return (expression);

      OR  return ;

Here return is keyword in the C. It is a full fledged C statement that can appear anywhere within the function body. A function can also have more than one return statement but in an execution of the program only one return statement will be executed not more than one. The return statement terminates the execution of the function and passes control back to the calling environment. The return statement in a function can have following purposes:

  1. On executing the return statement, it immediately transfers the control back to the calling function.
  2. It returns the value present in the parenthesis after it return to the calling function.
  3. There is no restriction on the number of return statement that may be present in a function. Also the return statement need not always be present on the calling portion of the program.
  4. A return statement can return only one value at a time.

 

 

Types of function on the basis of return statement

On the basis of passing of arguments and usage of the return statement generally function can be classified into three different categories:

  1. no argument no return value
  2. argument but no return value
  3. argument and return value

There also may one another type of the function which is no argument but return value. This type of function generally does not exist in the real practice therefore we can neglect this type of the function from our course of study.

                   Type 1: No Argument No Return Value

Here a function is called without any formal arguments from calling portion of the program and there is no return statement in the called function. Thus in this mechanism no arguments are passed to the function and no values are returned by the function.

Syntax:

main()

{

int x,y;

…..

…..

message//function is invoked

return 0;

}

message()

{

//body of the function

}

example:

#include<stdio.h>

#include<conio.h>

void func();

main();

{

printf(“\n this is the example of no argument and no return value.”);

func();

getch();

}

void func()

{

printf(“\n here the calling function has nor sent any argument and this function is nor returning any value to the calling function.”);

}

                   Type 2: Arguments but No Return Value

In this type of function the arguments are passed to the function but no values are returned by the function to the calling portion. There is one way data communication between the calling portion and the function block.

Syntax:

void main()

{

int x,y;

power(x,y)// function declaration

……..

………

}

power(x,y)

int x,y;

{

//body of the function

//no value is transferred back to the caller.

}

Example:

#include<stdio.h>

#include<conio.h>

void func(int);

main();

{

int n=5;

printf(“\n this is the example of argument but no return value.”);

func(n);

getch();

}

void func(int m)

int i,m;

for(i=1;i<=m;i++)

printf(“\n this is the second type of the function.”);

}

                   Type 3: Argument and Return Value

In this mechanism the function is called with passing of some formal arguments and the called function returns some values to the called function.

Syntax:

void main ()

{

int x,y,temp;

char ch;

……

…..

temp=output(x,y,ch);

}

output(a,b,s)

int a,b;

char s;

{

int value;

// body of the function

return (something);

}

Example:

#include<stdio.h>

#include<conio.h>

int sum(int, int);

void main()

{

int a,b,c;

printf(“\nplease enter the value of a and b:\t”);

scanf(“%d%d”,&a,&b);

c=sum(a,b);

printf(“\nthe sum of the given numbers is %d”,c);

getch();

}

int sum(int a, int b)

 {

int addition;

addition=a+b;

return addition;

}

 

Passing arrays to the function

An entire array can also be passed to the function as an argument to the calling portion of the function .To pass a single array to the function; the elements of an array are passed to the function as an argument in the normal fashion. It should be noted that in the array accessing in function there is always passing by reference.

We can pass one dimensional array to the function by simply passing the name of the array to the calling function. In the function definition and function declaration, we have to write the name of the array with empty pair of brackets. The syntax for the passing one dimensional array to the function takes the form:

//function declaration

return_type function_name(data_type array_name[],……);

 main()

{

…………

…………

//function calling

function_name(array_name);

……

……

}

//function definition

  return_type function_name(data_type array_name[],……)

{

………

………

}

Let us consider the following example:

Program to illustrate to pass the single dimensional array to the function;

#include<stdio.h>

#include<conio.h>

void display (int marks[]); //function declaration

void main()

{

int  marks[]={20,18,35,19,27};

display (marks); //function calling

getch();

}

void display (int marks[])//function definition

{

int i;

for (i=0;i<5;i++)

printf(“%d”,marks[i]);

}

Now one question can be raised here. If we want to pass the 2 dimensional array to the function then how can we do this? For this we have to send the second dimension of the array i.e. numbers of columns. This takes the syntax as:

//function declaration

return_type function_name(data_type arrayname[][no. of columns],……);

 main()

{

…………

…………

//function calling

function_name(array_name);

……

……

}

//function definition

  return_type function_name(data_type array_name[][no. of columns],……)

{

………

………

}

Let us consider the following example:

Program to illustrate to pass the single dimensional array to the function;

#include<stdio.h>

#include<conio.h>

void display (int marks[][5]); //function declaration

void main()

{

int  marks[][5]={20,18,35,19,27,23,65,26,89,12};

display (marks); //function calling

getch();

}

void display (int marks[][5])//function definition

{

int i,j;

for (i=0;i<2;i++)

for(j=0;j<5;j++)

printf(“%d\t”,marks[i][j]);

}

                   Recursive Function :

The term recursion refers to a process or mechanism by which a function calls itself repeatedly until a condition is satisfied. Thus a recursive function can be defined as that type of function which calls itself repeatedly until a condition is satisfied. Here the statement in the body of the function calls the function repeatedly until a condition is satisfied. There are two possible ways of recursion, one is direct recursion i.e. the function calls itself repeatedly, and the other is indirect i.e. the function calls another function and it calls the first one repeatedly until a condition is satisfied.

Thus for a function to be recursive two conditions must be satisfied.

1) The function should be written in recursive format

2) The stopping condition must be defined

          Example of a recursive function:

Program to calculate the factorial value of a number using a recursive function.

#include<stdio.h>

long int factorial(int n);

void main()

{

long int factorial(int );

long int fact;

int num;

printf(“Enter the number whose factorial is to be calculated:”);

scanf(“%d”,&num);

fact=factorial(num);

printf(“The factorial of the given number is %ld”,fact);

}

long int factorial(int n)

{

long int fac;

if (n==0||n==1)

return(1);

else

{

fac*=factorial(n-1);

return (fac);

}

}

 

 

                   Some examples of program using function:

 

*Program to reverse any digit numbers using function.

#include<stdio.h>

#include<conio.h>

void main()

{

int n,result;

int reverse(int n);

printf(“\n Enter the number”);

scanf(“%d”,&n);

result=reverse(n);

printf(“\n Reverse of no: %d”, result);

getch();

}

int reverse(int n)

{

int digit, y=0;

do

{

digit=n%10;

y=y*10+digit;

n=n/10;

}while(n!=0);

return(y);

}

*Program to accept the names of a given number of students and sort in alphabetical order.

#include<stdio.h>

#include<conio.h>

#include<string.h>

void main()

{

clrscr();  

char name[25][25];

char tname[25][25];

char temp[25];

int  i, j;

int n;

printf(“What is  the total  number of student in class ?”);

scanf(“%d”,&n);

printf(“Enter the data \n”);

for(i=0;i<n;i++)    

{

printf(“Enter the student’s name “);

scanf(“%s”,&name[i]);

}

for(i=0;i<n;i++)

{

for(j=i+1;j<n;j++)

{

if(strcmp(name[i],name[j])>0)

{

strcpy(temp,name[i]);

strcpy(name[i],name[j]);

strcpy(name[j],temp);

}

}

}

printf(“ The name list in the ascending order is :\n”);

for(i=0;i<n;i++)

printf(“\n%s”,name[i]);

getch();

}

*Program to input different value in array and arrange in descending order using function with pointer.

#include<stdio.h>

#include<conio.h>

void sort(int *,int);

void main()

{

int num[50];

int upto;

clrscr();

printf(“Enter the number of data you want to sort.\t”};

scanf(“%d”,&upto);

for(int i=0;i<upto;i++)

{

printf(“Please enter the data one by one\n”);

scanf(“%d”,&num[i]);

}

printf(“ The data before sorting \n);

for(int j=0;j<upto;j++)

{

printf(“\n%dth number is=%d\n”,j+1,num[j]);

}

sort(num,upto);

printf(“The data after being sorted in descending order is /n”);

for( j=0;j<upto;j++)

{

printf(“\n%dth number is =%d \n”,j+1,num[j]);

}

getch();

}

void sort(int *num,int upto)

{

int i, j;

int temp;

for(i=0;i<upto;i++)

{

    for(j=i+1;j<upto;j++)

     {

        if(num[i]<num[j])

           {

         temp=num[i];

         num[i]=num[j];

         num[j]=temp;

            }

      }

C Programming Questions Solutions with Arrays (Prev Lesson)
(Next Lesson) Important Questions from Functions
Back to C-Programming

No Comments

Post a Reply

Teacher
Bhim Gautam
Role : Lecturer
Read More
error: Content is protected !!