Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
6 views

8.user Defined Function in C

Uploaded by

23dcs069
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

8.user Defined Function in C

Uploaded by

23dcs069
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

User-defined functions

What is User-defined functions?


Why we need functions in C?
Types of functions
Advantage of functions in C
Flow of Control in multi-function Program
How to call a function in C?
Components/Element of user defined function
Categories of functions in c
Nesting of Function In C
What is Recursion?
Passing an array to the function
Passing Strings to Functions
Storage Classes in C
What is Call by value?
What is Call by Reference?

Edited by: Hardik S. Jayswal


What is User-defined functions?
C functions can be classified into two categories,

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.

Benefits of Using Functions

1. It provides modularity to your program's structure.

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.

4. It makes the program more readable and easier to understand.

Flow of Control in multi-function Program


Components/Element of user defined function

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 :-

int max(int num1, int num2);

Parameter names are not important in function declaration only their type is required, so the following
is also a valid declaration –

int max(int, int);

Function definition

Defining a Function

The general form of a function definition in C programming language is as follows

return type function name( parameter list )

body of the 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

There can be 4 different types of user-defined functions, they are:

1. Function with no arguments and no return value.


2. Function with no arguments and a return value.
3. Function with arguments and no return value.
4. Function with arguments and a return value.
To understand the above four categories, we will see the example of addition

Function with no arguments and no Function with no arguments and a return


return value. value
void Add(); int Add();

void Add() int Add()


{ {
int Sum, a = 10, b = 20; int Sum, a = 10, b = 20;
Sum = a + b; Sum = a + b;

printf("%d",Sum); return (sum);


} }

void main() void main()


{ {
Add(); // Function call int z;
} z=Add(); // Function call
printf(“%d”,z);
}

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;

printf("%d",Sum); return (Sum);


} }
void main() void main()
{ {
int a = 10, b = 20 int z, a = 10, b = 20;
Add(a,b); // Function call z=Add(a,b); // Function call
} printf(“%d”,z);
}
Example :-
Printing n Natural numbers (Identify the category of function ? )

#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:-

This is main method in c

This is a user define function

This is nested function in c


Example :-

#include<stdio.h>
#include<math.h>

int sum( );
float area(int,int ,int ,float );

float area(int a,int b ,int c,float s)


{
int area0;
area0=sqrt(s*(s-a)*(s-b)*(s-c));
return area0;
}
int sum()
{
int area1,s;
int a,b,c,area2;
printf("enter number");
scanf("%d",&a);
printf("enter number");
scanf("%d",&b);
printf("enter number");
scanf("%d",&c);
s=(a+b+c)/2;
area1=area(a,b,c,s);
if(a+b>c && b+c>a && c+a>b)
{
printf("this triangle is valid area is %d",area1);
}
else
{
printf("invalid triangle");
}
}
int main()
{

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.

// Fibonacci series Factorial of a Number Using Recursion


#include <stdio.h>
#include <stdio.h> long int multiplyNumbers(int n);
int main()
// Function for fibonacci {
int fib(int n) int n;
{ printf("Enter a positive
// Stop condition integer: ");
if (n == 0) scanf("%d", &n);
return 0; printf("Factorial of %d = %ld",
n, multiplyNumbers(n));
// Stop condition return 0;
if (n == 1 || n == 2) }
return 1; long int multiplyNumbers(int n)
{
if (n >= 1)
// Recursion function return n*multiplyNumbers(n-
else 1);
return (fib(n - 1) + fib(n - else
2)); return 1;
} }

// Driver Code
int main()
{
// Initialize variable n.
int n = 5;
printf("Fibonacci series "
"of %d numbers is: ",
n);

// for loop to print the


fibonacci series.
for (int i = 0; i < n; i++) {
printf("%d ", fib(i));
}
return 0;
}
passing array to the function in c
Passing array elements to a function is similar to passing variables to a function.

#include <stdio.h> #include <stdio.h>


void display(int age1, int age2) float calculateSum(float age[]);
{ int main()
printf("%d\n", age1); {
printf("%d\n", age2); float result, age[ ] = {23.4, 55, 22.6, 3, 40.5, 18};
} // age array is passed to calculateSum()
int main() result = calculateSum(age);
{ printf("Result = %f", result);
int ageArray[] = {2, 8, 4, 12}; return 0;
// Passing second and third elements to }
display() float calculateSum(float age[ ])
display(ageArray[1], ageArray[2]); {
return 0; float sum = 0.0;
} for (int i = 0; i < 6; ++i)
{
sum += age[i];
}
return sum;
}

Passing two-dimensional arrays

#include <stdio.h>

void displayNumbers(int num[2][2]);

int main()

int num[2][2], i, j;

printf("Enter 4 numbers:\n");

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

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

scanf("%d", &num[i][j]);

// passing multi-dimensional array to displayNumbers function

displayNumbers(num);

return 0; }
void displayNumbers(int num[2][2])

