Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 34

UNIT 3

User Defined Functions


FUNCTIONS
 “In c, we can divide a large program into the basic building blocks known as function. The function
contains the set of programming statements enclosed by {} that performs a particular task/job”.
 A function can be called multiple times to provide reusability and modularity to the C program.
 In other words, we can say that the collection of functions creates a program.
 The function is also known as procedure or subroutine in other programming languages.

Example:
void hello( )
{
printf("hello UVCE");
}
3.1 INTRODUCTION TO NEED OF FUNCTIONS:
 We know, the C program consists of a main function and inside that we are writing the logic of the program.
 Disadvantage of this method is,
 if the logic/code in the main function becomes huge or complex, it will become difficult to debug the
program or test the program or maintain the program.
 So we‟ll break down entire logic into different parts, this type of approach for solving the given problems is
known as Top Down approach.

PROGRAM ------ MAIN ------ MODULE1 MODULE2 MODULE3

 Advantages of Functions: Some of the advantages of writing/using functions are:


 Functions support top-down modular programming.
 By using functions, the length of the source code decreases.
 Writing functions makes it easier to isolate and debug the errors.
 Functions allow us to reuse the code.

Types Of Functions:
Based on the nature of functions, they can be divided into two categories.
They are:
1) In-built functions / Predefined functions / Library functions Ex: printf, scanf
2) User defined functions Ex: main()
a) In-built functions / Predefined functions:
 Is a function which is already written by another developer.
 The users generally use these library functions in their own programs for performing the desired task.
 The predefined functions are available in the header files.
 So, the user has to include the respective header file to use the predefined functions available in it.
 Example: the printf function which is available in the header file is used for printing information.
 Other examples of predefined functions are: scanf, strlen, strcat, sqrt, fabs etc.

b) User defined functions:


 A user defined function is a function which is declared and defined by the user himself.
 While writing programs, if there are no available library functions for performing a particular task, we
write our own function to perform that task.
 Example: for user defined function is main function.

Scope, Visibility & Lifetime Of Variables (Storage Classes)


“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).
 example: auto int i=1;
 They are assigned a garbage value by default whenever they are declared.

“extern”
 extern storage class simply tells us that the variable is defined elsewhere and not
within the same block where it is used.
 The main purpose of using extern variables is that they can be accessed between
two different files which are part of a large program.
 example: int i=1;------- extern int i;
 A normal global variable can be made extern as well by placing the “extern ‟
keyword before its declaration/definition in any function/block.
“static”
 This storage class is used to declare static variables 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.
 example: static int i=1;
 Global static variables can be accessed anywhere in the program.
 By default, they are assigned the value 0 by the compiler.

“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.
 example: register int i;
 An important and interesting point to be noted here is that we cannot obtain
the address of a register variable using pointers.
BASIC ELEMENTS OF USER DEFINED FUNCTION:
For creating user defined functions in C programs, we have to perform three steps.
They are:
a) Function Declaration: Declaring the function (blue-print).
b) Function Definition: Defining the function (logic).
c) Function Calling: use of function in program (calling)

d) FUNCTION DECLARATION:
 The function declaration is the blue print of the function. The function declaration can also be called as
the function’s prototype.
 The function declaration tells the compiler and the user about what is the function ‟s name, inputs and
output(s) of the function and the return type of the function.

Syntax: for declaring a function is shown below: return_type function_name(parameters list);

Example: int add(int m, int n);


In the above example, add is the name of the function, int is the return type of the function.
In our example, add function has two parameters. The parameters list is optional.
b) FUNCTION DEFINITION:
 The function definition specifies how the function will be working i.e the logic of the function
will be specified in this step.

Syntax: of function definition is shown below


return_type function_name(parameters list)
{
local variable declaration’s;
---
return(expression);
}

Example:
int add(int a, int b)
{
int res;
res = a+b;
return res;
}
c) FUNCTION CALLING:
 After declaring and defining the functions, we can use the functions in our program. For using the functions,
we must call the function by its name.
 Syntax: of function definition is shown below function_name(parameters list);
Example: add(m,n);

 Whenever the compiler comes across a function call, it takes the control of execution to the first statement in
the function‟s definition.
 After the completion of function i.e., whenever the compiler comes across the return statement or the
closing brace of the function’s body, the control will return back to the next statement after the function call.
CATEGORIES OF USER DEFINED FUNCTIONS:
 A function may or may not accept any argument. It may or may not return any value. Based on these facts,
there are four different aspects of function calls.
a) function without arguments and without return value
b) function without arguments and with return value
c) function with arguments and without return value
d) function with arguments and with return value

