Chapter 10 Functions
Chapter 10 Functions
Chapter 10 Functions
Functions
Functions
• A function in C is a set of statements that when called perform some
specific tasks. It is the basic building block of a C program that
provides modularity and code reusability. (Modularity is the practice
of breaking down a system into smaller, independent units, while
code reusability is the practice of designing code to be used in
multiple contexts )The programming statements of a function are
enclosed within { } braces, having certain meanings and performing
certain operations.
Need for functions
Functions are an essential part of C programming because they he
structure, readability, and maintainability of code:
Reusability: Functions allow you to write code once and use it mu
which reduces redundancy and saves time.
Modularity: Functions break down a program into smaller, more m
making it easier to understand and maintain.
Abstraction: Functions provide abstraction functionality.
Flexibility and optimization: User-defined functions can be tailo
requirements using parameters and return types.
Debugging: Assigning different tasks to each function makes deb
What is a Function
• A Function is a named, independent section of C code that performs a specific task. Generally.
function is designed to perform smaller tasks. C provides a variety of library functions such as
scanf(),printf(), getchar(), strlen(), strcat(), etc., are not C language statements but are library
functions provided by compiler. Also, 'C' allows to define our own functions (user-defined
functions) the following g details present basic concepts about a function
• A function is named: Each function has a unique name. By using that name in another part of
program, we can execute the statements contained in the function.this is known as calling the
function. A function can be called from within another unction.
• A function is independent: A function can perform its task without interferences from or
interfering with other parts of the program.
• A function can return a value to the calling function
• A function consists of two sets of variables:
• Formal Parameters: are the variables in which each variable receives a value from the calling
function.
• Local Variables: are a set of variables declared within the function.
Function Definition
• The definition of a function consists of two parts. They are 1)Function
header ,2)Body of function
• 1) Function Header: Contains the return type, the function name, and the
parameters (if any).
• Syntax
return_type function_name(parameter_list)
{
// Function body (code to be executed)
}
Cont…..
• return_type: The data type of the value the function will return (e.g.,
int, void, float).
• function_name: The name of the function.
• parameter_list: The list of parameters (optional), enclosed in
parentheses, and separated by commas (e.g., int a, int b).
• function body: The block of code inside curly braces {} that defines
the actions the function will perform.
• 2) Body of function may contain local variables,statements,or return
statement.The actual task will be performed in the body of the
function.
• Ex: Data type of return value Function name Formal Parameters
• C Function Prototype
• A function prototype is also known as a function declaration which
specifies the function’s name, function parameters,and return type.
• The function prototype does not contain the body of the function. It
is basically used to inform the compiler about the existence of the
user-defined function which can be used in the later part of the
program.
Syntax:return_type function_name (type1 arg1, type2 arg2, ... typeN
argN);
2) C Function Definition
• C Function Definition
• Once the function has been called, the function definition contains the
actual statements that will be executed.
• All the statements of the function definition are enclosed within { }
braces.
• Syntax:return_type function_name (type1 arg1, type2 arg2 .... typeN
argN) {
// actual statements to be executed
// return value if any
}
• Note: If the function call is present after the function definition, we can
skip the function prototype part and directly define the function.
3) C Function Call
• C Function Call
• In order to transfer control to a user-defined function, we need to call
it. Functions are called using their names followed by round brackets.
Their arguments are passed inside the brackets.
• Syntax
• function_name(arg1, arg2, ... argN);
Example of User-Defined Function
The following C program illustrates how to use user-defined functions in our program.
// C Program to illustrate the use of user-defined function
#include <stdio.h>
// Function prototype
int sum(int, int);
// Function definition
int sum(int x, int y)
{
int sum;
sum = x + y;
return x + y;
}
// Driver code
int main()
{
int x = 10, y = 11;
// Function call
int result = sum(x, y);
printf("Sum of %d and %d = %d ", x, y, result);
return 0;
//
}
Categories Of Functions:
• A user-defined function is one that is defined by the user when writing any program,
as we do not have library functions that have predefined definitions. To meet the
specific requirements of the user, the user has to develop his or her own functions.
Such functions must be defined properly by the user. There is no such kind of
requirement to add any particular library to the program.
• Different Types of User-defined Functions in C
• There are four types of user-defined functions divided on the basis of arguments they
accept and the value they return:
• Function with no arguments and no return value
• Function with no arguments and a return value
• Function with arguments and no return value
• Function with arguments and with return value
1. Function with No Arguments and No Return Value
• A macro in C is a section of code that is defined using the #define keyword and replaced by its value
or expression when the compiler encounters it in the code.
Macros used in variable length arguments: to use variable length arguments functionality, we need
to make use of stdarg.h header file which provides the functions and macros to implement the
functionality of variable arguments. To implement var-args in our program we will use following
macros definition
va_list: This type is used to declare a variable that will store the list of arguments.
va_start: This macro initializes the va_list variable to start processing the arguments, and it takes the
last known fixed argument (count in this case).
va_arg: This macro retrieves the next argument from the list, given the type of argument. In this case,
it retrieves an int.
va_end: This macro cleans up after you are done with the argument list.
Steps to implement variable length
arguments in a function
• Step1:Include stdarg.h header file to access variable length argument.
• Step 2: Define a function to accept variable length arguments.
• void myfunction(int num, ...);
• Step 3: Inside function create a va list type variable.
• va_list list;
• Step 4: Initialize list variable using va_start macro, va_start macro accepts two parameters.First va list
type variable and number of arguments in the list.
• va_start(list, num);
• Step 5: Run a loop from 1 to number of arguments. Inside the loop, use va arg to get next argument
passed as variable length arguments. va_arg accepts two parameter. First va list type variable from where
to fetch values. Second, type (data type) of value we want to retrieve.
• va_arg(list, int);
• Step 6: Finally release memory occupied by va_list using
• va_end. va_end(list);
ex
• #include <stdio.h>
• #include <stdarg.h>
// Function to calculate the sum of variable number of integers
int sum(int count, ...) {
int total = 0;
// Initialize the va_list variable to access the variable arguments
va_list args;
va_start(args, count);
// Loop through each argument and add it to the total
for (int i = 0; i < count; i++) {
total += va_arg(args, int); // Get the next argument as an integer
} // Clean up the va_list
va_end(args);
return total;
}
int main() {
printf("Sum of 3, 5, 7: %d\n", sum(3, 3, 5, 7));
Nesting Of Functions
• In C, nesting of functions refers to the practice of calling one function from within another function. This is a
common feature in C programming, allowing you to organize code in smaller, modular, and reusable units.
However, defining one function inside another is not allowed in C, meaning that the definition of a function
cannot be nested within another function. But you can definitely call one function from inside another.
• Ex:
main()
{
function A();
}
function A();
{
function B();
}
Function B();
Passing Arrays to functions
• Can be done in 2 ways:
• Passing individual elements of an array.
• Passing the entire array to a function.
• 1. Passing Individual Elements of an Array to a Function
• When you pass individual elements of an array to a function, you're
essentially passing a single value from the array (which is a value of a
specific type, like int, float, etc.).
• You can access the elements of the array in the function using the
index, and the function will work with the value of that particular
element.
Passing Individual Elements of an Array to a
Function
• #include <stdio.h>
// Function to print a specific element of the array
void printElement(int element) {
printf("Element: %d\n", element);
}
int main() {
int arr[] = {10, 20, 30, 40, 50};
// Passing individual elements of the array to the function
printElement(arr[0]); // Passing the first element
printElement(arr[2]); // Passing the third element
printElement(arr[4]); // Passing the fifth element
return 0;
} //output
Element: 10
Element: 30
2. Passing the Entire Array to a
Function
When you pass an entire array to a function, you're passing the base address (pointer) of the
array.
In C, arrays are always passed by reference, meaning the function gets access to the original array
in memory (it does not get a copy of the array).However, the size of the array is not passed along
with it, so you need to pass the size of the array explicitly to ensure the function can work with the
array properly.
Example:
#include <stdio.h>// Function to print all elements of an array
void printArray(int arr[], int size) {
for (int i = 0; i < size; i++) {
printf("Element %d: %d\n", i, arr[i]);}}
int main() {
int arr[] = {10, 20, 30, 40, 50};
int size = sizeof(arr) / sizeof(arr[0]); // Calculate size of the array
// Passing the entire array to the function
printArray(arr, size);
return 0;
}
Advantages of User defined
Functions
• . Code Reusability
• One of the biggest advantages of user-defined functions is reusability. Once
a function is written and tested, it can be used multiple times throughout the
program or in different programs.
• Easier Debugging and Maintenance
• Isolating errors becomes easier when your program is divided into functions.
If something goes wrong, you can focus on the specific function where the
problem likely exists, rather than sifting through the entire program.
• Code reusability
• Easy to debug and maintain