[go: up one dir, main page]

0% found this document useful (0 votes)
6 views40 pages

Chapter 10 Functions

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1/ 40

Chapter 10

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

int sum {int X, int Y}


{
int z: //local variable
z=x + y: //statement
return z; // Return Statement
Function Prototyping
• Function Prototyping (also known as Function Declaration) is the
declaration of a function before its actual definition in a C program.
• A function prototype provides the compiler with the necessary
information about the function's return type, name,and parameters.
• This allows the function to be called before its full definition, typically
in the main function or elsewhere
• Syntax:return_type function_name(parameter_type1,
parameter_type2, ...);
• Ex: float sum(float f1,float f2);
Types of Functions
• There are basically two types of functions.They are:
1) Library Functions
2) User Defined Functions

1) Library Functions:Library functions in C are predefined functions that are provided by


the C standard library.
These functions are designed to perform common operations, such as input/output,
memory management, string manipulation, mathematical calculations, and more.
The C standard library is included through header files (like <stdio.h>, <stdlib.h>,
<string.h>, etc.), and these functions can be used directly in your programs.
Using library functions saves time because they offer tested and optimized solutions for
common tasks, so you don't have to write the code for these operations from scratch.
To demonstrate the library functions
#include <stdio.h>
#include <math.h>
int main() {
double num1 = 16.0, num2 = 2.0;
// Calculate the square root of num1
double sqrt_result = sqrt(num1);
printf("Square root of %.2f is %.2f\n", num1, sqrt_result);
// Calculate num2 raised to the power of 3
double power_result = pow(num2, 3);
printf("%.2f raised to the power of 3 is %.2f\n", num2, power_result);
return 0;
}
//Output :Square root of 16.00 is 4.00
//2f" tells the printf method to print a floating point value (the double, x, in this case) with 2 decimal places.
User Defined Functions
• 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 th
• How to use User-Defined Functions in C?
• To use a user-defined function, we first have to understand the different parts
of its syntax. The user-defined function in C can be divided into three parts:
• Function Prototype
• Function Definition
• Function Call
1) C Function Prototype

• 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

• 1. Function with No Arguments and No Return Value


• Functions that have no arguments and no return values. Such functions can
either be used to display information or to perform
• any task on global variables.
• Syntax : void return type with no arguments
• void function_name()
•{
• // no return value
• return;
•}
EX:

Example:// C program to use function withno argument and no return values


#include <stdio.h>
void sum()
{
int x, y;
printf("Enter x and y\n");
scanf("%d %d", &x, &y);
printf("Sum of %d and %d is: %d", x, y, x + y);
}
// Driver code
int main()
{
// function call
sum();
return 0;
} //Output:Enter x and y:Sum of 4195522 and 0 is: 4195522
2. Function with No Arguments and With
Return Value

• 2. Function with No Arguments and With Return Value


• Functions that have no arguments but have some return values. Such
functions are used to perform specific operations and return their
value.
• Syntax:return_type function_name()
{
// program
return value;
}
EX:
Example:// C program to use function with no argument and with return values
#include <stdio.h>
int sum()
{
int x, y, s = 0;
printf("Enter x and y\n");
scanf("%d %d", &x, &y);
s = x + y;
return s;
}
// Driver code
int main()
{
// function call
printf("Sum of x and y is %d", sum());
return 0;
3. Function With Arguments and No Return Value

• 3. Function With Arguments and No Return Value


• Functions that have arguments but no return values. Such functions
are used to display or perform some operations on given arguments.
• Syntax:void function_name(type1 argument1, type2
argument2,...typeN argumentN)
{
// Program
return;
}
Example:
Example:// C program to use function with argument and no return values
#include <stdio.h>
void sum(int x, int y)
{
printf("Sum of %d and %d is: %d", x, y, x + y);
}// Driver code
int main()
{
int x, y;
printf("Enter x and y\n");
scanf("%d %d", &x, &y);
// function call
sum(x, y);
return 0;
}
4. Function With Arguments and With Return Value

• 4. Function With Arguments and With Return Value


Functions that have arguments and some return value. These functions are used to
perform specific operations on the given arguments and return their values to the
user.
Syntax
return_type function_name(type1 argument1, type2 argument2,...typeN
argumentN)
{
// program
return value;
}
// C program to use function withargument and with return values
#include <stdio.h>

int sum(int x, int y) { return x + y; }


// Driver code
int main()
{
int x, y;
printf("Enter x and y\n");
scanf("%d %d", &x, &y);
// function call
printf("Sum of %d and %d is: %d", x, y, sum(x, y));
return 0;
}
Output
Enter x and y
Sum of 0 and 0 is: 0
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.
• Syntax: Function_name(actual arguments list);
• Ex: main()
{
int x=10,y=20;
sum(x,y)//Function call
}
Passing parameters to the called
function
• The arguments present in the function call is called as actual arguments.There
are two ways in which actual arguments are passed to the called functions.
• 1) Call by value: In call by value method of parameter passing, the values of
actual parameters are copied to the function’s formal parameters.
• There are two copies of parameters stored in different memory locations.
• One is the original copy and the other is the function copy.
• Any changes made inside functions are not reflected in the actual parameters
of the caller.
ex: sum(X,Y);
sum(10,20);
• 2) Call by reference
• In call by reference method of parameter passing, the address of the
actual parameters is passed to the function as the formal parameters.
In C, we use pointers to achieve call-by-reference.
• Both the actual and formal parameters refer to the same locations.
• Any changes made inside the function are actually reflected in the
actual parameters of the caller.
• Ex: sum(&X,&Y);
• sum(x,&Y);
Types Of Arguments
• Two types of arguments:
• 1) Formal arguments
• 2)Actual arguments
• 1)Formal parameters, also known as formal arguments, are placeholders defined in the function
signature or declaration.
• They represent the data that the function expects to receive when called. Formal parameters
serve as variables within the function's scope and are used to perform operations on the input
data.
Syntax of Formal parameters:
// Here, 'name' is the formal parameter
function gfgFnc(name) {
// Function body
}
Actual parameters
• Actual parameters, also called actual arguments or arguments, are the
values or expressions provided to a function or method when it is called.
They correspond to the formal parameters in the function's definition and
supply the necessary input data for the function to execute. Actual
parameters can be constants, variables, expressions, or even function calls.
• Syntax of Actual parameters:function gfgFnc(name) {
// Function body
}
// Actual Parameter
gfgFnc("Geek");
Formal and Actual parameters
in C:
• #include <stdio.h>
// a and b are formal parameters
int sum_numbers(int a, int b) { return a + b; }
int main()
{
// 3 and 5 are actual parameters
int result = sum_numbers(3, 5);
printf("Sum: %d\n", result);
return 0;
}
Variable length argument list
• Variable length argument is a feature that allows a function to receive
any number of arguments. There are situations where we want a
function to handle variable number of arguments according to
requirement. 1) Sum of given numbers. 2) Minimum of given
numbers. and many more. Variable number of arguments are
represented by three dotes (…)
• EX: printf(“Programming in c”); // 1 argument
• printf(“Max number is %d”,max); // 2 argument
• printf(“Date is %d-%d-%d”,03,02,2022); // 4 arguments
Syntax:
• Return_type function_name(int num,….);

• 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

You might also like