e) Function without arguments and without return value:


 In this type of functions there are no parameters/arguments in the function definition and the function
does not return any value back to the calling function.
 Generally, these types of functions are used to perform housekeeping tasks such as printing some
characters etc.
Example:
void printstars( )
{
int i;
for(i = 0; i < 20; i++)
{
printf(“ * ”);
}}
 In the above example, printstars function does not have any parameters. Its task is to print 20 stars
whenever it is called in a program.
b) Function without arguments and with return value:
 In this type of functions, the function definition does not contain arguments.
 But the function returns a value back to the point at which it was called.
Example:
int readint( )
{
int num;
printf(“Enter a number: “);
scanf(“%d”,&num);
return num;
}
 In the above example, readint function has no parameters/arguments. The task of this function is to read an
integer from the keyboard and return back to the point at which the function was called.

c) Function with arguments and without return value:


 In this type of functions, the function definition contains arguments.
 But the function does not returns a value back to the point at which it was called.
Example:
void sum(int a, int b)
{ printf("\nThe sum is %d",a+b); }

 In the above example, sum function has two parameters/arguments. The task of this function is to print the
sum without using return value.
d) Function with arguments and with return value:
 In this type of functions, the function definition consists of parameters/arguments.
 Also, these functions returns a value back to the point at which the function was called.
 These types of functions are the most frequently used in programming.
Example:
int add(int x, int y)
{
int result;
result = x + y;
return result;
}

 In the above example, the function add consists of two arguments or parameters x and y.
 The function adds both x and y and returns that value stored in the local variable result back to the point at
which the function was called.
PROGRAM TO FIND GCD & LCM USING FUNCTIONS:
Functions that return multiple values in C
 We already know that the design of C functions prohibits us from returning multiple values.
 However, programmers frequently want a function to return multiple values.
 Fortunately, there are a few solutions for returning multiple values in C.

The methods for returning multiple values from a function in C are as follows:
 Using pointers.
 Using structures.
 Using Arrays.

Using Pointers
In C, we may employ pointers to return more than one value from a function by passing pointers as function
arguments and using them to set several values visible in the caller function.

Example
#include <stdio.h>
// Function to return multiple values using pointers
void func(int *var1, int *var2, char *var3)
{
*var1 = 40;
*var2 = 50;
*var3 = 'X';
}
int main(void)
{
int var1, var2;
char var3;

func(&var1, &var2, &var3);


printf("var1 = %d, var2 = %d, var3 = %c", var1, var2, var3);
return 0;
}

Output:

var1 = 40, var2 = 50, var3 = X


RECURSIVE FUNCTION
 “A function is said to be recursive, if a function calls itself within the function ‟s definition”.
 When writing recursive functions, proper care must be taken that the recursive calls return a value back at
some point.
 Otherwise, the function calls itself infinite number of times.
 Example: In the above example, func1 is calling itself in the last line of its definition.

FACTORIAL OF A NUMBER –
 Factorial of n is the product of all positive descending integers.
 Factorial of n is denoted by n!
 Example: 5! = 5*4*3*2*1 = 120
 Recursive function: 5!=5*4! // n * Fact(n-1)
4!=4*3! ……….. 1!=1*0! 0!=1 //stop calling
Program to find factorial of given number using recursion:
#include
int find_factorial(int);
void main()
{
int num, fact;
printf("\nEnter any integer number:");
scanf("%d",&num);
fact =find_factorial(num);
printf("\nfactorial of %d is: %d",num, fact);
}
//recursive function definition
int find_factorial(int n)
{
if(n==0)
{
return 1;
}
else
{
return(n*find_factorial(n-1));
}
}
FIBONACCI SERIES
 A series of numbers in which each number ( Fibonacci number ) is the sum of the two preceding numbers.
Example: 0, 1, 1, 2, 3, 5, 8, etc.
 The first two numbers of fibonacci series are 0 and 1.

Recursive Function:
There are 3 cases in fibonacci series
1) if n = 1 only one digit to be printed i.e “0”.
2) 2) if n = 2 only two digit to be printed i.e “1”.
3) 3) if n > 2 last two digits to be added & printed so “fib(n-1) + fib(n-2)”

Program to find Fibonacci Series using recursion:


