8.user Defined Function in C
8.user Defined Function in C
1. Library functions
2. User-defined functions
Library functions are those functions which are already defined in C library,
example printf(), scanf(), strcat() etc. You just need to include appropriate header files to use these
functions. These are already declared and defined in C libraries.
A User-defined functions on the other hand, are those functions which are defined by the user at the time
of writing program. These functions are made for code reusability and for saving time and space.
A function is a block of code that performs a specific task. C allows you to define functions according to
your need. These functions are known as user-defined functions
There are many situations where we might need to write same line of code for more than once in a
program. This may lead to unnecessary repetition of code, bugs and even becomes boring for the
programmer. So, C language provides an approach in which you can declare and define a group of
statements once in the form of a function and it can be called and used whenever required.
These functions defined by the user are also known as User-defined Functions
Why we need functions in C
Functions are used because of following reasons –
1) To improve the readability of code.
2) Improves the reusability of the code, same function can be used in any program rather than writing
the same code from scratch.
3) Debugging of the code would be easier if you use functions, as errors are easy to be traced.
4) Reduces the size of the code, duplicate set of statements are replaced by function calls.
2. It makes your code reusable. You just have to call the function by its name to use it, wherever
required.
3. In case of large programs with thousands of code lines, debugging and editing becomes easier if you
use functions.
In order to make use of a user defined function, we need to establish three elements of user defined
functions which are as follows
1. Function Declaration
2. Function Definition
3. Function call
Function Declaration
A function declaration tells the compiler about a function name and how to call the function. The actual
body of the function can be defined separately.
A function declaration has the following parts –
return_type function_name( parameter list );
Example :-
Parameter names are not important in function declaration only their type is required, so the following
is also a valid declaration –
Function definition
Defining a Function
return statement
A function definition in C programming consists of a function header and a function body. Here are all
the parts of a function −
Return Type − A function may return a value. The return_type is the data type of the value the
function returns. Some functions perform the desired operations without returning a value. In
this case, the return_type is the keyword void.
Function Name − This is the actual name of the function. The function name and the parameter
list together constitute the function signature.
Parameters − A parameter is like a placeholder. When a function is invoked, you pass a value to
the parameter. This value is referred to as actual parameter or argument. The parameter list
refers to the type, order, and number of the parameters of a function. Parameters are optional;
that is, a function may contain no parameters.
Function Body − The function body contains a collection of statements that define what the
function does.
Function call
When a function is called, control of the program gets transferred to the function.
functionName(argument1, argument2,...);
Example : - add(a,b);
categories of functions in c
Function with arguments and no return Function with arguments and a return
value. value.
void Add(int); int Add(int);
void Add(int x, int y ) int Add(int x, int y )
{ {
int Sum; int Sum;
Sum = x + y; Sum = x + y;
#include< stdio.h>
#include< conio.h>
void nat( int);
void main()
{
int n;
clrscr();
printf("\n Enter n value:");
scanf("%d",&n);
nat(n);
getch();
}
void nat(int n)
{
int i;
for(i=1;i<=n;i++)
printf("%d\t",i);
}
Output:
Enter n value: 5
12345
Example :-
#include< stdio.h>
#include<conio.h>
int fact(int);
void main()
{
int n;
clrscr();
printf("\n Enter n:");
scanf("%d",&n);
printf("\n Factorial of the number : %d", fact(n));
getch();
}
int fact(int n)
{
int i,f;
for(i=1,f=1;i<=n;i++)
f=f*i;
return(f);
}
Example:-
#include< stdio.h>
#include< conio.h>
int sum();
void main()
{
int s;
clrscr();
printf("\n Enter number of elements to be added :");
s=sum();
printf("\n Sum of the elements :%d",p);
getch();
}
int sum()
{
int a[20], i, s=0,n;
scanf("%d",&n);
printf("\n Enter the elements:");
for(i=0;i< n; i++)
scanf("%d",& a[i]);
for(i=0;i< n; i++)
s=s+a[i]; return s;}
#include <stdio.h>
#include <stdlib.h>
int main()
{
printf("This is main method in c\n");
function_one();
getch();
return 0;
}
void function_one()
{
printf("This is a user define function\n");
function_two();
}
void function_two()
{
printf("This is nested function in c\n");
}
O/P:-
#include<stdio.h>
#include<math.h>
int sum( );
float area(int,int ,int ,float );
sum();
return 0;
}
What is Recursion?
The process in which a function calls itself directly or indirectly is called recursion and the
corresponding function is called as recursive function.
// Driver Code
int main()
{
// Initialize variable n.
int n = 5;
printf("Fibonacci series "
"of %d numbers is: ",
n);
#include <stdio.h>
int main()
int num[2][2], i, j;
printf("Enter 4 numbers:\n");
scanf("%d", &num[i][j]);
displayNumbers(num);
return 0; }
void displayNumbers(int num[2][2])
int i, j;
printf("Displaying:\n");
printf("%d\n", num[i][j]);
Output
Enter 4 numbers:
Displaying:
5
Passing Strings to Functions
#include <stdio.h>
int main()
char str[50];
gets(str);
return 0;
puts(str);
}
Storage Classes in C
auto: This is the default storage class for all the variables declared inside a function or a block.
Hence, the keyword auto is rarely used while writing programs in C language. Auto variables can
be only accessed within the block/function they have been declared and not outside them (which
defines their scope).
extern: Extern storage class simply tells us that the variable is defined elsewhere and not
within the same block where it is used. Basically, the value is assigned to it in a different block
and this can be overwritten/changed in a different block as well. So an extern variable is nothing
but a global variable initialized with a legal value where it is declared in order to be used elsewhere
static: This storage class is used to declare static variables which are popularly used while
writing programs in C language. Static variables have a property of preserving their value even
after they are out of their scope! Hence, static variables preserve the value of their last use in their
scope. So we can say that they are initialized only once and exist till the termination of the
program.
register: This storage class declares register variables which have the same functionality as
that of the auto variables. The only difference is that the compiler tries to store these variables in
the register of the microprocessor if a free register is available. This makes the use of register
variables to be much faster than that of the variables stored in the memory during the runtime of
the program. If a free register is not available, these are then stored in the memory only.
// A C program to demonstrate different storage
// classes
#include <stdio.h>
void autoStorageClass()
{
printf("--------------------------------");
}
void registerStorageClass()
{
printf("--------------------------------");
}
void externStorageClass()
{
printf("--------------------------------");
}
void staticStorageClass()
{
int i = 0;
printf("\nLoop started:\n");
printf("\nLoop ended:\n");
printf("--------------------------------");
}
int main()
{
// exiting
printf("\n\nStorage Classes demonstrated");
return 0;
}
Function call by value in C programming
Actual parameters: The parameters that appear in function calls.
Formal parameters: The parameters that appear in function declarations
For example:
#include <stdio.h>
int sum(int a, int b)
{
int c=a+b;
return c;
}
int main(
{
int var1 =10;
int var2 = 20;
int var3 = sum(var1, var2);
printf("%d", var3);
return 0;
}
In the above example variable a and b are the formal parameters (or formal
arguments). Variable var1 and var2 are the actual arguments (or actual
parameters). The actual parameters can also be the values. Like sum(10, 20),
here 10 and 20 are actual parameters.
As mentioned above, in the call by value the actual arguments are copied to the
formal arguments, hence any operation performed by function on arguments
doesn’t affect actual parameters.
}
int main( )
{
int num1 = 35, num2 = 45 ;
printf("Before swapping: %d, %d", num1, num2);
Output:
When we call a function by passing the addresses of actual parameters then this
way of calling the function is known as call by reference. In call by reference, the
operation performed on formal parameters, affects the value of actual parameters
because all the operations performed on the value stored in the address of actual
parameters
#include
void swapnum ( int *var1, int *var2 )
{
int tempnum ;
tempnum = *var1 ;
*var1 = *var2 ;
*var2 = tempnum ;
}
int main( )
{
int num1 = 35, num2 = 45 ;
printf("Before swapping:");
printf("\nnum1 value is %d", num1);
printf("\nnum2 value is %d", num2);
printf("\nAfter swapping:");
printf("\nnum1 value is %d", num1);
printf("\nnum2 value is %d", num2);
return 0;
}
Output:
Before swapping:
num1 value is 35
num2 value is 45
After swapping:
num1 value is 45
num2 value is 35
Practice Program:
1. Write a program to find LCM and GCD of the given two numbers using two functions. Write
a program using the categories “Function with argument and with return type” and
“Function with argument and with no return type”.
2. Write a program to evaluate the following using up to N terms using nested functions.
1/1!+2/2!+3/3!.....N/N!
3. Write a program to check whether the given integer number is palindrome or not using
nested functions.
4. Write a program to find the sum of the entered number’s digits using recursive function.
5. Write a program to find binary equivalent of given positive integer number using recursive
function.
6. Write a program to enter N elements in array. Enter another number and find its position in
the given array using function.
7. Write a program which passes the array as an argument to a user-defined function and
find maximum and minimum number from the array of n elements.
9. Write a program to delete a character from the given string using function.
10. Write a program to pass two matrices to function and calculate the sum of two matrices.
(Hint: pass two-dimensional array to the function) .
References: -
1. https://www.programiz.com/c-programming/c-user-defined-functions
2. https://code4coding.com/user-defined-function-in-c/#Types_of_the_user-
defined_function_in_C_language
3. https://www.studytonight.com/c/user-defined-functions-in-c.php
4. https://beginnersbook.com/2014/01/c-functions-examples/
5. https://www.tutorialspoint.com/cprogramming/c_functions.htm
6. https://www.javatpoint.com/functions-in-c
7. https://www.geeksforgeeks.org/nested-functions-c/
8. https://code4coding.com/nesting-of-function-in-c/