0% found this document useful (0 votes)
47 views10 pages

FPL unit 5

Uploaded by

sanskarkale24
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)
47 views10 pages

FPL unit 5

Uploaded by

sanskarkale24
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
You are on page 1/ 10

Unit 5

User Defined Functions

5.1 User Defined Functions: Need for User-defined Functions,


5.2 A Multi-Function Program, Elements of User defined Functions,
5.3 Definition of Functions, Return Values and their Types, Function Calls, Function
Declaration,
5.4 Category of Functions: No Arguments and no Return Values, Arguments but No Return
Values, Arguments with Return values, No Arguments but Returns a Value, Functions that
Return Multiple Values
5.5Nesting of Functions, Recursion
5.6 Structures: What is a Structure? Structure Type Declarations
5.7 Structure Declarations, Referencing Structure Members
5.8 Referencing Whole Structures, Initialization of Structures.

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


himself to perform some specific task. It provides code reusability and modularity to our
program. 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.
5.1 User Defined Functions: Need for User-defined Functions
Advantages of User-Defined Functions
The advantages of using functions in the program are as follows:
 One can avoid duplication of code in the programs by using functions. Code can be
written more quickly and be more readable as a result.
 Code can be divided and conquered using functions. This process is known as Divide
and Conquer. It is difficult to write large amounts of code within the main function, as
well as testing and debugging. Our one task can be divided into several smaller sub-
tasks by using functions, thus reducing the overall complexity.
 For example, when using pow, sqrt, etc. in C without knowing how it is implemented,
one can hide implementation details with functions.
 With little to no modifications, functions developed in one program can be used in
another, reducing the development time.

Benefits of User-Defined Functions

There are several benefits to using user-defined functions in C programming, including:

Reusability: One of the main benefits of user-defined functions is that they can be reused in
different parts of a program. Instead of writing the same code multiple times, you can define
a function and call it whenever you need to perform a specific task. It makes the code more
efficient and easier to maintain.

Modularity: User-defined functions promote modularity in a program by breaking it down


into smaller, manageable parts. Each function can perform a specific task, and the program as
a whole can be built by combining these functions. It makes it easier to understand the code
and debug any issues that may arise.

Simplified code: User-defined functions can simplify the code by abstracting away complex
logic into a single function. It makes the code easier to read and understand, reducing the
likelihood of errors and improving the overall quality of the program.

Better testing: By breaking down a program into smaller functions, it becomes easier to test
each function individually. It makes it easier to identify and isolate issues within the code,
making it easier to fix any bugs and improve the overall quality of the program.

Improved collaboration: User-defined functions can improve collaboration by making it


easier for multiple developers to work on different parts of a program simultaneously. By
breaking the program down into smaller functions, each developer can focus on their specific
task and work independently, making it easier to combine their work later.

5.2 A Multi-Function Program, Elements of User defined Functions


1.Function declaration.
2.Function definition.
3.Function call.
1. 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 Declaration
2. Definition of Functions
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).
A C function is generally defined and declared in a single step because the function
definition always starts with the function declaration so we do not need to declare it
explicitly. 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
}

3. Function call

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.
Working of function in C

5.4 Nesting of Function.

Some programmer thinks that defining a function inside an another function is known as
“nested function”.

Some programmer thinks that defining a function inside an another function is known as
“nested function”. #include<stdio.h>
int my_fun() {
printf("check_fun function");
printf("\n");
}
int main() {
my_fun();
printf("Main Function\n");

printf("Done");
}

Recursion

Recursion is the technique of making a function call itself. This technique provides a way to
break complicated problems down into simple problems which are easier to solve.

Recursion is the process which comes into existence when a function calls a copy of itself to
work on a smaller problem. Any function which calls itself is called recursive function, and
such function calls are called recursive calls. Recursion involves several numbers of recursive
calls. However, it is important to impose a termination condition of recursion. Recursion code
is shorter than iterative code however it is difficult to understand.