#include
int fib(int);
void main()
{ int n, i = 0, c;
printf(“enter N value\n”);
scanf("%d", &n);
printf("Fibonacci series terms are:\n");
for (c = 1; c <= n; c++)
{ printf("%d\n", fib(i)); i++; } }
int fib(int n)
{ if (n == 0 || n == 1) return n;
else return (fib(n-1) + fib(n-2)); }
Program to Convert Binary number to Decimal:
#include <stdio.h>
int convert(int);
void main()
{ int dec, bin;
printf("Enter a Binary number\n");
scanf("%d", &bin);
dec = convert(bin);
printf("The Decimal Equivalent of %d is %d \n", bin, dec);
}
int convert(int bin)
{
if (bin == 0)
{
return 0;
}
else
{
return (bin % 10 + 2 * convert(bin/10));
}
}
Program to check whether the given number is prime or not:
#include
int isPrime(int);
void main()
{
int res,num;
printf("Enter the number:");
scanf("%d",&num);
res=isPrime(num);
if(res==0)
printf("%d is not a Prime Number\n",num);
else printf("%d is a Prime Number\n",num);
}
int isPrime(int num)
{ int i;
if (num==0 || num==1)
return 0;
for (i=2; i<=num/2; i++)
{
if (num %i == 0)
{
return 0; } }
return 1; }
Passing arrays to functions
 Passing arrays to functions using recursion is a programming technique where a function calls itself to
process or manipulate elements of an array, typically through recursive function calls on subarrays or
individual elements.
Example:
#include <stdio.h>

int recursive_sum(int arr[], int index) {


if (index == 0) {
return arr[0];
} else {
return arr[index] + recursive_sum(arr, index - 1);
}
}

int main() {
int my_array[] = {1, 2, 3, 4, 5};
int result = recursive_sum(my_array, sizeof(my_array) / sizeof(my_array[0]) - 1);
printf("Sum of array elements: %d\n", result);
return 0;
}

OUTPUT: 15
Passing strings to functions
 Passing strings to functions using recursion in C language involves creating recursive functions that work with
character arrays (strings) to perform various operations.
 Definition: Passing strings to functions using recursion in C means creating recursive functions that
manipulate or process character arrays (strings) by calling themselves with sub-strings or individual
characters.

Example 1:
#include <stdio.h>
// Function to calculate the length of a string recursively
int recursive_strlen(const char *str) {
if (*str == '\0’) {
return 0; // Base case: end of the string
} else {
return 1 + recursive_strlen(str + 1); // Recursion: move to the next character
} }

int main() {
const char *my_string = "Hello, World!";
int length = recursive_strlen(my_string);
printf("Length of the string: %d\n", length);
return 0;
} OUTPUT: Length of
the string is 13
Example 2:
#include <stdio.h>
// Function to reverse a string recursively
void recursive_reverse(char *str, int start, int end) {
if (start >= end) {
return; // Base case: the string is reversed
} else {
// Swap characters at start and end positions
char temp = str[start];
str[start] = str[end];
str[end] = temp;

// Recursion: move to the next pair of characters


recursive_reverse(str, start + 1, end - 1);
}
}

int main() {
char my_string[] = "Hello, World!";
recursive_reverse(my_string, 0, strlen(my_string) - 1);
printf("Reversed string: %s\n", my_string);
return 0;
} OUTPUT: Reversed string: !dlroW ,olleH
POINTERS
 A pointer is a derived data type in C.
 It is built from one of the fundamental data types available in C.
 Pointers contain memory addresses as their values.
 Since these memory addresses are the locations in the computer memory where program instructions and
data are stored.
 pointers can be used to access and manipulate data stored in the memory.
Advantages of Pointers:
Pointers are used frequently in C, as they offer a number of benefits to the programmers.
They include the following:
 Pointers are more efficient in handling arrays and data tables.
 Pointers allow C to support dynamic memory management.
 Pointers provide an efficient way for manipulating dynamic data structures such as structures, linked lists,
queues, stacks and trees.
 Pointers increase the execution speed and thus reduce the program execution time.
 Pointers can be used to return multiple values from a function via function arguments.
 Pointers allow passing a function as argument to other functions.

How a Pointer Works:


 Whenever we declare a variable in our programs, the system allocates somewhere in the memory, an
appropriate location to hold the value of the variable.
 This location will have its own address number.
 Consider the following example:
The above statement int var creates a location in the memory to hold integer value.
That location will have an address for example assume it is 5000.
The statement var = 200 stores the value 200 at the location whose address is 5000.
So, in our example, var is the variable name, 200 is the value stored in var and 5000 is the address of the
memory location containing the variable var.
So, we can access the value 200 either by using the variable name var or by using the address of the memory
location which is 5000.‟

a) Pointer Variable, Constants & Values:


 “The concept of storing memory address in a variable and accessing the value available at that address is
known as a pointer variable.”
 Since the pointer is also variable, it will also have a memory address just like any other variable.

 Pointer Constants: The memory addresses within a computer are referred to as pointer constants.

 Pointer Values: We cannot assign the memory addresses directly to a variable. We can only get the address of
