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

Function Notes

This document covers Unit III of a CSE course, focusing on functions and pointers in C programming. It explains modular programming, advantages and disadvantages of using functions, function declaration, definition, and calling, as well as parameter passing methods. Key concepts such as recursion, pointers, and built-in functions are also discussed, providing a comprehensive overview of how to effectively utilize functions in C programming.

Uploaded by

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

Function Notes

This document covers Unit III of a CSE course, focusing on functions and pointers in C programming. It explains modular programming, advantages and disadvantages of using functions, function declaration, definition, and calling, as well as parameter passing methods. Key concepts such as recursion, pointers, and built-in functions are also discussed, providing a comprehensive overview of how to effectively utilize functions in C programming.

Uploaded by

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

KIOT––Department

KIOT DepartmentofofCSE
CSE

UNIT-III FUNCTIONS AND POINTERS


UNIT III FUNCTIONS AND POINTERS 9
Modular programming - Function prototype, function definition, function call, Built-in
functions (string functions, math functions) – Recursion, Binary Search using recursive
functions –Pointers –Pointer operators – Pointer arithmetic – Arrays and pointers – Array of
pointers – Parameter Passing: Pass by value, Pass by reference.

Modular Programming

Modular programming is a software design technique that emphasizes separating the


functionality of a program into independent, interchangeable modules, such that each
contains everything necessary to execute only one aspect of the desired functionality.

 Goes hand-in-hand with stepwise refinement and incremental development


 Makes the code easier to develop, test and debug
 Promotes reusability of codes
 Write a separate module to perform the computation step.
 If the computation is complex, it should be further split into smaller steps and
each step performed by a module.
 A ‘module’  Should be well-defined, should to one task.
 A well-defined module
 Has a good name (for readability and documentation)
 Has a clear interface (what parameters does it take?)
 May pass back to its caller no result or a single result (what value does it
return?)

In general, a problem is solved in 3 steps: input computationoutput.

R. Sathya Priya AP/CSE -KIOT 1|Page


KIOT – Department of CSE

Advantages of Modular Programming


 It is easy to understand the program.
 Debugging and maintenance becomes easy.
 Saves programmers or user’s time.
 Reuse the code where ever necessary.
 Modules are often reusable – libraries.
 Development can be divided: Allows development to be divided by splitting down a
program into smaller programs in order to execute a variety of tasks.
 Readable programs: Helps develop programs that are much easier to read since they
can be enabled as user-defined functions.
 Improves manageability: Having a program broken into smaller sub-programs
allows for easier management.
 Collaboration: With Modular Programming, programmers can collaborate and work
on the same application.

Disadvantages of modular programming


 There is a need for extra time and budget for a product in modular programming.
 It is a challenging task to combine all the modules.
 Careful documentation is required so that other program modules are not affected.
 Some modules may partly repeat the task performed by other modules. Hence,
Modular programs need more memory space and extra time for execution.
 Integrating various modules into a single program may not be a task because different
people working on the design of different modules may not have the same style.
 It reduces the program's efficiency because testing and debugging are time-
consuming, where each function contains a thousand lines of code.

FUNCTIONS
 C enables programmers to break up a program into segments commonly known as
Function, each of which can be written more or less independently of the others.
 Each function in the program is supposed to perform a well-defined task.
 Every C program has at least one function, which is main(), and all the most
important programs can define additional functions.
 The function contains the set of programming statements enclosed by {}.
 A function can be called multiple times to provide reusability and modularity to the C
program.
 The function is also known as procedure or subroutine in other programming
languages.

R. Sathya Priya AP/CSE -KIOT 2|Page


KIOT – Department of CSE

Advantage of functions in C

 By using functions, we can avoid rewriting same logic/code again and again in a
program.
 We can call C functions any number of times in a program and from any place in a
program.
 We can track a large C program easily when it is divided into multiple functions.
 Reusability is the main achievement of C functions.
 However, Function calling is always above head in a C program.

Why are functions needed?

 Top-down approach  Dividing a program into separate well-defined functions


facilitates each function to be written and tested separately.
 Understanding, coding, and testing multiple separate functions are far easier than
doing it for one big function.
 Developing a large program without utilizing any functions besides the main()
function leads to an extensive main() function with countless lines. This makes
program maintenance quite challenging, especially in macro-computers where
memory space is limited.
 All the libraries in C contain a set of functions that the programmers are free to use in
their programs. Function have been pre-written and pre-tested
 When a big program is broken into comparatively smaller functions, then different