Recursion cannot be applied to all the problem, but it is more useful for the tasks that can be
defined in terms of similar subtasks. For Example, recursion may be applied to sorting,
searching, and traversal problems.
#include <stdio.h>
int fact (int);
int main()
{
int n,f;
printf("Enter the number whose factorial you want to calculate?");
scanf("%d",&n);
f = fact(n);
printf("factorial = %d",f);
}
int fact(int n)
{
if (n==0)
{
return 0;
}
else if ( n == 1)
{
return 1;
}
else
{
return n*fact(n-1);
}
}

Syntax:

void recurse()
{
... .. ...
recurse();
... .. ...
}

int main(){
... .. ...
recurse();
... .. ...
}

5.5 Structures: What is a Structure? Structure Type Declarations


The structure in C is a user-defined data type that can be used to group items of possibly
different types into a single type. The struct keyword is used to define the structure in the
C programming language. The items in the structure are called its member and they can be
of any valid data type. Additionally, the values of a structure are stored in contiguous
memory locations.
The difference between an array and a structure is that an array is a homogenous collection
of similar types, whereas a structure can have elements of different types stored adjacently
and identified by a name.
C 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;
....
....
};
The above syntax is also called a structure template or structure prototype and no memory
is allocated to the structure in the declaration.

Ex:
struct book
{
char title[50];
char author[50];
double price; int pages;
};

C Structure Definition
To use structure in our program, we have to define its instance. We can do that by creating
variables of the structure type. We can define structure variables using two methods:

1.Structure Variable Declaration with Structure Template


struct structure_name {
data_type member_name1;
data_type member_name1;
....
....
}variable1, varaible2, ...;
2. Structure Variable Declaration after Structure Template
// structure declared beforehand
struct structure_name variable1, variable2, .......;

Structure Variable Declaration


To access and manipulate the members of the structure, you need to declare its variable first.
To declare a structure variable, write the structure name along with the "struct" keyword
followed by the name of the structure variable. This structure variable will be used to access
and manipulate the structure members.
Example
The following statement demonstrates how to declare (create) a structure variable
struct book book1;
Initialization of Structures.
Structure Initialization
The initialization of a struct variable is done by placing the value of each element inside
curly brackets.
We can initialize structure members in 3 ways which are as follows:
1. Using Assignment Operator.
1. Using Initializer List.
1. 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 };
In this type of initialization, the values are assigned in sequential order as they are declared
in the structure template.

Example
The following statement demonstrates the initialization of structure
struct book book1 = {"Learn C", "Dennis Ritchie", 675.50, 325};

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

Accessing the Structure Members


To access the members of a structure, first, you need to declare a structure variable and then
use the dot (.) operator along with the structure variable.
Syntax
structure_name.member1;
strcuture_name.member2;

Example 1
The four elements of the struct variable book1 are accessed with the dot (.) operator.
Hence, "book1.title" refers to the title element, "book1.author" is the author name,
"book1.price" is the price, "book1.pages" is the fourth element (number of pages).
Take a look at the following example −
Open Compiler
#include <stdio.h>
struct book{
char title[10];
char author[20];
double price;
int pages;
};

int main(){
struct book book1 = {"Learn C", "Dennis Ritchie", 675.50, 325};
printf("Title: %s \n", book1.title);
printf("Author: %s \n", book1.author);
printf("Price: %lf\n", book1.price);
printf("Pages: %d \n", book1.pages);
printf("Size of book struct: %d", sizeof(struct book));
return 0;
}
Output
Run the code and check its output −
Title: Learn C
Author: Dennis Ritchie
Price: 675.500000
Pages: 325
Size of book struct: 48

Simple structure program 2:


#include <stdio.h>
struct Car {
char brand[50];
char model[50];
int year;
};
int main() {
struct Car car1 = {"BMW", "X5", 1999};
struct Car car2 = {"Ford", "Mustang", 1969};
struct Car car3 = {"Toyota", "Corolla", 2011};
printf("%s %s %d\n", car1.brand, car1.model, car1.year);
printf("%s %s %d\n", car2.brand, car2.model, car2.year);
printf("%s %s %d\n", car3.brand, car3.model, car3.year);
return 0;
}

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy