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

Functions

Unit 5 covers user-defined functions in C, detailing their necessity for code reusability, modularity, and ease of debugging. It explains the elements of functions, types of function calls, and various categories of functions, including those with and without arguments and return values. Additionally, it discusses function nesting, recursion, and provides examples for better understanding.

Uploaded by

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

Functions

Unit 5 covers user-defined functions in C, detailing their necessity for code reusability, modularity, and ease of debugging. It explains the elements of functions, types of function calls, and various categories of functions, including those with and without arguments and return values. Additionally, it discusses function nesting, recursion, and provides examples for better understanding.

Uploaded by

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

UNIT 5

USER DEFINED FUNCTIONS


Contents
◦ User Defined Functions: Need for User-defined Functions,
◦ A Multi-Function Program,
◦ Elements of User defined Functions,
◦ Definition of Functions,
◦ Return Values and their Types,
◦ Function Calls,
◦ Function Declaration,
◦ Category of Functions: 1.No Arguments and no Return Values,
2.Arguments but No Return Values, 3.Arguments with Return
values, 4.No Arguments but Returns a Value, 5.Functions that
Return Multiple Values,
◦ Nesting of Functions,
◦ Recursion
Functions:
◦ A function in C is a set of statements that when called perform some
specific tasks.

◦ A function is a block of code which only runs when it is called.

◦ You can pass data, known as parameters, into a function.

◦ Functions are used to perform certain actions, and they are important
for reusing code: Define the code once, and use it many times.
Need for User-defined Functions
◦ The function can reduce the repetition of the same
statements in the program- Code reusability
◦ The function makes code readable by providing
modularity to our program.
◦ There is no fixed number of calling functions it can be
called as many times as you want.
◦ The function reduces the size of the program.
◦ Once the function is declared you can just use it
without thinking about the internal working of the
function.
Need for User-defined Functions
◦ Modular programming - Reduction in the amount of work and
development time - Program and function debugging is easier.
◦ Division of work is simplified due to the use of divide-and-
conquer principle.
◦ Reduction in size of the program due to code reusability
◦ Function can be access repeatedly without redevelopment,
which in turn promotes reuse of code.
◦ Library of function can be implemented by combining well
designed, tested and proven function.
Multi-Function Program
A program that uses more than one functions is called a multi-function program.

Int main()
{
int a;
printf(“Enter any number”);
scanf(“%d”,&a);
printf(“%d”,sizeof(a));
return 0;
}
Types of functions
◦ 1. pre-defined/library functions

◦ 2. user defined functions


1.pre-defined/library functions
◦ A library function is also referred to as a “built-in
function”.
◦ A compiler package already exists that contains these
functions, each of which has a specific meaning and is
included in the package.
◦ Built-in functions have the advantage of being directly
usable without being defined, whereas user-defined
functions must be declared and defined before being
used.
◦ Ex. pow(), sqrt(), strcmp(), strcpy() etc.
User Defined Functions
The elements of user-defined functions in C
◦ Function declaration: Informs the compiler about the
function's name, parameters, data types, and return
type.
◦ Function definition: Contains the body of the function,
which is the code to be executed.
◦ Function call: An essential part of a user-defined
function in C.
◦ Return type: Defines the data type of the value returned
by the function.
◦ Parameters: A user-defined function can take zero or
more input parameters.
Syntax of user defined functions in C
◦ The syntax of function can be divided into 3 aspects:

◦ Function Declaration
◦ Function Definition
◦ Function Calls
Function Declarations

◦ In a function declaration, we must provide the function name, its return type, and the
number and type of its parameters.
◦ A function declaration tells the compiler that there is a function with the given
name defined somewhere else in the program.
◦ Syntax:return type name_of_the_function (parameter_1, parameter_2);
◦ The parameter name is not mandatory while declaring functions. We can also declare
the function without using the name of the data variables.
◦ Example
◦ int sum(int a, int b); // Function declaration with parameter names
◦ int sum(int , int); // Function declaration without parameter names
Function Definition
The function definition consists of actual statements which are executed
when the function is called (i.e. when the program control comes to the
function).

The below example serves as both a function definition and a declaration.

return_type function_name (para1_type para1_name, para2_type


para2_name)
{
// body of the function
}
Function Call

◦ A function call is a statement that instructs the compiler to execute the


function. We use the function name and parameters in the function call.

◦ In the below example, the first sum function is called and 10,30 are passed to the sum
function. After the function call sum of a and b is returned and control is also returned
back to the main function of the program.
Return Values and their Types
int
void
float
char
pointer
Passing Parameters to Functions
◦ The data passed when the function is being invoked is known as the
Actual parameters.
◦ In the below program, 10 and 30 are known as actual parameters.
◦ Formal Parameters are the variable and the data type as mentioned in
the function declaration.
◦ We can pass arguments to the C function in two ways:
◦ Pass by Value
◦ Pass by Reference
1.pass by value
◦ Parameter passing in this method copies values from
actual parameters into formal function parameters.
◦ As a result, any changes made inside the functions do
not reflect in the caller’s parameters.
Example pass by value
#include <stdio.h> sum(var1, var2);
void sum(int var1, int var2) //Printf(“sum=%d”,sum); cant access sum in
{ main() function.
int sum=var1+var2; return 0;
printf(“Sum=%d”,sum);
}
}
O/P: Sum=5
// Driver code
int main()
{
int var1 = 3, var2 = 2;
Example pass by value
#include <stdio.h> printf("Before swap Value of var1 and var2
void swap(int var1, int var2) is: %d, %d\n",var1, var2);
{ swap(var1, var2);
int temp = var1; printf("After swap Value of var1 and var2
var1 = var2; is: %d, %d",var1, var2);
var2 = temp; return 0;
}
}
// Driver code
O/P: Before swap Value of var1 and var2
int main()
is: 3, 2
{
After swap Value of var1 and var2 is: 3, 2
int var1 = 3, var2 = 2;
2. Pass by Reference
◦ The caller’s actual parameters and the function’s
actual parameters refer to the same locations, so any
changes made inside the function are reflected in the
caller’s actual parameters.
Example call by reference
// C program to show use of printf("Before swap Value of var1 and var2 is: %d, %d\n",
var1, var2);
// call by Reference
swap(&var1, &var2);
#include <stdio.h>
printf("After swap Value of var1 and var2 is: %d, %d",
var1, var2);
void swap(int *var1, int *var2)
return 0;
{
int temp = *var1; }

*var1 = *var2;
O/P:
*var2 = temp;
Before swap Value of var1 and var2 is: 3, 2
}
After swap Value of var1 and var2 is: 2, 3
// Driver code
int main()
{
int var1 = 3, var2 = 2;
Category of Functions:
1.No Arguments and no Return Values

2.Arguments but No Return Values

3.Arguments with Return values

4.No Arguments but Returns a Value

5.Functions that Return Multiple Values,


1.No Arguments and no Return Values
# include <stdio.h> ◦ O/P: sum=30
void sum(); //function prototype/declaration
int main()
{
sum(); //function call
return 0;
}
void sum() //function definition
{
int a,b,sum;
a=10;
b=20;
sum=a+b;
printf("Sum=%d",sum);
}
2.Arguments but No Return Values
# include <stdio.h> ◦ O/P:Sum=30;
void sum(int x,int y)
{
int sum;
sum=x+y;
printf("Sum=%d",sum);
}
int main()
{ int a,b;
a=10;
b=20;
sum(a,b);
return 0;
}
3.Arguments with Return values
# include <stdio.h> int main()
int sum(int x,int y) { int a,b,result;
{ a=10;
int sum; b=20;
sum=x+y; result=sum(a,b);
return sum; rintf("\nResult=%d",result);
} return 0;
}
◦ O/P:
◦ Result=30
4.No Arguments but Returns a Value
# include <stdio.h> int main()
int sum() { int result;
{ result=sum();
int sum,x=10,y=20; printf("\nResult=%d",result);
sum=x+y; return 0;
return sum; }
} ◦ O/P:
◦ Result=30
5.Functions that Return Multiple Values
# include <stdio.h> int main()
int check(int x,int y) { int a,b,result;
a=10;
{
b=20;
if(x>y)
result=check(a,b);
return x;
printf("%d is the greater number“,result);
else return 0;
return y; }
} ◦ O/P:20 is the greater number
Nesting of Functions
◦Nested functions in C refer to the ability to define
functions within the scope of other functions.
◦ Unlike many other programming languages, C
traditionally doesn't support nested functions.
◦ However, some compilers, such as GNU Compiler
Collection (GCC), offer an extension to the C language
that enables nested functions.
Example 1:
#include <stdio.h>
void outerFunction() {
int x = 10;
void innerFunction() {
printf("Inner function: %d\n", x);
}
innerFunction();
}
int main() {
outerFunction();

//innerFunction(); Will give an error


return 0;
}
O/P:Inner function: 10
Example 2: O/P:in View
#include <stdio.h>
in Main
int main() before return
{ • In GCC (GNU C Compiler), there is an
auto int view(); extension that allows you to declare
view(); nested functions.
printf("in Main\n"); • However, to use this extension, you
int view() need to start the declarations of
{ these nested functions with the
printf("in View\n"); “auto” keyword as a prefix.
return 1;
}
• This extension enables you to define
printf("before return");
functions inside other functions,
return 0; which is not a standard feature in C
} but can be useful in certain
programming scenarios.
Some examples to try…..
1. WA function to find factorial of a given number

2. WA function fpow(int x, int y),which finds xy, and returns the


result.

3. WA function to find greatest of 3 numbers

4. WA function to find average of marks of five subjects of a


student.
Function to display an array
#include <stdio.h> printf("\n Enter the elements:");
for(i=0;i<=n-1;i++)
void display(int a[],int n)
scanf("%d",&a[i]);
{
display(a,n);
int i;
return 0;
for(i=0;i<=n-1;i++)
}
printf("%d\t",a[i]);
O/P:
}
Enter no of elements in an array5
int main()
{
Enter the elements:1
int a[10],n,i;
2
printf("Enter no of elements in an array");
3
scanf("%d",&n);
4
5
1 2 3 4 5
Function to read & display an array
#include <stdio.h> int main()
void getArray(int arr[], int size) {
int a[10],n,i;
{
printf("Enter no of elements in an array:");
int i; scanf("%d",&n);
getArray(a,n);
printf("Enter elements in array: ");
printf("\n Array elements are:\n");
for (i = 0; i < size; i++) display(a,n);

{ return 0;
}
scanf("%d", &arr[i]);
} O/P:Enter no of elements in an array:5
} Enter elements in array: 9

void display(int a[],int n) 5


7
{
1
int i; 3
for(i=0;i<=n-1;i++)
Array elements are:
printf("%d\t",a[i]);
9 5 7 1 3
}
User defined function to find length of a string
#include <stdio.h> int main()
int slen(char s1[]) {
{ char str1[]="COMPUTER";
int i,length=0; int len=slen(str1);
for(i=0; s1[i]!='\0'; i++) printf("Length of a string is %d",len);
{ return 0;
length++; }
}
return length;
}
Function returning a string
#include <stdio.h> int main()
# include<string.h> {
char* strcat1(char *s1,char *s2) char s1[20]="Hello";
{ char s2[10]="World";
strcat(s1,s2);
char *res;
return s1;
res=strcat1(s1,s2);
}
puts(res);
return 0;
}
O/P:HelloWorld
Function to read and display structure
#include <stdio.h> struct student read()
struct student { {
char name[50]; struct student s;
int age; printf("Enter name: ");
}; fgets(s.name,sizeof(s.name),stdin);
void display(struct student s); printf("Enter age: ");
struct student read(); scanf("%d", &s.age);
int main() { return s;
struct student s1; }
s1=read(); O/P:
display(s1); // passing struct as an argument Enter name: Robin D
return 0; Enter age: 23
}
void display(struct student s) { Displaying information
printf("\nDisplaying information\n"); Name: Robin D
printf("Name: %s", s.name);
printf("\nAge: %d", s.age); Age: 23
}
Function returning an structure
#include <stdio.h> int main()
struct student { {
char name[20]; struct student s1 = get_student_data();
int age; printf("Name: %s", s1.name);
float marks; printf("Age: %d\n", s1.age);
}; printf("Marks: %.1f\n", s1.marks);
struct student get_student_data() return 0;
{ }
struct student s; O/P:
printf("Enter name: "); Enter name: David J
fgets(s.name,sizeof(s.name),stdin); Enter age: 19
printf("Enter age: "); Enter marks: 87'
scanf("%d", &s.age); Name: David J
printf("Enter marks: "); Age: 19
scanf("%f", &s.marks); Marks: 87.0
return s;
}
Pointers: A B C

◦ Pointer is a variable containing address Value 100 20 30


as well as value at that address

◦ Syntax: Address 30 100 20


◦ Datatype *variableName;

◦ Ex. int *a;

◦ a-address
◦ *a-values at that address
Example on pointers
int main()
{
Int *a,b;
a=&b;
printf(“%d”,a); //will print 100
printf(“%d”,&a); // will print 30
printf(“%d”,*a); // will print 20
return 0;
}
You can go through…..
# include <stdio.h>
O/P:
int main()
-658081364
{ int b=10;
-658081376
int *a=&b;
10
int **c=&a;
printf("%d\n",a);
-658081376
printf("%d\n",&a);
-658081384
printf("%d\n\n",*a);
-658081364
printf("%d\n",c);
10
printf("%d\n",&c);
printf("%d\n",*c);
printf("%d\n",**c);
return 0;
}
Use of pointers
◦ Pointers in C are variables that store the memory address of another variable, which
allows for direct access to the data at that location.
◦ Passing large structures or arrays to a function: Pointers are useful when you need to
pass large structures or arrays to a function.
◦ Modifying a variable's value: Pointers allow a function to modify the value of a
variable.
◦ Iterating over elements in arrays or other data structures: Pointers are used to iterate
over elements in arrays or other data structures.
◦ Creating flexible and reusable code: Function pointers are used to create flexible and
reusable code.
◦ Dynamic memory allocation: The malloc() and free() functions are used to allocate
dynamic memory from the heap.
◦ Storing the address of another pointer: A pointer to a pointer, or double pointer, is used
to store the address of another pointer.
Example on call by reference
// C program to show use of printf("Before swap Values of var1 and var2 are: %d, %d\n",
var1, var2);
// call by Reference
swap(&var1, &var2);
#include <stdio.h>
printf("After swap Values of var1 and var2 are: %d, %d",
var1, var2);
void swap(int *v1, int *v2)
return 0;
{
int temp = *v1; }

