0% found this document useful (0 votes)
5 views20 pages

User-Defined Functions in C Programming

The document provides an overview of user-defined functions in C programming, highlighting their importance for code reusability, modularity, error detection, and flexibility. It explains the elements of user-defined functions, including declaration, definition, and calling, along with various categories based on arguments and return values. Additionally, it discusses structures in C, their declaration, initialization, and access methods, along with sample programs demonstrating the use of functions and structures.

Uploaded by

kuldeepkandale
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views20 pages

User-Defined Functions in C Programming

The document provides an overview of user-defined functions in C programming, highlighting their importance for code reusability, modularity, error detection, and flexibility. It explains the elements of user-defined functions, including declaration, definition, and calling, along with various categories based on arguments and return values. Additionally, it discusses structures in C, their declaration, initialization, and access methods, along with sample programs demonstrating the use of functions and structures.

Uploaded by

kuldeepkandale
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Unit 05: User-Defined Function

User-Defined Function:

 A user-defined function is a type of function in C language that is defined by


the user himself to perform some specific task.
 User-defined functions are different from built-in functions as their working is
specified by the user and no header file is required for their usage.

Need for User-defined Functions:


1. Code reusability

 Suppose we need to perform a certain task at several places in our program.


 Instead of writing the same code again and again at different places in the
program, if we make a function for that code, we can simply call the function from
different places. This will add only one line to the program for each function call
as opposed to adding the whole block of code each time. Hence by re-using the
code we have reduced the size of our program.

2. Modularity

 Modularity gives a structured approach to programming


 Instead of writing the whole program as a simple block of code, we divide it into
small tasks to make the approach more logical.

3. Error Detection

 Modular approach makes it very easy to identify errors in a program.


 Suppose we didn't use functions and simply wrote the whole program as one big
code in main. Now if we get an error, we need to debug our full program, just to
identify where the error lies.
 Instead, if we divided our code into small functions, each doing a particular task,
the nature of the error will immediately lead us to the function that caused the
error.

4. Flexibility.
 Suppose we need to perform a task at n different places in our program, instead
of making a function for this, we have simply written our code at all those n
places, now if that task has to be modified in the future, we will have to go and
make the change at all the n places where we wrote this code.
 Instead, if we used a function, then simply changing the code inside the function
will reflect the new change in the entire program. Hence using functions makes
our programs more flexible.
A Multi-Function Program:
 A function is a self-contained block of code that performs a particular
task.
 Once a function has been designed and packed, it can be treated as a
‘black box’ that takes some data from the main program and returns a
value.
 Thus a program, which has been written using a number of functions, is
treated as a multi-function program.
 Every C program can be designed using a collection of these black boxes
known as Functions.
Elements of User defined Functions:

1. Function declaration: This includes the function's name, return type, and
parameters.
Syntax-
Return_type function_name (parameter_type parameter_ name, parameter_type
parameter_name);

2. Function definition: also known as function implementations .This includes the


i) Function's type
ii) Function name
iii) List of parameter
iv) Local variable declarations
v) Function statements
vi) Return statements
All six elements are grouped together into two parts Function headers & Function
Body.
3. Function call: This is when the function is called to be executed by the compiler.
Syntax- function_name(arg1, arg2, ... argN);

Sample Program -
Return Values and their Types:
A function may or may not send back any value to the calling function. If it does, it is
done through the return statement.
While it is possible to pass to the called function any number of values, (the called
function can only return one value per call, at the most.)

The return statement can take one of the following forms:


return; or return (expression);
Category of Functions:
Depending upon the arguments are present or not & whether the the value is returned
or not following are the Category of Functions
1. Function with no arguments and no return value
2. Function with argument and with no return value
3. Function with arguments and with one return value
4. Function with no arguments and with return value
5. Function that return multiple value

1. Function with no arguments and no return value:

Syntax:

void function_name()
{
// no return value
return;
}

Program-

Explanation
In the above program, function sum does not take any arguments and has no return
values. It takes x and y as inputs from the user and prints them inside the void
function.
2. Function with No Arguments and With Return Value
Syntax-

return_type function_name()
{
// program
return value;
}

Explanation
In the above program, function sum does not take any arguments and has a
return value as an integer type. It takes x and y as inputs from the user and
returns them.
3. Function With Arguments and No Return Value:
Syntax:
void function_name(type1 argument1, type2 argument2,...typeN
argumentN)
{
// Program
return;
}
Explanation
In the above program, function sum does take x and y as arguments and has
no return value. The main function takes x and y as inputs from the user and
calls the sum function to perform the print operation on the given arguments.
4. Function With Arguments and With Return Value:
return_type function_name(type1 argument1, type2 argument2,...typeN
argumentN)
{
// program
return value;
}
Explanation
In the above program, function sum takes two arguments as x and y,
and has a return value as an integer type. The main function takes
input x and y from the user and calls the sum function to perform a
specific operation on the given arguments and returns the value.

Nesting of Functions:
In some applications, we have seen that some functions are declared inside
another function. This is sometimes known as nested function, but
actually this is not the nested function. This is called the lexical scoping.
Lexical scoping is not valid in C because the compiler is unable to reach correct
memory location of inner function.

Nested function definitions cannot access local variables of surrounding blocks.


They can access only global variables. In C there are two nested scopes the
local and the global. So nested function has some limited use. If we want to
create nested function like below, it will generate error.
But an extension of GNU C compiler allows declaration of the nested function.
For this we have to add auto keyword before the declaration of nested function.

Sample Programs On Functions


1. Find the area of circle using function

Algorithm:

1. Define a constant PI with the value of 3.142.


2. Create a function find Area.
3. Within the find Area function, multiply PI by the square of the
radius r and return the result.
2. Write a c program to add two no’s using user defined
functions
Algorithm:
1. Start
2. Create a function sum.
3. Declaration of type of data
4. Within the sum function add a and b & return the result
Structure
 A structure is a collection of data of different data types
 The main difference between a structure and an array is that in an array, all
the data has to be of the same data type.
 Many a times, we need to combine several attributes of an object, together
into a data structures. These attributes may not be of the same data type.
 Eg: Let us look at the attributes of a student

Student

1. Name --- character array


2. Age --- integer
3. Percentage ---- float
As seen above, this is a collection of data of different data types. Here we use a
structure.

Structure Declaration:

We have to declare structure in C before using it in our program. In structure


declaration, we specify its member variables along with their datatype. We can
use the struct keyword to declare the structure in C using the following syntax:

Syntax:
struct structure_name {
data_type member_name1;
data_type member_name1;
....
....
} variable 1,variable 2;

Ex. struct student


{
char name[100];
int age;
float percentage;
}struct student s1,s2,s3;
Initialization of structure:
Structure we can initialize structure members in 3 ways which are as follows:
1. Using Assignment Operator.
2. Using Initializer List.
3. Using Designated Initializer List.

1. Initialization using Assignment Operator


struct structure_name str;
str.member1 = value1;
str.member2 = value2;
str.member3 = value3;

2. Initialization using Initializer List


struct structure_name str = { value1, value2, value3 };

3. Initialization using Designated Initializer List


Designated Initialization allows structure members to be initialized
in any order. This feature has been added in the C99 standard.
struct structure_name str = { .member1 = value1, .member2 = value2,
.member3 = value3 };

Access Structure Members:

We can access structure members by using the ( . ) dot operator.


Syntax
1. First Create structure variable-
struct structure name member1;
[Link] assign value to member1-
[Link]=value;
1. Write a program to represent 5 student data using structure. (Consider fields as
roll no., name and percentage

#include <stdio.h>
struct student
{
char Name[50];
int roll;
float marks;
} s[5];

int main()
{
int i;
printf("Enter information of students:\n");

// storing information
for (i = 0; i < 5; ++i)
{

s[i].roll = i + 1;
printf("\nFor roll number%d:\n", s[i].roll);
printf("Enter first name: ");
scanf("%s", &s[i].Name);
printf("Enter marks: ");
scanf("%f", &s[i].marks);
}
printf("Displaying Information:\n");

// displaying information
for (i = 0; i < 5; ++i)
{
printf("\nRoll number: %d\n", i + 1);
printf("First name: ");
puts(s[i].Name);
printf("Marks: %.f", s[i].marks);
printf("\n");
}
return 0;
}
O/P-
Enter information of students:
For roll number1:
Enter first name: Tushar
Enter marks: 90

For roll number2:


Enter first name: RAM
Enter marks: 80

For roll number3:


Enter first name: SHAM
Enter marks: 70

For roll number4:


Enter first name: KIRAN
Enter marks: 60

For roll number5:


Enter first name: RAHUL
Enter marks: 50

Displaying Information:
Roll number: 1
First name: Tushar
Marks: 90

Roll number: 2
First name: RAM
Marks: 80

Roll number: 3
First name: SHAM
Marks: 70

Roll number: 4
First name: KIRAN
Marks: 60

Roll number: 5
First name: RAHUL
Marks: 50

=== Code Execution Successful ===


[Link] C program to read and display the Title, Author and Price of 03 book using arrays
of structure

#include <stdio.h>
struct book
{
int Book;
char Title[50];
char Author[50];
float Price;
} s[3];

int main()
{
int i;
printf("Enter information of students:\n");

// storing information
for (i = 0; i < 3; ++i)
{
s[i].Book = i+1;
printf("\nFor Book%d:\n", s[i].Book);
printf("Enter Title: ");
scanf("%s", &s[i].Title);
printf("Enter Author: ");
scanf("%s", &s[i].Author);
printf("Enter Price: ");
scanf("%f", &s[i].Price);
}

printf("Displaying Information:\n\n");

// displaying information
for (i = 0; i < 3; ++i)
{
printf("\nBook: %d\n", i + 1);
printf("Title : ");
puts(s[i].Title);
printf("Author : ");
puts(s[i].Author);
printf("Price : ");
printf("%f", s[i].Price);
printf("\n");
}
return 0;
}
O/P-
Enter information of students:

For Book1:
Enter Title: FPL
Enter Author: RAM
Enter Price: 500

For Book2:
Enter Title: CHEM
Enter Author: SHAM
Enter Price: 1000

For Book3:
Enter Title: BXE
Enter Author: AAP
Enter Price: 1500
Displaying Information:

Book: 1
Title : FPL
Author : RAM
Price : Price: 500.000000

Book: 2
Title : CHEM
Author : SHAM
Price : Price: 1000.000000

Book: 3
Title : BXE
Author : AAP
Price : Price: 1500.000000

=== Code Execution Successful ===

Sample program on multifunction

#include <stdio.h>
void HappyDiwali()
{
printf("HAPPY DIWALI \n");
}
void HappyNewYear()
{
printf("HAPPY NEW YEAR \n");
}
void HappyFriendshipDay()
{
printf("HAPPY Friendship Day \n");
}

int main() {

HappyDiwali();
HappyNewYear();
HappyFriendshipDay();

return 0;
}
Recursive functions:
Recursion is a technique where a function calls itself, repeatedly, until a base-case is
satisfied.

It is a very powerful technique used in programming. It breaks down a big task into
smaller tasks to be executed repeatedly, the simplest example is to calculate 10^5

105 =10*104 Recursive case


104 =10*103 Recursive case
3
10 =10*102 Recursive case
102 =10*101 Recursive case
1
10 =10*100 Recursive case
100 =1 Base Case
In general –
10^n=10*10^(n-1)

So here n=0 no becomes our base-case, and for all other cases we simply continue in
a recursive manner with the principle that 10^n=10x 10^(n-1).

Syntax:
type function_name (args) {
// function statements
// base condition
// recursion case (recursive call)
}

Algorithm to calculate result = x y

1. Define "x", "y", "result"

2. Accept "x" and "y" from the user

3. Call the function power(x, y), pass "x", "Y”

4. This function will return x* power(x, y-1)

5. This means it will call itself recursively

6. The break case will be when y0, in that case it will return just 1.
1. Sample program to find power of given no using recursion

2. Find the factorial of no by using recursion


3. Find the sum of natural no using recursion

4. Find GCD of two no’s using recursion

You might also like