EST102: Programming in C: Functions

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 17

EST102 : Programming in C

Chapter 9
Functions

Narasimhan T.

9.1 Introduction
Most of the programs that solve real-world problems are much bigger and complex than
the programs presented in the earlier chapters. C language allows a large program to be
broken down into a number of smaller modules or components. Such components are called
functions. A function is a named, self-contained block of statements that carries out some
specific, well-defined task. A program can be seen as a collection of functions, each of which
has some unique, identifiable purpose. This way of dividing a program into code fragments
(functions) is called modular programming. There are several advantages to this modular
approach to program development(using functions):

1. Functions eliminate redundancy: Many programs require that a particular group


of instructions be accessed repeatedly, from several different places within the pro-
gram. The repeated instructions can be placed within a single function, which can
then be accessed whenever it is needed. The use of a function avoids the need for
redundant (repeated) programming of the same instructions.

2. Functions enables the re-use of code: A function may be used by many other
programs. Thus a programmer can build on what others have already done instead
of starting from scratch. Thus functions facilitate re-use of code.

3. Functions hide complexity: Functions can simplify a program by hiding a complex


computation from other parts of the program that don’t need to know about them.
A function will carry out its intended action whenever it is accessed. If you want to
use the function in your program, you don’t have to know how it works inside! This
mechanism is called abstraction. Thus a function hides unnecessary details from the
users.

126
9.2. ELEMENTS OF USER DEFINED FUNCTION 127

4. Functions support division of labour: Functions can enforce division of labour.


Ideally, each function performs a single coherent task. A complex task could be
divided into simpler sub-tasks. Each of these sub-tasks can be assigned to separate
functions.

5. Functions enhance the readability of programs: Dividing a long program into


functions allows you to separate different parts of the program. This makes the
program easier to design and understand.

6. Functions enable improved debugging and testing: When a program is divided


into functions, it is possible to isolate a function and investigate it separately which
helps in easily locating and pin-pointing errors. Thus functions aid in easy debugging.

There are two categories of functions:

1. Library functions – These are also known as built-in functions. They come as part of
the compiler and are used to perform tasks such as mathematical computations, I/O
processing, string handling etc. These functions are defined in various header files.
When you include the header file, these functions are available for use. printf(),
sqrt() are some examples.

2. User defined functions – C allows programmers to define their own functions. Such
functions are called user-defined functions. There is no limit to the number of user
functions that you can create.

9.2 Elements of user defined function


There are three aspects of working with user defined functions:

1. Function declaration – also known as function prototype or function signature.

2. Function definition – implementation of the function.

3. Function use – known as function call or function invocation.

9.2.1 Function declaration


When users develop their own functions, the compilers should be informed about the ex-
istence of these new functions. This is done through function declaration. It contains the
following elements.

→ function name

→ return type – data type of the result produced by the function

→ list of argument types – data types of the input values to the function

Example 9.1. Assume you have the following statement in a program


128 CHAPTER 9. FUNCTIONS

int ABC(char,float);
This declares a function:
⋆ with name ABC
⋆ that takes two input values of type char and float
⋆ that produces a result of type int

9.2.2 Function definition


Each function has its own purpose in the program. The logic required to implement the
task performed by the function is specified in the function definition. It has two parts:
→ function header – specifies the name of the function along with the input values to it.
It also indicates the return type [See function declaration]
→ function body – this contains the statements that implement the task to be performed.
The statements are to be enclosed in a pair of braces.
Example 9.2. The following defines a function ABC.
int ABC(char c, float f)
{
......
......Statements that make the function body
......
}

9.2.3 Function call


Just defining a function is not sufficient. In order to use it, we need to access it. This is
known as calling the function. The statements inside the function do not get executed
until the function is called. A function can be called by specifying its name, followed by
the list of input values in parentheses and separated by commas. If the function call does
not require any input values, an empty pair of parentheses must follow the name of the
function.
Example 9.3. The statement
ABC(m,n);
calls a function ABC and supplies two input values m and n to it. ■
Assume a function ABC is called from another function XYZ, then
→ ABC is known as the called function or callee.
→ XYZ is known as the calling function or caller.
9.3. HOW A FUNCTION WORKS? 129

