Professional Documents
Culture Documents
EST102: Programming in C: Functions
EST102: Programming in C: Functions
EST102: Programming in C: Functions
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):
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.
126
9.2. ELEMENTS OF USER DEFINED FUNCTION 127
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.
→ function name
→ list of argument types – data types of the input values to the function
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
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.
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);
}
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
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);
}
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
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
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.
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");
}
}
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.
#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));
}
#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");
}
}
#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
#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);
}
#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));
}
#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));
}
#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));
}
#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));
}