*v1 = *v2;
O/P:
*v2 = temp;
Before swap Values of var1 and var2 are: 3, 2
}
After swap Values of var1 and var2 are: 2, 3
// Driver code
int main()
{
int var1 = 3, var2 = 2;
Recursion
◦ Recursion is the process of a function calling itself repeatedly till
the given condition is satisfied.
◦ A function that calls itself directly or indirectly is called a recursive
function and such kind of function calls are called recursive calls.
◦ In C, recursion is used to solve complex problems by breaking them down into simpler
sub-problems. We can solve large numbers of problems using recursion in C. For
example, factorial of a number, generating Fibonacci series, generating subsets, etc.
◦ Basic Structure of Recursive Functions
◦ type function_name (args) {
◦ // function statements
◦ // base condition
◦ // recursion case (recursive call)
◦}
Recursive function to find factorial of a number
#include <stdio.h> else if ( n == 1) //base case 2
int fact (int); {
int main() return 1;
{ }
int n,f; else
printf("Enter the number whose factorial {
you want to calculate?");
return n*fact(n-1); //recursive call
scanf("%d",&n);
}
f = fact(n); //function call
}
printf("factorial = %d",f);
}
O/P:
int fact(int n)
Enter the number whose factorial you want
{ to calculate?5
if (n==0) //base case 1 factorial = 120
{
return 1;
}
Recursive Function
◦ A recursive function performs the tasks by dividing it into
the subtasks. There is a termination condition defined in
the function which is satisfied by some specific subtask.
After this, the recursion stops and the final result is
returned from the function.

◦ The case at which the function doesn't recur is called


the base case whereas the instances where the
function keeps calling itself to perform a subtask, is
called the recursive case. All the recursive functions
can be written using this format.
Steps to write any recursive function:
if (test_for_base)
{
return some_value;
}
else if (test_for_another_base)
{
return some_another_value;
}
else
{
// Statements;
recursive call;
}
Sum of first n Natural Numbers Using Recursion
#include <stdio.h> int sum(int n) {
int sum(int n); if (n != 0)
int main() { return n + sum(n-1); //recursive call
int number, result; else
printf("Enter a positive integer: "); return n; //base case
scanf("%d", &number); }
result = sum(number);//fn call O/P:
printf("sum = %d", result); Enter a positive integer:3
return 0; sum = 6
}

You might also like