R If a function is defined before it is called, there is no need to declare the function.

9.3 How a function works?


1. When a function call is encountered, the control passes to the called function.

2. The called function will process the information that it is supplied with, and produces
a result.

3. The data supplied (input values) to the function are called arguments or parameters
and the result produced is known as return value. In other words, arguments are
those values that are passed (supplied) from the caller to the callee and return value
is the result sent back to the caller from callee.

4. The parameters in the function definition are called formal parameters and those
in the function call are called actual parameters. The values that the caller needs
to pass to callee are packed as actual arguments. These values are received by the
called function as formal arguments.

5. The called function operates on the formal arguments and produces the result.

6. When the called function finishes its execution, control is passed back to the statement
immediately following the function call in the calling function. When it gets to the
end of the program, it terminates.

Which category should I choose?


You know there are four categories of user defined functions which are all equivalent.
Now, given a problem, which category to choose? The choice of the category depends
entirely on the programmer. As a rule of thumb, if you input the values in the calling
function and need to process them in the called function, then your function should
have arguments. Thus choose between categories 3 and 4. Similarly if you want the
result of this processing to be available in the calling function, then your function
should return that value. In this case, you should choose between categories 2 and 4.

9.4 Classification of functions


The arguments and the return value are both optional. This results in four categories of
functions. Precisely, all the categories are equivalent in the sense that the problem solved
with one category is solvable using any other category. (Read the box - Which category
should I choose?) To elucidate the differences among the different categories, a simple
function sum() to add two numbers is defined in the following examples.
130 CHAPTER 9. FUNCTIONS

9.4.1 Function with no arguments and no return value

Example 9.4. The main() function calls an user defined function sum(). In sum(), two
values are input and their sum is computed and displayed inside the function itself. See the
program below:
#include<stdio.h>
void sum();
main()
{
sum();
}
void sum()
{
int a,b;
printf("Enter two values to add\n");
scanf("%d %d",&a,&b);
printf("The sum is %d\n",a+b);
}

9.4.2 Function with no arguments but returns a value

Example 9.5. Here, main() function calls sum() which inputs the values and finds their
sum. The result is then returned to main() where it is printed. This is shown in the code
below:
#include<stdio.h>
int sum();
main()
{
int s;
s=sum();
printf("The sum is %d\n",s);
}
int sum()
{
int a,b;
printf("Enter two values to add\n");
scanf("%d %d",&a,&b);
return (a+b);
}
9.4. CLASSIFICATION OF FUNCTIONS 131

9.4.3 Function with arguments but with no return value

Example 9.6. The main() function accepts input from the user and calls sum() with the
input values as arguments. sum() receives the arguments, adds them and prints the result
in the function itself. See the program below.
#include<stdio.h>
void sum(int,int);
main()
{
int a,b;
printf("Enter two values to add\n");
scanf("%d %d",&a,&b);
sum(a,b);
}
void sum(int x,int y)
{
printf("The sum is %d\n",x+y);
}

9.4.4 Function with arguments and returns a value

Example 9.7. Here, main() accepts input from user and passes them as arguments while
calling sum(). The called function adds the received arguments and returns their sum. This
return value is accepted by main() which is then printed. The code is shown below.
#include<stdio.h>
int sum(int,int);
main()
{
int a,b,s;
printf("Enter two values to add\n");
scanf("%d %d",&a,&b);
s=sum(a,b);
printf("The sum is %d\n",s);
}
int sum(int x,int y)
{
return (x+y);
}
132 CHAPTER 9. FUNCTIONS

9.5 Parameter passing schemes


There are two ways to pass arguments to a function in C language: call by value and call
by reference. We discuss call by value now and defer the discussion of call by reference
until the concept of pointers is introduced.

9.5.1 Call by value


This method copies the value of an actual parameter into the formal parameter of the called
function. In this case, changes made to the formal parameters are not reflected in the calling
function. The changes are made only to the local copy of the formal parameters.

Example 9.8. This program illustrates call by value method of parameter passing.
#include<stdio.h>
void updateVar(int);
main()
{
int var=10;
printf("In calling function: Old value was %d\n",var);
updateVar(var);
printf("In calling function: New value is %d\n",var);
}
void updateVar(int var)
{
printf("In called function: Received value is %d\n",var);
var+=5;
printf("In called function: Updated value is %d\n",var);
}

Here the value of the variable var is copied to the formal parameter. Thus any changes
made on this copy will be available only in the called function. The program outputs:
In calling function: Old value was 10
In called function: Received value is 10
In called function: Updated value is 15
In calling function: New value is 10

9.6 Passing arrays to a function


An entire array can be passed to a function as an argument. The manner in which the
array is passed differs from that of an ordinary variable.
9.6. PASSING ARRAYS TO A FUNCTION 133

9.6.1 Passing 1D array to a function


To pass an 1D array to a function, you need to specify the array name (without any
subscripts) and the size of the array in the function call. See the example below:

Example 9.9. This program inputs and prints the elements of an 1D array.
#include<stdio.h>
void printArray(int [],int);
main()
{
int a[10],n,i;
printf("How many elements you want?\n");
scanf("%d",&n);
printf("Enter %d elements\n",n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printArray(a,n);
}
void printArray(int a[],int n)
{
int i;
printf("The array elements are\n");
for(i=0;i<n;i++)
printf("%d ",a[i]);
}
See how the function is declared. The data types of the array and its size are to be specified.
An empty pair of square brackets must follow the data type of each array argument, thus
indicating that the argument is an array. Following the array argument type, data type for
the array size is specified.

9.6.2 Passing 2D arrays to a function


To pass 2D array to a function, you specify the array name (just as you do in the case of
passing 1D array) followed by number of rows and columns. In the function declaration,
the array data type is followed by two pairs of brackets, the first for the number of rows and
the other for number of columns. The first pair is left empty as the number of rows need
not be specified explicitly. The second pair of brackets provides an explicit size specification
for columns. Following the array argument type, data types for the array dimension sizes
(sizes of rows and columns) are specified. See the example below:

Example 9.10. This program inputs and displays the elements of a matrix.
#include<stdio.h>
void printMatrix(int [][5],int,int);
main()
134 CHAPTER 9. FUNCTIONS

{
int a[5][5],m,n,i,j;
printf("How many rows and columns you want?\n");
scanf("%d %d",&m,&n);
printf("Enter the elements\n");
for(i=0;i<m;i++)
for(j=0;j<n;j++)
scanf("%d",&a[i][j]);
printMatrix(a,m,n);
}
void printMatrix(int a[][5],int m,int n)
{
int i,j;
printf("The array elements are\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
printf("%d ",a[i][j]);
printf("\n");
}
}

9.6.3 Passing string to a function


Recall that strings are one dimensional char arrays. So strings can be passed to a function
in the same way as an 1D array.

Example 9.11. This example inputs a string and toggles (changes) the case of its individual
characters, i.e., lower case characters are changed to upper case and vice versa. The ASCII
range of upper case letters is from 65 to 90 and that of lower case characters is from 97 to
122. Thus to convert lower case to upper case, you need to subtract 32 from the ASCII
value and to convert upper case to lower case, you need to add 32. This results in the code
below:
#include<stdio.h>
#include<string.h>
void toggleCase(char str[],int n)
{
int i;
printf("The original string is %s\n",str);
for(i=0;i<n;i++)
{
if(str[i]>='A'&&str[i]<='Z')
str[i]+=32;
else if(str[i]>='a'&&str[i]<='z')
9.7. RECURSION 135

str[i]-=32;
}
printf("The string after toggling case is: %s",str);
}
main()
{
char str[20];
printf("Please enter a string\n");
gets(str);
toggleCase(str,strlen(str));
}

9.7 Recursion
You can call any function inside any other function. Thus, a function can call itself too. In
such a case, the function is said to be recursive. Recursion is a process by which a function
calls itself repeatedly, until some specified condition has been satisfied. The process is used
for repetitive computations in which each action is stated in terms of a previous result.
Many iterative (i.e., repetitive) problems can be written in this form.
Example 9.12. A classic application of recursion is in calculating the factorial of a number.
Recall that factorial of a number n is the product of all the integers between 1 and n. For
example, 4! is 4 × 3 × 2 × 1. But 3 × 2 × 1 is 3!. Thus, 4! = 4 × 3!. Again, 3! = 3 × 2!
and this recursive process continues. In general, n! = n × (n − 1)!. This is the recursive
definition for factorial of a number. If you use this definition to find n!, you finally end
up with calculating 0! which is defined to be 1. Thus the recursive definition of a function
fact(n) to compute n! can be written as
{
1 if n == 0
fact(n) =
n × fact(n − 1) otherwise

This idea is implemented in the program below. Here, the function declaration is omitted
since it is defined before the call.
#include<stdio.h>
int fact(int n)
{
if(n == 0)
return 1;
else
return n * fact (n-1);
}
main()
{
int n;
136 CHAPTER 9. FUNCTIONS

printf("Enter a number\n");
scanf("%d",&n);
printf("The factorial of %d is %d\n",n,fact(n));
}
Suppose user inputs a value 5. Thus main() calls fact(5). Now what happens is
fact(5) executes 5 * fact(4)
fact(4) executes 4 * fact(3)
fact(3) executes 3 * fact(2)
fact(2) executes 2 * fact(1)
fact(1) executes 1 * fact(0)
fact(0) returns 1 to its calling function fact(1)
fact(1) returns 1 * 1 = 1 to its calling function fact(2)
fact(2) returns 2 * 1 = 2 to its calling function fact(3)
fact(3) returns 3 * 2 = 6 to its calling function fact(4)
fact(4) returns 4 * 6 = 24 to its calling function fact(5)
fact(5) returns 5 * 24 = 120 to its calling function main()

While writing recursive functions, you must have a conditional statement, such as an
if, somewhere to force the function to return without the recursive call being executed. If
you don’t, the function will never return once you call it. For example, the code
main()
{
printf("Will this stop?");
main();
}
will never stop. This is known as infinite recursion, and is generally not considered a
good practice.
The condition used to stop the recursion is called base case or anchor condition and it
does not make a recursive call. For the code in Example 9.12, n == 0 is the base case.

9.8 Programming examples


Program 9.67. To find the absolute value of an integer.

#include<stdio.h>
int abs(int x)
{
if(x<0)
return -x;
9.8. PROGRAMMING EXAMPLES 137

else
return x;
}
main()
{
int num;
printf("Enter a number\n");
scanf("%d",&num);
printf("The absolute value of %d is %d",num,abs(num));
}

Program 9.68. To implement a menu driven calculator

#include<stdio.h>
int add(int x,int y)
{
return x+y;
}
int sub(int x,int y)
{
return x-y;
}
int mul(int x,int y)
{
return x*y;
}
float div(int x,int y)
{
return (float)x/y;
}
int mod(int x,int y)
{
return x%y;
}
main()
{
int a,b,ch;
printf("Choose the operation\n");
printf("1 - Addition\n 2 - Subtraction\n 3 - Multiplication\n 4 -
Division\n 5 - Remainder\n");
scanf("%d",&ch);
printf("Enter the two operands\n");
scanf("%d %d",&a,&b);
switch(ch)
{
138 CHAPTER 9. FUNCTIONS

case 1:
printf("%d + %d = %d",a,b,add(a,b));
break;
case 2:
printf("%d - %d = %d",a,b,sub(a,b));
break;
case 3:
printf("%d * %d = %d",a,b,mul(a,b));
break;
case 4:
printf("%d / %d = %f",a,b,div(a,b));
break;
case 5:
printf("%d mod %d = %d",a,b,mod(a,b));
break;
default:
printf("Enter the correct choice\n");
}
}

Program 9.69. To print the perfect numbers in a range.

#include<stdio.h>
int isPerfect(int x)
{
int i,sum=0;
for(i=1;i<=x/2;i++)
if(x%i==0)
sum+=i;
if(sum==x)
return 1;
else
return 0;
}
void printPerfect(int lb,int ub)
{
int i;
printf("The perfect numbers lying between %d and %d is\n",lb,ub);
for(i=lb;i<=ub;i++)
if(isPerfect(i)==1)
printf("%d ",i);
}
main()
{
int lb,ub;
9.8. PROGRAMMING EXAMPLES 139

printf("Enter the lower and upper bounds of the range\n");


scanf("%d %d",&lb,&ub);
printPerfect(lb,ub);
}
Program 9.70. To compute the value of ex as the sum of the following series upto n
terms:
x2 x3 x4
ex = 1 + x + + + + ······
2! 3! 4!

#include<stdio.h>
#include<math.h>
int fact(int n)
{
if(n == 0)
return 1;
else
return n * fact(n-1);
}
main()
{
int n,i,x;
float sum=0.0;
printf("How many terms in the series you want to add?\n");
scanf("%d",&n);
printf("Value of x please..\n");
scanf("%d",&x);
for(i=0;i<n;i++)
sum+=pow(x,i)/fact(i);
printf("The sum of %d terms in the series is %f\n",n,sum);
}
Program 9.71. To compute the value of e−x as the sum of the following series upto n
terms:
x2 x3 x4
e−x = 1 − x + − + + ······
2! 3! 4!

#include<stdio.h>
#include<math.h>
int fact(int n)
{
if(n == 0)
return 1;
else
return n * fact(n-1);
}
140 CHAPTER 9. FUNCTIONS

main()
{
int n,i,x;
float sum=0.0;
printf("How many terms in the series you want to add?\n");
scanf("%d",&n);
printf("Value of x please..\n");
scanf("%d",&x);
for(i=0;i<n;i++)
sum+=pow(-x,i)/fact(i);
printf("The sum of %d terms in the series is %f\n",n,sum);
}

Program 9.72. To print the nth Fibonacci number.

#include<stdio.h>
int fib(int x)
{
if(x==0)
return 0;
else if(x==1)
return 1;
else
return fib(x-1) + fib(x-2);
}
main()
{
int n;
printf("Enter the value of n\n");
scanf("%d",&n);
printf("The required Fibonacci number is %d",fib(n));
}

Program 9.73. To print the first n terms of Fibonacci series.

#include<stdio.h>
int fib(int x)
{
if(x==0)
return 0;
else if(x==1)
return 1;
else
return fib(x-1) + fib(x-2);
}
main()
9.8. PROGRAMMING EXAMPLES 141

{
int i,n;
printf("Enter the value of n\n");
scanf("%d",&n);
for(i=0;i<n;i++)
printf("%d ",fib(i));
}

Program 9.74. To recursively find the sum of a range of numbers.

#include<stdio.h>
int sumRange(int low,int high)
{
if(low>high)
return 0;
else
return low + sumRange(low+1,high);
}
main()
{
int lb,ub;
printf("Enter the limits of the range\n");
scanf("%d %d",&lb,&ub);
printf("Sum of numbers lying between %d and %d is
%d\n",lb,ub,sumRange(lb,ub));
}

Program 9.75. To print the nth prime number.

#include<stdio.h>
int isPrime(int num)
{
int i,flag=1;
for(i=2;i<=num/2;i++)
{
if(num%i==0)
{
flag=0;
break;
}
}
if(flag==0)
return 0;
else
return 1;
}
142 CHAPTER 9. FUNCTIONS

main()
{
int n,i,count=0,num=2;
printf("Enter the value of n\n");
scanf("%d",&n);
while(count<n)
{
if(isPrime(num)==1)
{
count++;
if(count==n)
{
printf("The required prime number is %d",num);
break;
}
}
num++;
}
}
Program 9.76. To recursively find the sum of digits of a number.

#include<stdio.h>
int sumDigits(int n)
{
if(n==0)
return 0;
else
return n%10 + sumDigits(n/10);
}
main()
{
int n;
printf("Enter a number\n");
scanf("%d",&n);
printf("Sum of digits of %d is %d\n",n,sumDigits(n));
}

You might also like