programmers working on that project can divide the workload by writing different
functions.
 Like C Libraries, Programmers can also write their functions and use them at different
points in the main program or in any other program that needs its functionalities.

While using functions we will be using the following terminologies:

1. Function Declaration / Function Prototype


2. Function Definition
3. Function Call
4. Return Statement
5. Argument, Parameter, Actual Argument, Formal Argument
6. Passing Parameters to Function
5.1 Call by Value
5.2 Call by Reference

R. Sathya Priya AP/CSE -KIOT 3|Page


KIOT – Department of CSE

FUNCTION DECLARATION / FUNCTION PROTOTYPE

 Declare the properties of the function to the complier.


 Placing the function declaration statement prior to its use enables the complier to
make a check on the arguments used while calling that function.
 General Format for declaring a function that accepts some arguments and returns
some value as a result can be given as:

return_data_type function_name(data_type variables1, data_type variable2, ……);

The parameter name is not mandatory while declaring functions. We can also declare the
function without using the name of the data variables.
 It is not necessary to initially declare a function.

Note:
 function_name  Naming the function follows the same rules as naming variables and
Every function must have different name.
 return_data_type  data_type of the value that will be returned to the calling function
as a result of the processing performed by the called function.
 data_type variables1, data_type variable2  list of variables of specified data types,
called function accepts to perform its task.
Valid function declarations:
Function Declaration Use of the function
Return data type Converts a character to upper case. The function
receives a character as an argument, converts it into
char convert_to_uppercase (char ch); uppercase and returns the converted character back
to the calling function.
Function name Calculates average of two integer numbers a and b
received as arguments. The function returns a
float avg (int a, int b); floating point value.

R. Sathya Priya AP/CSE -KIOT 4|Page


KIOT – Department of CSE

int find_largest (int a, int b, int c); Finds the largest of three numbers— a, b, and c
received as arguments. An integer value which
Data type of variable is the largest of the three numbers is returned to the
calling function.
double multiply(float a, float b); Multiplies two floating point numbers a and b that
are received as arguments and returns a double
Variable1 value.
Swaps or interchanges the value of integer variables
a and b received as arguments. The function
void swap(int a, int b);
returns no value, therefore the return type is
void.
The function is used to print information on screen.
The function neither accepts any value as
void print(void); argument nor returns any value . Therfore, the
return type is void and the argument list contains
void data type.
Things to remember about function declaration:
1. After the declaration of every function, there should be a semicolon.
2. The Function declaration is global, declared function can be called from any point in
the program.
3. Use of argument names in the function declaration statement is optional.
Example: int func(int, char, float);
Or
int func (int num, char ch, float fnum);

4. A Function cannot be declared be within the body of another function.


5. A Function having void as its return type cannot return any value.
6. A Function having void as its parameter list cannot accept any value. Function
declaration does not accept any input /arguments from the calling function.
Example: void print(void);
Or
void print();
7. If the function declaration does not specify any return type, then by default, the
function returns an integer value. Example: sum(int a, int b);
8. Some compilers make it compulsory to declare the function before its usage while
other compilers make it optional.
FUNCTION DEFINITION
 When a function is defined. space is allocated for that function in the memory.
 A function definition comprises two parts:
1. Function Header

return_type function_name (para1_datatype para1_name, para2_datatype para2_name)


{
// body of the function
Statement1;
………….. Function Body
Statement2;
return variable;

R. Sathya Priya AP/CSE -KIOT 5|Page


KIOT – Department of CSE

}  The number of arguments and the order of arguments in the


Function Header
2. Function
function header must beBody
same as that given in the function
declaration statement.
 The parameter list in the function definition as well as function declaration must
match.
 The function header is same as function declaration.
 The only difference between the two is that a function header is not followed by a
semicolon. The list of variables in the function header is known as the formal
parameter.
 The parameter list may have zero or more parameters of any data type.
 A function can be defined either before or after main().
 The argument names in the function declaration and function definition need not be
the same. However, the data types of the arguments specified in function declaration
must match with the given in function definition.

R. Sathya Priya AP/CSE -KIOT 6|Page


KIOT – Department of CSE

Output: Sum is : 40
FUNCTION CALL
 The function call statement invokes the function.
 When a function is invoked, the compiler jumps to the called function to execute the
statements that are part of that function. Once the called function is executed, the
Program control passes back to the calling function.
 Function Call Statement has the following syntax:
function_name(variable1, variable2,…..);

 When the function declaration is present before the function call, the compiler can
check if the correct number and type of arguments are used in the function call and the
returned value, if any, is being used reasonably.
 List of variables used in function call is known as actual parameter list.
 The actual parameter list may contain variable names, expressions, or constants.
Points to Remember while Functions
Function name and the number and datatype of arguments in the function call must be same
as that given in the function declaration and function header of the function definition.
If the parameter passed to a function are more than what it is specified to accept then the
extra arguments will be discarded.
A Logical error will be generated if the arguments in the function call are placed in the wrong
order.
If the parameters passed to a function are less than what it is specified to accept then the
unmatched arguments will be initialized to some garbage value.
Parameter list must be separated with commas.
Names (and not the datatype) of variables in function declaration, function call, and header of
function definition may vary.

EXAMPLE:
#include<stdio.h>
void sum(void); // function declaration
int main()
{
sum(); //function call
} Output:
void sum () //function definition The sum of first 10 numbers is 55
{
int i,s=0;
for(i=1;i<=10;i++)

R. Sathya Priya AP/CSE -KIOT 7|Page


KIOT – Department of CSE

{
s=s+i;
}
printf(“the sum of the first 10 numbers is %d ”,s);
}

Prime Numbers Between Two Integers:


#include <stdio.h>
int checkPrimeNumber(int n); // Function Declaration
int main() {
int n1, n2, i, flag;
printf("Enter two positive integers: ");
scanf("%d %d", &n1, &n2);
if (n1 > n2) { // swap n1 and n2 if n1 > n2 Output:
n1 = n1 + n2; Enter two positive integers: 12 30
n2 = n1 - n2; Prime numbers between 12 and 30 are:
n1 = n1 - n2; 13 17 19 23 29
}
printf("Prime numbers between %d and %d are: ", n1, n2);
for (i = n1 + 1; i < n2; ++i) {
// flag will be equal to 1 if i is prime
flag = checkPrimeNumber(i); // Function Call
if (flag == 1) {
printf("%d ", i);
}
}
return 0;
}
// user-defined function to check prime number
int checkPrimeNumber(int n) { // Function Definition
int j, flag = 1;
for (j = 2; j <= n / 2; ++j) {
if (n % j == 0) {
flag = 0;
break;
} A function cannot be used on the left side of an assignment statement. Therefore writing, func(10) = 100 ,
} return flag;
is invalid in C, where func is a function that accepts an integer value.
}
return <expression>;  expression appearing in a return statement is
converted to the return type of the function in which the statement appears.
return <variable_name>; (or)
return integer_value; (or)
return variable1;
RETURN STATEMENT:
 The return statement is used to terminate the execution of a function and returns control to the
calling function.
 When the return statement is encountered, the program execution resumes in the calling
function at the point immediately following the function call.
 A return statement may or may not return a value to the calling function.
 The syntax of return statement can be given as

R. Sathya Priya AP/CSE -KIOT 8|Page


KIOT – Department of CSE

Example:
return;
return 10;
return a;
return a+b;

It is legal to have multiple return statement in C.


 In C, one cannot skip the return statement when the return type of the function is non-void type.
The return statement can be skipped only for void types.
 As void means empty, we don’t need to return anything, but we can use the return statement inside
void functions as shown below. Although, we still cannot return any value.
 The "return" statement functions as a jump statement that allows for breaking the flow of a
function and exiting from it. It can be considered as an alternative to the "break statement"
specifically used within functions.
 What will happen if we write some statements below to the return statement? If the program
execution reaches return statement, the statements below to that will not be executed. Execution
control will leave the current function immediately.

Output:
10+5=15
In the program, printf("Hello"); will not be
executed as it's below to the return statement.

PASSING PARAMETERS TO FUNCTIONS:


 When a function is called, the calling function may have to pass some values to the
called function
 There are two ways in which arguments or parameters can be passed to the
called function.
1. Call by value
2. Call by reference
#include<stdio.h>
 Call by value in which values of variables are passed by the calling function to the
int sum(int a, int b)
{ called function. The programs that we have written so far call functions using call-by
return a+b;
value method of passing parameters.
printf("Hello");
}
 Call by reference in which address of variables are passed by the calling function to
int main()
{
int ans;the called function.
ans = BY
CALL sum(10,5);
VALUE
printf("10 + 5 = %d",ans);
return 0;
R. Sathya } AP/CSE -KIOT
Priya 9|Page
KIOT – Department of CSE

 In the call by-value method, the called function creates new variables to store the