// Instead of the above line,

// void displayNumbers(int num[][2]) is also valid

int i, j;

printf("Displaying:\n");

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

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

printf("%d\n", num[i][j]);

Output

Enter 4 numbers:

Displaying:

5
Passing Strings to Functions

Strings can be passed to a function in a similar way as arrays.

#include <stdio.h>

void displayString(char str[]);

int main()

char str[50];

printf("Enter string: ");

gets(str);

displayString(str); // Passing string to a function.

return 0;

void displayString(char str[])

printf("String Output: ");

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>

// declaring the variable which is to be made extern


// an intial value can also be initialized to x
int x;

void autoStorageClass()
{

printf("\nDemonstrating auto class\n\n");

// declaring an auto variable (simply


// writing "int a=32;" works as well)
auto int a = 32;

// printing the auto variable 'a'


printf("Value of the variable 'a'"
" declared as auto: %d\n",
a);

printf("--------------------------------");
}

void registerStorageClass()
{

printf("\nDemonstrating register class\n\n");

// declaring a register variable


register char b = 'G';

// printing the register variable 'b'


printf("Value of the variable 'b'"
" declared as register: %d\n",
b);

printf("--------------------------------");
}

void externStorageClass()
{

printf("\nDemonstrating extern class\n\n");

// telling the compiler that the variable


// z is an extern variable and has been
// defined elsewhere (above the main
// function)
extern int x;
// printing the extern variables 'x'
printf("Value of the variable 'x'"
" declared as extern: %d\n",
x);

// value of extern variable x modified


x = 2;

// printing the modified values of


// extern variables 'x'
printf("Modified value of the variable 'x'"
" declared as extern: %d\n",
x);

printf("--------------------------------");
}

void staticStorageClass()
{
int i = 0;

printf("\nDemonstrating static class\n\n");

// using a static variable 'y'


printf("Declaring 'y' as static inside the loop.\n"
"But this declaration will occur only"
" once as 'y' is static.\n"
"If not, then every time the value of 'y' "
"will be the declared value 5"
" as in the case of variable 'p'\n");

printf("\nLoop started:\n");

for (i = 1; i < 5; i++) {

// Declaring the static variable 'y'


static int y = 5;

// Declare a non-static variable 'p'


int p = 10;

// Incrementing the value of y and p by 1


y++;
p++;

// printing value of y at each iteration


printf("\nThe value of 'y', "
"declared as static, in %d "
"iteration is %d\n",
i, y);

// printing value of p at each iteration


printf("The value of non-static variable 'p', "
"in %d iteration is %d\n",
i, p);
}

printf("\nLoop ended:\n");

printf("--------------------------------");
}

int main()
{

printf("A program to demonstrate"


" Storage Classes in C\n\n");

// To demonstrate auto Storage Class


autoStorageClass();

// To demonstrate register Storage Class


registerStorageClass();

// To demonstrate extern Storage Class


externStorageClass();

// To demonstrate static Storage Class


staticStorageClass();

// 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.

What is Function Call By value?


When we pass the actual parameters while calling a function then this is known
as function call by value. In this case the values of actual parameters are copied
to the formal parameters. Thus operations performed on the formal parameters
don’t reflect in the actual parameters.
Example of Function call by Value

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.

Swapping numbers using Function Call by Value


#include <stdio.h>

void swapnum( int var1, int var2 )


{
int tempnum ;
/*Copying var1 value into temporary variable */
tempnum = var1 ;

/* Copying var2 value into var1*/


var1 = var2 ;

/*Copying temporary variable value into var2 */


var2 = tempnum ;

}
int main( )
{
int num1 = 35, num2 = 45 ;
printf("Before swapping: %d, %d", num1, num2);

/*calling swap function*/


swapnum(num1, num2);
printf("\nAfter swapping: %d, %d", num1, num2);
}

Output:

Before swapping: 35, 45


After swapping: 35, 45
Function call by reference in C Programming

What is Function Call By Reference?

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);

/*calling swap function*/


swapnum( &num1, &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.

8. Write a program to pass a string as an argument to a user-defined function which checks


whether the string is palindrome or not. A string is said to be a palindrome if the string read
from left to right is equal to the string read from right to left.

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/

You might also like