Unit 3
Unit 3
INTRODUCTION TO
FUNCTIONS
Structured programming is a programming technique in which a larger
program is divided into smaller subprograms. These subprograms are easy
3.1
to understand, easy to implement. The structured programming enables code
reusability. Code reusability is a method of writing code once and using it
many times. In C, the structured programming can be designed using
functions concept. Using functions concept, we can divide larger program
into smaller subprograms and these subprograms are implemented
individually.
Main
Program
Module 4 Module 5
3.1.1 Functions
✤ A function is a block of statements that together perform a specific
task.
✤ Every C program has at least one function, which is main().
✤ A function can also be referred as a method or a sub-routine or a
procedure, etc.
Uses of C Functions
✤ Using functions, larger program can be divided into smaller modules.
✤ Modular programming is implemented using functions.
✤ Main advantages of C functions are, re-usability, dividing a big task into
small pieces to achieve the functionality and to improve
understandability.
✤ It is easy to track when the program is divided into functions.
✤ Once a function is created it can be used many times (code re-
usability).
FUNCTIONS AND 3.3
POINTERS
Syntax
Every function in C has the following.
✤ Function Declaration (Function Prototype)
✤ Function Definition
✤ Function Call
Syntax
returnTypefunctionName(parameters)
{
//Function body
}
✤ Function body is the collection of statements.
Example:
int sum (int x, int y)
{
// Function body has 2 statements
int s = x+y;
return s;
}
#include
<stdio.h> void
functionName()
{
..................
..................
} Function
int main() is
{ called
..................
When the Function is ..................
completed, it returns functionName();
back ..................
..................
Fig 3.2 Working of a C - function
Execution:
Output:
Hello World
3.6 PROGRAMMING IN C
Execution:
Output:
I am Biology Student
I am maths Student
I am commerce Student
FUNCTIONS AND 3.7
POINTERS
In the concept of functions, the function call is known as "Calling
Function" and the function definition is known as "Called Function". When
we make a function call, the execution control jumps from calling function to
called function. After executing the called function, the execution control
comes back to calling function from called function. The data values
transferred from calling function to called function are called as Parameters
and the data value transferred from called function to calling function is
called Return value.
Fig 3.3
4 3 = 80
5 5
3.8 PROGRAMMING IN C
#include <stdio.h>
intaddNumbers(int a, int b); //function
declaration void main()
{
intsum;
sum = addNumbers(10,20);//function
call printf("sum of two numbers =
%d",sum);
}
intaddNumbers(inta,int b) //function definition
{
/* Start of function definition.
*/ int add;
add=a+b;
return add;// //return statement of
function
/* End of function definition. */
}
Execution:
Output:
sum of two numbers = 30
Control Passing
void
function1() void function2()
No Argument Passing
{ {
....................... ..........................
No Return Value
... ..........................
function2(); }
Control Passing
.......................
...
}
Calling Function Called Function
Control Passing
void function1()
{ void function2()
No Argument
.......................... {
result=function2( return(z);
Passing ..........................
);
.......................... }
Returning Value
}
Control Passing
Calling Function Called Function
Control Passing
void function1()
{ void function2(int x, int y)
Argument Passing
......................... {
. ..........................
No Return Value
function2(10,20 ..........................
); }
Control Passing
.........................
.
}
Calling
Called Function
Function
Control Passing
void function1() void function2(int x, int y)
{ {
Argument
......................... ..........................
.
Passing return(z);
function2(10,20 ..........................
);
Returning Value }
.........................
.
Control Passing
}
Calling
Called Function
Function
Fig 3.7 With arguments and with return values
FUNCTIONS AND 3.13
POINTERS
Execution:
Input:
Enter any two integer numbers : 20 30
Output:
Sum = 50
3.14 PROGRAMMING IN C
Function
declared and
defined with No parameter list
parameter list
No value passed
values for parameter during function call
passed during function
call
Ex:
int show();
Ex:
int sum(int x, int y);
//declaration show();
//call
//declaration sum(10, 20); //call
Fig 3.8
//Method definition
int add(int x, int y)
{
return Formal Parameters
or Arguments
(x+y); x, y
}
Original
Value
No If Ye
chang s
e
call by call by
value reference
Fig 3.10 Call by Value Vs Call by Reference
1. Call by Value
✤ In call by value parameter passing method, the copy of actual
parameter values are copied to formal parameters.
✤ The changes made on the formal parameters have no effect on the
actual parameters.
3.16 PROGRAMMING IN C
That means, after the execution control comes back to the calling
function, the actual parameter values remains same.
45 35
#include
<stdio.h> void
main()
{
int num1, num2 ;
void swap(int,int) ; // function
declaration num1 = 10 ;
num2 = 20 ;
printf("\nBefore swap: num1 = %d, num2 = %d", num1,
num2) ; swap(num1, num2) ; // calling function
printf("\nAfter swap: num1 = %d\nnum2 = %d", num1,
num2);
}
void swap(int a, int b) // called function
{
int temp ;
temp = a ;
a = b ;
b = temp ;
}
Execution:
Output:
Before swap: num1 = 10, num2 = 20
After swap: num1 = 10, num2 = 20
FUNCTIONS AND 3.17
POINTERS
Here, num1 and num2 are called actual parameters,a andb are called
formal parameters. num1 is copied to a and num2 is copied to b. Changes
made on a and b have no effect on num1 and num2.
2. Call by Reference
✤ In Call by Reference parameter passing method, the address of the
memory location address is copied to formal parameters. The address
of the actual parameters is passed to the called function and is
received by the formal parameters (pointers).
Hence changes made on the formal parameters have effect on the
actual parameters also.
Here, the addresses num1 and num2 are copied to a and b. Hence,
changes made on the pointer variables a and b have effect on the actual
parameters too.
main()
funct1()
Call funct1
funct2()
Call funct2
ret
ret
3.4 RECURSION
Recursion is the process of repeating items in a self-similar way. In
programming languages, a function calling itself is called recursive function.
void recursion()
{
recursion(); /* function calls itself */
}
void main()
{
recursion();
}
FUNCTIONS AND 3.23
POINTERS
The recursive functions should be used very carefully because; when a
function called by itself it enters into infinite loop. Define the condition to
exit from the function call so that the recursive function gets terminated.
Recursive functions are very useful to solve many mathematical problems,
such as calculating the factorial of a number, generating Fibonacci series,
etc.
fact(5)
3 * fact(2)
4 - call fact(3)
Step Step 7 - return 2 (2*1)
2 * fact(1)
Step 6 - return 2 (2*1)
- call fact(1)
Step 5
1
Fig 3.12 Factorial using Recursion
1+1=2 13 + 21 = 34
1 3,
1, 1, 2, +2 5,=8,313, 21,
2134,
+ 34
55,=89,
55 144,
233, 377,...
2+3=5 34 + 55 = 89
3+5=8 55 + 89 =
144
5 + 8 = 13 89 + 144 =
233
8 + 13 = 21 144 + 233 =
377
#include
<stdio.h>
intfibonacci(in
t i)
{
if(i == 0)
return 0;
if(i == 1)
return 1;
return fibonacci(i-1) + fibonacci(i-2);
}
void main()
{
int i;
for (i = 0; i < 10; i++)
printf("%d\t", fibonacci(i));
}
Execution:
Output:
0 1 1 2 3 5 8 13 21 34
FUNCTIONS AND 3.25
POINTERS
Merits of using Recursion
✤ To write efficient programs using a minimum amount of code.
✤ Nominal chance of syntax and logical errors.
✤ Increases the program efficiency.
Demerits of using Recursion
✤ Can cause infinite loops and other unexpected results if not written
properly.
✤ Recursion takes a lot of stack space, usually not considerable when
the program size is small.
✤ Recursion uses more processor time.
Key Points to remember while writing Functions
✤ Every C program has a function called main().
✤ C Functions can be invoked from anywhere within a C program.
✤ C functions can be called with or without arguments/parameters.
These arguments inputs to the functions.
✤ C functions may or may not return values to calling functions. These
values output of the functions.
✤ When a function completes its task, program control is returned to
the function from where it is called.
✤ Before calling and defining a function, declare function prototype
to inform the compiler about the function name, function parameters
and return value type.
✤ When return data type of a function is "void", then, it won't return
any values.
✤ When return data type of a function is other than void such as "int,
float, double", it returns value to the calling function.
3.26 PROGRAMMING IN C
#include
<stdio.h>
#include
<conio.h>
#include
<math.h>
#include
<stdlib.h> void
main()
{
int n, x1;
float acc, term, den, x, sinx=0,
sinval; clrscr();
printf("Enter the value of x (in
degrees)\n"); scanf("%f",&x);
x1 = x;
/* Converting degrees to
radians*/ x = x*(3.142/180.0);
sinval = sin(x);
printf("Enter the accuary for the
result\n"); scanf("%f", &acc);
term = x;
sinx =
term; n =
1;
do
{
den = 2*n*(2*n+1);
FUNCTIONS AND 3.27
POINTERS
term = -term * x * x /
den; sinx = sinx + term;
n = n + 1;
} while(acc<= fabs(sinval - sinx));
printf("Sum of the sine series = %f\n",
sinx);
printf("Using Library function sin(%d) = %f\n",
x1,sin(x)); getch();
}
Execution:
Input:
Enter the value of x (in
degrees) 45
Enter the accuary for the
result 0.00001
Output:
Sum of the sine series =0.707178
Using Library function sin(45)= 0.707179
Program 2:
Scientific Calculator using Built-in functions.
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main(void)
3.28 PROGRAMMING IN C
{
int choice, i, a,
b; float x, y,
result;
clrscr();
do
{
printf("\nSelect your operation (0 to exit):\n");
printf("1.Addition\n 2.Subtraction\
n 3.Multiplication\n
4.Division\n");
printf("5. Square root\n6. X ^ Y\n7. X ^ 2\n8. X ^ 3\n");
printf("Choice: ");
scanf("%d",
&choice);
if(choice == 0)
exit(0);
switch(choice)
{
case 1:
printf("Enter X:
");
scanf("%f", &x);
printf("\nEnter Y:
"); scanf("%f",
&y); result = x + y;
printf("\nResult: %f",
result); break;
case 2:
printf("Enter X:
");
scanf("%f", &x);
printf("\nEnter Y:
"); scanf("%f",
&y); result = x -
y;
printf("\nResult: %f",
result); break;
case 3:
printf("Enter X:
");
scanf("%f", &x);
FUNCTIONS AND 3.29
POINTERS
printf("\nEnter Y:
"); scanf("%f",
&y); result = x * y;
printf("\nResult: %f",
result); break;
case 4:
printf("Enter X:
");
scanf("%f", &x);
printf("\nEnter Y:
"); scanf("%f",
&y); result = x /
y;
printf("\nResult: %f",
result); break;
case 5:
printf("Enter X:
");
scanf("%f",
&x); result =
sqrt(x);
printf("\nResult: %f",
result); break;
case 6:
printf("Enter X:
");
scanf("%f", &x);
printf("\nEnter Y:
"); scanf("%f",
&y); result =
pow(x, y);
printf("\nResult: %f",
result); break;
case 7:
printf("Enter X:
");
scanf("%f", &x);
result = pow(x,
2);
printf("\nResult: %f",
result); break;
3.30 PROGRAMMING IN C
case 8:
printf("Enter X: ");
scanf("%f",
&x); result =
pow(x, 3);
printf("\nResult: %f",
result); break;
default:
printf("\nInvalid Choice!");
}
} while(choice);
getch();
}
Execution:
Input:
Select your operation (0 to exit):
1.Addition
2.Subtraction
3.Multiplication
4.Division
5.Square
root 6.X^Y
7.X^2
8.X^3
Output:
Choice:
1 Enter
X:5
Enter
Y:4
Result:
9
FUNCTIONS AND 3.31
POINTERS
Program 3:
Binary Search using Recursive functions.
4 5 10 15 20 25 30 35 40 45 50 58 65 80 98
4 5 10 15 20 25 30 35 40 45 50 58 65 80 98
4 5 10 15 20 25 30 35 40 45 50 58 65 80 98
Middle
Lower Higher
4 5 10 15 20 25 30 35 40 45 50 58 65 80 98
#include<stdio.h>
void main()
{
int a[10],i,n,m,c,l,u;
printf("Enter the size of an array: ");
scanf("%d",&n);
printf("Enter the elements of the
array: " ); for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("Enter the number to be
search: "); scanf("%d",&m);
3.32 PROGRAMMING IN C
l=0,u=n-1;
c=binary(a,n,m,l,u);
if(c==0)
printf("Number is not
found."); else
printf("Number is found.");
}
int binary(int a[],intn,intm,intl,int u)
{
intmid,c=0;
if(l<=u)
{
mid=(l+u)/2;
if(m==a[mid])
c=1;
else if(m<a[mid])
return binary(a,n,m,l,mid-1);
else
return binary(a,n,m,mid+1,u);
}
else
return
c;
}
Execution:
Input:
Enter the size of an
array: 4
Enter the elements of the array:
4 5 6 7
Enter the number to be
search: 7
Output:
Number is found.
FUNCTIONS AND 3.33
POINTERS
3.5 POINTERS
Pointers are the powerful feature of C that differentiates it from other
popular programming languages like: Java and Python. In c programming
language, we use normal variables to store data values. When we declare a
variable, the compiler allocates required memory with specified name. We
use a special type of variable called pointer to store the address of another
variable with same data type.
100 204
1 7
50
100
var ptr
(normal (pointe
variable) r)
Memory X 2568
Memory X 2568 32
Address of c: 2686784
Value of c: 2
**somewhere_else
*somewhere here
Value
Address
Address
The pointer-to-a-
The pointer contains The variable
pointer contains the
the address of a contains a value.
address of another
variable
pointer
Syntax:
datatype **pointerName ;
A variable that is a pointer to a pointer must be declared by placing an
additional asterisk in front of its name. For example, the following declaration
declares a pointer to a pointer of type int.
int **var;
*ptr;
int
**pptr; var
= 3000;
printf("Value of var = %d\n", var );
/* take the address of var
*/ ptr = &var;
printf("Address of 3000 = %u\n", ptr );
FUNCTIONS AND 3.39
POINTERS
printf("Value available at *ptr = %d\n", *ptr );
/* take the address of ptr using address of
operator & */ pptr = &ptr;
printf("Address of pointer = %u\n", pptr );
/* take the value using pptr */
printf("Value available at **pptr = %d\n", **pptr);
}
Execution:
Output:
Value of var = 3000
Address of 3000 =
7956
Value available at *ptr =
3000 Address of pointer =
6598
Value available at **pptr =
3000
3. Incrementing a Pointer
"Incrementing a pointer increases its value by the number of bytes
of its data type".
Let ptr be an integer pointer which points to the memory location 5000
and size of an integer variable is 32-bit(4 bytes). Now, when we increment
pointer ptr
ptr++;
will point to memory location 5004 because it will jump to the next integer
location which is 4 bytes next to the current location. Incrementing a pointer is
not same as incrementing an integer value. On incrementing, a pointer will
point to the memory location after skipping N bytes, where N is the size of the
data type (in this case it is 4).A character (1 bytes) pointer is incremented by 1
bytes.
ptr + (sizeof(pointer_data_type))
4. Decrementing a Pointer
"Decrementing a pointer increases its value by the number of bytes of
its data type"
ptr– –;
ptr will point to 4996.
ptr - (sizeof(pointer_data_type))
FUNCTIONS AND 3.41
POINTERS
5. Subtracting Pointers
The difference between two pointer returns indicates. It gives the total
number of elements between two pointers. If an integer pointer 'ptr1' points
at memory location 10000 and integer pointer 'ptr2' points at memory location
10008, the result of ptr2 – ptr1 is 2.
/* Initialize pointers */
int_ptr = &int_var;
char_ptr = &char_var;
float_ptr = &float_val;
printf("Address of int_var = %u\n", int_ptr);
printf("Address of char_var = %u\n",
char_ptr); printf("Address of float_var = %u\
n\n", float_ptr);
/* Incrementing pointers */
int_ptr++;
char_ptr++;
float_ptr++;
printf("After increment address in int_ptr = %u\n",
int_ptr); printf("After increment address in char_ptr =
%u\n", char_ptr); printf("After increment address in
float_ptr = %u\n\n", float_ptr);
/* Adding 2 to pointers */
int_ptr = int_ptr + 2;
char_ptr = char_ptr +
2; float_ptr = float_ptr
+ 2;
3.42 PROGRAMMING IN C
Execution:
Output:
Address of int_var = 2293300
Address of char_var =
2293299 Address of float_var
= 2293292
After increment address in int_ptr =
2293304 After increment address in
char_ptr = 2293300 After increment
address in float_ptr = 2293296 After
addition address in int_ptr = 2293312
After addition address in char_ptr =
2293302 After addition address in
float_ptr = 2293304
Rules
✤ An array name is a constant pointer.
✤ Array name can be used to access the address and value of all the
elements of that array.
✤ Since array name is a constant pointer we can't modify its value.
Consider the following example statements.
ptr = names + 2 ;
Here, the pointer variable "ptr" is assigned with address of "names[2]"
element.
printf("Address of 'names[4]' = %u",names+4) ;
The above printf statement displays the address of element "names[4]".
printf("Value of 'names[0]' = %d",*names) ;
printf("Value of 'names[3]' = %d",*(names+3)) ;
In the above two statements, first printf statement prints the value 89
(i.e., value of names[0]) and the second printf statement prints the value 72
(i.e., value of names[3]).
names++ ;
The above statement generates compilation error because the array name
acts as a constant pointer. So we can't change its value.
3.44 PROGRAMMING IN C
In the above example program, the array name names can be used as
follows.
Table 3.4
C \0 C + + \0 J a v a \0
Fig 3.19
1 2 3 4 5
lang[0] C \0
lang[1] C + + \0
lang[2] J a v a \0
Fig 3.20
435 = 4 + 3 + 5 =
12
#include
<stdio.h> void
main()
{
intnum, no, digit, sum = 0;
printf("Enter the number \
n"); scanf("%d", &num);
no = num;
while (num>
0)
{
digit = num %
10; sum =
sum + digit;
num /= 10;
}
printf("Given number = %d\n", no);
3.50 PROGRAMMING IN C
#include
<stdio.h>
#include
<string.h> void
main()
{
char
string1[20]; int i,
length;
int flag = 0;
printf("Enter a string:\
n"); scanf("%s",
string1); length =
strlen(string1);
for(i=0;i < length ;i+
+)
{
if(string1[i] != string1[length-i-1])
FUNCTIONS AND 3.51
POINTERS
{
flag = 1;
break;
}
}
if (flag)
printf("%s is not a palindrome\n",
string1); else
printf("%s is a palindrome\n", string1);
}
Execution:
Input:
Enter a string:
12 Enter a
string: dad
Output:
12 is not a
palindrome dad is
a palindrome
int power(intx,int i)
{
int p;
if(i==0)
p=1;
else
p=power(x,i-1)*x;
return p;
}
int fact(int x)
{
int f;
if(x==0
) f=1;
else
f=fact(x-1)*x;
return f;
}
float sum(intx,int n)
{
int i;
float s,s1=0,s2,s3;
for(i=0;i<n;i++)
{
s2=power(x,i);
s3=fact(n);
FUNCTIONS AND 3.53
POINTERS
s=s2/s3;
s1=s1+s
;
}
return s1;
}
}
Execution:
Input:
Enter the 'x'
value: 2 Enter the
'n' value: 3
Output:
sum of the series: 1.166667
for(i=1;i<=n;i++)
for(j=1;j<=i;j++)
sum = sum + n;
printf("sum = %d\n", sum);
}
Execution:
Input:
Please enter an integer, n =2
Output:
sum = 4
3.54 PROGRAMMING IN C
fact = fact * i
printf("Factorial = %d\n", fact);
}
Execution:
output:
Factorial = 120
Smalles Larges
t t
Elemen Elemen
t t
5 902
#inclu <stdio.h
de >
void main()
{
intarr[30],size,largest,i;
printf("Enter the size of the array
:\n "); scanf("%d",&size);
printf("Enter the numbers:\n ");
for(i=0;i<size;i++)
scanf("%d",&arr[i]);
largest =
find_largest(arr,size);
printf("\nThe largest element is: %d\
n",largest); smallest =
find_smallest(arr,size);
printf("\nThesmallest element is: %d\n",smallest);
}
FUNCTIONS AND 3.57
POINTERS
intfind_largest(int arr1[],int size1)
{
intlarge,i;
large=arr1[0];
for(i=1;i<size1;i++)
if(arr1[i] >large)
large =arr1[i];
return(large);
}
Execution:
Input:
Enter the size of the array:
4 Enter the numbers: 22 55
11 44 Output:
The largest element
is: 55 The smallest
element is: 11
3.58 PROGRAMMING IN C
✤ Formal Parameters
The formal parameters are the parameters that are declared at
called function.
When a function gets executed, the copy of actual parameters is
copied to the formal parameters.
1 3 . What is Parameter Passing in C?
When the execution control is transferred from calling function to called
function it may carry one or more number of data values. These data
values are called as parameters.
Parameters are the data values that are passed from calling
function to called function.
1 4 . How the functions are classified in C?
✤ Functions with no arguments and no return value.
✤ Functions with no arguments and with return value
✤ Functions with arguments and no return value.
✤ Functions with arguments and with return value
1 5 . What type of functions available in C?
The C language supports two types of functions.
Library functions
Library functions are pre-defined set of functions. These are called as
system defined functions or Pre-Defined Functions.printf(), scanf(), sqrt()
are examples of library functions.
User-defined functions
User-defined functions have to be developed by the user at the time of
writing the program.main() is an example of user-defined functions.
FUNCTIONS AND 3.63
POINTERS
1 6 . What is Function definition?
✤ The function definition provides the actual code of that function.
The function definition is also known as body of the function.
✤ The actual instructions of a function are written inside the braces "{ }".
✤ The function definition is performed before main function or after
main function.
1 7 . List the Various Built-In Functions in C.
The standard library functions are built-in functions in C programming
to handle tasks such as mathematical computations, I/O processing,
string handling etc.The various built-in functions along with the header
files are displayed in the follow.
Header File Purpose Example
REVIEW QUESTIONS
1. Explain the following with suitable examples.
(i) Function declaration. (8) (ii) Call by reference, call by value. (8)
2. i) Explain function with and without arguments with examples for each. (10)
ii) What is recursion? Give an example. (6)
3. What is a function in C? Discuss about call by value and call by reference
with illustration. (16)
4. What is recursion? Explain a recursion function with suitable example.
Write a iterative and recursive function to find the power of a number. (16)
5. Write in detail about pointer arithmetic. Support your answer with
suitable example. (16)
6. With an example program to explain the pointer to an array and array
of pointer. (16)