value of the arguments passed to it.
 Called function uses a copy of the actual arguments to perform its intended task.
 If the called function is supposed to modify the value of the parameters passed to it,
then the change will be reflected only in the called function. In the calling function
no change will be made to the value of the variables.
 All the changes were made to the copy of the variables and not to the actual
variables.
Example Program:

#include<stdio.h> Output :
void add(int n); The value of num before calling the function= 2
int main() The value of num in the called function= 12
{ The value of num after calling the function= 2
int num = 2;
printf("\n The value of num before calling the function= %d”, num);
add(num);
printf("\n The value of num after calling the function = %d" , num) ;
return 0;
}
void add (int n)
{
n = n + 10;
printf("\n The value of num in the called function = %d", n) ;
}

#include<stdio.h>
void print(int a)
{
printf("From print function ...\n");
printf("Value of a = %p\n",a);
printf("Address of a = %p\n",&a);
}
int main()
{
int a = 10;
printf("From Main Function ...\n");
printf("Value of a = %p\n",a);
printf("Address of a = %p\n",&a);
print(a);
return 0;
}

R. Sathya Priya AP/CSE -KIOT 10 | P a g e


KIOT – Department of CSE

Output
From Main Function ...
Value of a = 0
Address of a = 2024
From print function ...
Value of a = 10
Address of a = 1024
 Values of the variables in the calling function remain unaffected when the arguments are
passed using call by value technique.
 call by-value method also called as one-way of transfer the information.
 call-by-value method of passing arguments to a function must be used only in two cases:
1. When the called function does not need to modify the value of the actual parameter. It
simply uses the value of the parameter to perform its task.
2. When you want that the called function should only temporarily modify the value of
the variables and not permanently. So, although the called function may modify
the value of the variables, these variables remain unchanged in the calling function.
Advantage: pass arguments to the called function is that arguments can be variables (e.g., x),
literals (e.g.,6), or expressions (e.g., x+l).
Disadvantage:
1. Copying data consumes additional storage space.
2. Copying can be time-consuming, which can negatively impact performance, especially
when a function is called frequently.

CALL BY REFERENCE
 When using the call-by-value method for passing arguments from the calling function
to the called function, the only way to return the modified value of the argument to
the caller is by explicitly using the return statement.
 In call by reference, we declare function parameters as references instead of regular
variables. This allows any modifications made by the function to the arguments to be
visible in the calling function.
 To indicate that an argument is passed using call by reference, an asterisk (*) is
placed after the type in the parameter list. This enables changes made to the parameter
in the called function to be reflected in the calling function.
 Call-by-reference method, a function receives an implicit reference to the argument,
rather than a copy of its value.

R. Sathya Priya AP/CSE -KIOT 11 | P a g e


KIOT – Department of CSE

 The function can modify the value of the variable and that change will be reflected
in the calling function
 In call by reference, we pass the address of a variable. So, if we modify the value, it
will affect the original value of a variable

#include<stdio.h> Output :
void add(int *n); The value of num before calling the function= 2
int main() The value of num in the called function= 12
{ The value of num after calling the function= 2
int num = 2;
printf("\n The value of num before calling the function= %d”, num);
add(&num);
printf("\n The value of num after calling the function = %d" , num) ;
return 0; }
void add (int *n)
{ *n = *n + 10;
printf("\n The value of num in the called function = %d", *n) ; }

Output:
Main: Before calling set function a = 10
Set: In set function a = 0
Main: After calling set function a = 0

R. Sathya Priya AP/CSE -KIOT 12 | P a g e


KIOT – Department of CSE

Advantages:
 Arguments are not copied into new variables; it provides greater time and space
efficiency.
 The called function can change the value of the argument and the change is reflected
in the calling function.
 A return statement can return only one value. In case we need to return multiple
values, pass those arguments by reference.
Disadvantages
 When an argument is passed using call by address, it can be challenging to determine
whether that argument is intended for input, output, or both.

DEPENDING UPON THE PRESENCE OF ARGUMENTS AND THE RETURN VALUES,


USER DEFINED FUNCTIONS CAN BE CLASSIFIED INTO FIVE CATEGORIES:
1. Function with no arguments and no return values
2. Function with no arguments and one return value
3. Function with arguments and no return values
4. Function with arguments and one return value
5. Function with multiple return values

FUNCTION WITH NO ARGUMENTS AND NO RETURN VALUES

 A function with no arguments means that the called function does not receive any
data from the calling function.
 A function with no return value means that the calling function does not receive any
data from the called function.
 No data transfer between the calling and called functions.

/* program to calculate the area of square */


#include <stdio.h>
void area(); //function prototype
Output:
int main()
{ Enter the side of square: 3
area(); //function call Area of Square = 9
return 0;
}
void area() In the program, area( ); function
{ calculates area and no arguments are
int square_area,square_side;
printf("Enter the side of square :"); passed to this function. The return
13 | P a g e
R. Sathya Priya AP/CSE -KIOT
scanf("%d",&square_side); type of this function is void and hence
square_area = square_side * square_side;
return nothing.
KIOT – Department of CSE

FUNCTION WITH NO ARGUMENTS AND ONE RETURN VALUE


 When a function has no arguments, it means that the called function does not receive
any data from the calling function.
 A function with one return value means that the function will produce a single result
to be sent back to the caller.
 In such cases, there is no direct data transfer between the calling and called functions,
but the return value allows the caller to receive the computed result from the function.
#include <stdio.h>
int area(); //function prototype with return type int
int main()
{ Output:
Enter the side of square: 3
int square_area;
Area of Square = 9
square_area = area(); //function call
printf("Area of Square = %d",square_area);
return 0; In this function int area( ); no
} arguments are passed but it
int area() returns an integer
{ value square_area.
int square_area,square_side;
printf("Enter the side of square :");
scanf("%d",&square_side);
square_area = square_side * square_side;
return square_area;
}
FUNCTION WITH ARGUMENTS AND NO RETURN VALUES
 A function with arguments will accept data from the calling function, as the
arguments provide the necessary input.
 However, if the function has no return type, it means that nothing will be explicitly
returned to the calling program.
 In this case, it becomes a one-way type of communication, where the function
accepts input but does not send any specific data back to the calling program.

#include <stdio.h>
void area(int square_side); //function prototype
int main()
{ Output:
Enter the side of square: 3
int square_side;
Area of Square = 9
printf("Enter the side of square :");
scanf("%d",&square_side);
R. Sathya Priya AP/CSE//function
-KIOT call 14 | P a g e
area(square_side); In this function, the integer
return 0; value entered by the user
}
KIOT – Department of CSE

FUNCTION WITH ARGUMENTS AND ONE RETURN VALUE


 A function with arguments and one return value enables both the calling function and
the called function to exchange data.
 The calling function provides input data through the arguments passed to the called
function.
 The called function processes the data and returns a result value back to the calling
function.
 This type of interaction between the calling and called function can be considered as a
dual communication, as both get-togethers exchange data and receive information
from each other.

#include <stdio.h>
int area(int square_side); //function prototype with return type int
int main()
{ Output:
int square_area,square_side; Enter the side of square: 3
printf("Enter the side of square :"); Area of Square = 9
scanf("%d",&square_side);
square_area = area(square_side); //function call
printf("Area of Square = %d",square_area);
return 0;
}
int area(int square_side)
{
int square_area;
square_area = square_side * square_side;
return square_area;
}

R. Sathya Priya AP/CSE -KIOT 15 | P a g e


KIOT – Department of CSE

FUNCTION WITH MULTIPLE RETURN VALUES


 Typically, functions return a single value, but it is possible to create functions that
return multiple values using input parameters and output parameters.
 Input parameters are used to receive data, while output parameters are used to send
data.
 The address operator (&) and indirection operator (*) are used to achieve this
functionality.
 The following example will provide further clarity on this concept.

#include <stdio.h>
void area_volume(int l, int *a, int *v); //function prototype
int main()
Output:
{
Enter the side of square :3
int l,a,v;
Area = 9
printf("Enter the side of square :"); Volume = 27
scanf("%d",&l);
area_volume(l,&a,&v); //function call
In the above program l is input
printf("Area = %d\n Volume = %d",a,v);
argument, a and v are output
return 0;
arguments. In the function call, we
} pass actual value of l whereas
void area_volume(int l, int *a, int *v) addresses of a and v are passed.
{
*a = l*l;
*v = l*l*l;
}

Math Function :
 List of math functions available, that allows you to perform mathematical tasks on
numbers.
 To use them, you must include the math.h header file in your program:
#include <math.h>

R. Sathya Priya AP/CSE -KIOT 16 | P a g e


KIOT – Department of CSE

R. Sathya Priya AP/CSE -KIOT 17 | P a g e

You might also like