a variable by using the address operator (&). The value thus obtained is known as pointer value.

 Pointer Variables: Once we obtain the pointer value, we can store it in a variable. Such variable which stores
the memory address is known as a pointer variable.
b) Declaring Pointer Variables:
 In C, every variable must be declared for its type.
 Since pointer variables contain addresses that belong to a specific data type, they must be
declared as pointers before we use them.
Syntax for declaring a pointer is as shown below:
datatype *pointer-name;

 This tells the compiler three things about the variable pointer-name.
 They are: The asterisk (*) tells that the variable pointer-name is a pointer variable, pointer-name
needs a memory location and pointer-name points to a variable of type datatype.
 Example: int *p; float *p; char *ch;

c) Initialization of pointer variables:


 The process of assigning the address of a variable to pointer variable is known as initialization.
Method-1: int x; //declare a data variable
int *px; //declare a pointer variable px=&x // copy the address of data variable to
pointer variable
Method-2: int x; //declare a data variable
int *px=&x; //assign the address of data variable to pointer variable
Method-3: int x,*px=&x; //declare data variable and assign address
d) Dereferencing:
 Dereferencing a pointer means getting the value that is stored in the memory location pointed by the
pointer.
 The operator * is used to do this, and is called the dereferencing operator.
 Another name for the dereferencing operator is the indirection operator.
Example:
int quantity, *p, n;
quantity=179;
p=&quantity;
n=*p;

POINTERS AS FUNCTION ARGUMENTS


 When we pass the address of a variable as an argument the receiving parameter should be pointers.
 This process of calling a function using pointers to pass the addresses of variables is known as “Call by
reference”.
 This method will directly access the memory locations of actual parameters.
 So the changes made on the formal parameters effects the values of actual parameters.
Example:
void swap(int *a, int *b) // called function
{
int temp;
temp = *a;
*a = *b;
*b = temp;
}
Passing Structures to Functions (using Pointers):
 Functions are the basic building blocks of a C program.
 So, it is natural for C language to support passing structures as parameters in functions.
 We can pass the C structures to functions using pointers its also called as “Passing the address of the
structure (pass by reference)”.
Syntax for passing address the structure variable using pointer as a parameter:
return-type function-name(struct structname *var)
{
----
return expression;
}
We can access the members of structure using “arrow (->) operator or membership operator”.

DRAWBACKS OF POINTERS:
 Uninitialized pointers might cause segmentation fault.
 Dynamically allocated block needs to be freed explicitly. Otherwise, it would lead to memory leak.
 Pointers are slower than normal variables.
 If pointers are updated with incorrect values, it might lead to memory corruption.
 Understanding and using pointers in best way possible requires a lot of time.
Example:
#include
#include
struct student
{
int id;
char name[20];
float percentage;
};

void func(struct student *record);


void main()
{
struct student record = {“01”, “vishal”,”12”}
func(&record);
}

void func(struct student record)


{
printf(" Id is: %d \n", record->id);
printf(" Name is: %s \n", record->name);
printf(" Percentage is: %f \n", record->percentage);
}
Function returning pointer
Pointers in C programming language is a variable which is used to store the memory address of another variable.
We can pass pointers to the function as well as return pointer from a function.
But it is not recommended to return the address of a local variable outside the function as it goes out of scope
after function returns.

Program 1:
The below program will give segmentation fault since ‘A’ was local to the function:

// C program to illustrate the concept of returning pointer from a function


#include <stdio.h>
// Function returning pointer
int* fun()
{
int A = 10;
return (&A);
}

// main Code
int main()
{
// Declare a pointer
int* p;
/ Function call
p = fun();

printf("%p\n", p);
printf("%d\n", *p);
return 0;
}

Runtime Errors:
Segmentation fault

Output:
No output

 The main reason behind this scenario is that compiler always make a stack for a function call.
 As soon as the function exits the function stack also gets removed which causes the local variables of
functions goes out of scope.

 Static Variables have a property of preserving their value even after they are out of their scope.
 So to execute the concept of returning a pointer from function in C you must define the local variable as a
static variable.
0x601038 10
PROGRAM 2: // C program to illustrate the concept of returning pointer from a function
#include <stdio.h>

// Function that returns pointer


int* fun()
{
// Declare a static integer
static int A = 10;
return (&A);
}

// main Code
int main()
{
// Declare a pointer
int* p;
// Function call
p = fun();
// Print Address
printf("%p\n", p);
// Print value at the above address
printf("%d\n", *p);
return 0; } OUTPUT: 0x601038
10

You might also like