Professional Documents
Culture Documents
Unit 3 PPS
Unit 3 PPS
Example:
void hello( )
{
printf("hello UVCE");
}
3.1 INTRODUCTION TO NEED OF FUNCTIONS:
We know, the C program consists of a main function and inside that we are writing the logic of the program.
Disadvantage of this method is,
if the logic/code in the main function becomes huge or complex, it will become difficult to debug the
program or test the program or maintain the program.
So we‟ll break down entire logic into different parts, this type of approach for solving the given problems is
known as Top Down approach.
Types Of Functions:
Based on the nature of functions, they can be divided into two categories.
They are:
1) In-built functions / Predefined functions / Library functions Ex: printf, scanf
2) User defined functions Ex: main()
a) In-built functions / Predefined functions:
Is a function which is already written by another developer.
The users generally use these library functions in their own programs for performing the desired task.
The predefined functions are available in the header files.
So, the user has to include the respective header file to use the predefined functions available in it.
Example: the printf function which is available in the header file is used for printing information.
Other examples of predefined functions are: scanf, strlen, strcat, sqrt, fabs etc.
“extern”
extern storage class simply tells us that the variable is defined elsewhere and not
within the same block where it is used.
The main purpose of using extern variables is that they can be accessed between
two different files which are part of a large program.
example: int i=1;------- extern int i;
A normal global variable can be made extern as well by placing the “extern ‟
keyword before its declaration/definition in any function/block.
“static”
This storage class is used to declare static variables used while writing programs in
C language.
Static variables have a property of preserving their value even after they are out of
their scope!
Hence, static variables preserve the value of their last use in their scope.
example: static int i=1;
Global static variables can be accessed anywhere in the program.
By default, they are assigned the value 0 by the compiler.
“register”
This storage class declares register variables which have the same functionality as
that of the auto variables. The only difference is that the compiler tries to store
these variables in the register of the microprocessor if a free register is available.
This makes the use of register variables to be much faster than that of the variables
stored in the memory during the runtime of the program.
example: register int i;
An important and interesting point to be noted here is that we cannot obtain
the address of a register variable using pointers.
BASIC ELEMENTS OF USER DEFINED FUNCTION:
For creating user defined functions in C programs, we have to perform three steps.
They are:
a) Function Declaration: Declaring the function (blue-print).
b) Function Definition: Defining the function (logic).
c) Function Calling: use of function in program (calling)
d) FUNCTION DECLARATION:
The function declaration is the blue print of the function. The function declaration can also be called as
the function’s prototype.
The function declaration tells the compiler and the user about what is the function ‟s name, inputs and
output(s) of the function and the return type of the function.
Example:
int add(int a, int b)
{
int res;
res = a+b;
return res;
}
c) FUNCTION CALLING:
After declaring and defining the functions, we can use the functions in our program. For using the functions,
we must call the function by its name.
Syntax: of function definition is shown below function_name(parameters list);
Example: add(m,n);
Whenever the compiler comes across a function call, it takes the control of execution to the first statement in
the function‟s definition.
After the completion of function i.e., whenever the compiler comes across the return statement or the
closing brace of the function’s body, the control will return back to the next statement after the function call.
CATEGORIES OF USER DEFINED FUNCTIONS:
A function may or may not accept any argument. It may or may not return any value. Based on these facts,
there are four different aspects of function calls.
a) function without arguments and without return value
b) function without arguments and with return value
c) function with arguments and without return value
d) function with arguments and with return value
In the above example, sum function has two parameters/arguments. The task of this function is to print the
sum without using return value.
d) Function with arguments and with return value:
In this type of functions, the function definition consists of parameters/arguments.
Also, these functions returns a value back to the point at which the function was called.
These types of functions are the most frequently used in programming.
Example:
int add(int x, int y)
{
int result;
result = x + y;
return result;
}
In the above example, the function add consists of two arguments or parameters x and y.
The function adds both x and y and returns that value stored in the local variable result back to the point at
which the function was called.
PROGRAM TO FIND GCD & LCM USING FUNCTIONS:
Functions that return multiple values in C
We already know that the design of C functions prohibits us from returning multiple values.
However, programmers frequently want a function to return multiple values.
Fortunately, there are a few solutions for returning multiple values in C.
The methods for returning multiple values from a function in C are as follows:
Using pointers.
Using structures.
Using Arrays.
Using Pointers
In C, we may employ pointers to return more than one value from a function by passing pointers as function
arguments and using them to set several values visible in the caller function.
Example
#include <stdio.h>
// Function to return multiple values using pointers
void func(int *var1, int *var2, char *var3)
{
*var1 = 40;
*var2 = 50;
*var3 = 'X';
}
int main(void)
{
int var1, var2;
char var3;
Output:
FACTORIAL OF A NUMBER –
Factorial of n is the product of all positive descending integers.
Factorial of n is denoted by n!
Example: 5! = 5*4*3*2*1 = 120
Recursive function: 5!=5*4! // n * Fact(n-1)
4!=4*3! ……….. 1!=1*0! 0!=1 //stop calling
Program to find factorial of given number using recursion:
#include
int find_factorial(int);
void main()
{
int num, fact;
printf("\nEnter any integer number:");
scanf("%d",&num);
fact =find_factorial(num);
printf("\nfactorial of %d is: %d",num, fact);
}
//recursive function definition
int find_factorial(int n)
{
if(n==0)
{
return 1;
}
else
{
return(n*find_factorial(n-1));
}
}
FIBONACCI SERIES
A series of numbers in which each number ( Fibonacci number ) is the sum of the two preceding numbers.
Example: 0, 1, 1, 2, 3, 5, 8, etc.
The first two numbers of fibonacci series are 0 and 1.
Recursive Function:
There are 3 cases in fibonacci series
1) if n = 1 only one digit to be printed i.e “0”.
2) 2) if n = 2 only two digit to be printed i.e “1”.
3) 3) if n > 2 last two digits to be added & printed so “fib(n-1) + fib(n-2)”
int main() {
int my_array[] = {1, 2, 3, 4, 5};
int result = recursive_sum(my_array, sizeof(my_array) / sizeof(my_array[0]) - 1);
printf("Sum of array elements: %d\n", result);
return 0;
}
OUTPUT: 15
Passing strings to functions
Passing strings to functions using recursion in C language involves creating recursive functions that work with
character arrays (strings) to perform various operations.
Definition: Passing strings to functions using recursion in C means creating recursive functions that
manipulate or process character arrays (strings) by calling themselves with sub-strings or individual
characters.
Example 1:
#include <stdio.h>
// Function to calculate the length of a string recursively
int recursive_strlen(const char *str) {
if (*str == '\0’) {
return 0; // Base case: end of the string
} else {
return 1 + recursive_strlen(str + 1); // Recursion: move to the next character
} }
int main() {
const char *my_string = "Hello, World!";
int length = recursive_strlen(my_string);
printf("Length of the string: %d\n", length);
return 0;
} OUTPUT: Length of
the string is 13
Example 2:
#include <stdio.h>
// Function to reverse a string recursively
void recursive_reverse(char *str, int start, int end) {
if (start >= end) {
return; // Base case: the string is reversed
} else {
// Swap characters at start and end positions
char temp = str[start];
str[start] = str[end];
str[end] = temp;
int main() {
char my_string[] = "Hello, World!";
recursive_reverse(my_string, 0, strlen(my_string) - 1);
printf("Reversed string: %s\n", my_string);
return 0;
} OUTPUT: Reversed string: !dlroW ,olleH
POINTERS
A pointer is a derived data type in C.
It is built from one of the fundamental data types available in C.
Pointers contain memory addresses as their values.
Since these memory addresses are the locations in the computer memory where program instructions and
data are stored.
pointers can be used to access and manipulate data stored in the memory.
Advantages of Pointers:
Pointers are used frequently in C, as they offer a number of benefits to the programmers.
They include the following:
Pointers are more efficient in handling arrays and data tables.
Pointers allow C to support dynamic memory management.
Pointers provide an efficient way for manipulating dynamic data structures such as structures, linked lists,
queues, stacks and trees.
Pointers increase the execution speed and thus reduce the program execution time.
Pointers can be used to return multiple values from a function via function arguments.
Pointers allow passing a function as argument to other functions.
Pointer Constants: The memory addresses within a computer are referred to as pointer constants.
Pointer Values: We cannot assign the memory addresses directly to a variable. We can only get the address of
a variable by using the address operator (&). The value thus obtained is known as pointer value.
Pointer Variables: Once we obtain the pointer value, we can store it in a variable. Such variable which stores
the memory address is known as a pointer variable.
b) Declaring Pointer Variables:
In C, every variable must be declared for its type.
Since pointer variables contain addresses that belong to a specific data type, they must be
declared as pointers before we use them.
Syntax for declaring a pointer is as shown below:
datatype *pointer-name;
This tells the compiler three things about the variable pointer-name.
They are: The asterisk (*) tells that the variable pointer-name is a pointer variable, pointer-name
needs a memory location and pointer-name points to a variable of type datatype.
Example: int *p; float *p; char *ch;
DRAWBACKS OF POINTERS:
Uninitialized pointers might cause segmentation fault.
Dynamically allocated block needs to be freed explicitly. Otherwise, it would lead to memory leak.
Pointers are slower than normal variables.
If pointers are updated with incorrect values, it might lead to memory corruption.
Understanding and using pointers in best way possible requires a lot of time.
Example:
#include
#include
struct student
{
int id;
char name[20];
float percentage;
};
Program 1:
The below program will give segmentation fault since ‘A’ was local to the function:
// main Code
int main()
{
// Declare a pointer
int* p;
/ Function call
p = fun();
printf("%p\n", p);
printf("%d\n", *p);
return 0;
}
Runtime Errors:
Segmentation fault
Output:
No output
The main reason behind this scenario is that compiler always make a stack for a function call.
As soon as the function exits the function stack also gets removed which causes the local variables of
functions goes out of scope.
Static Variables have a property of preserving their value even after they are out of their scope.
So to execute the concept of returning a pointer from function in C you must define the local variable as a
static variable.
0x601038 10
PROGRAM 2: // C program to illustrate the concept of returning pointer from a function
#include <stdio.h>
// main Code
int main()
{
// Declare a pointer
int* p;
// Function call
p = fun();
// Print Address
printf("%p\n", p);
// Print value at the above address
printf("%d\n", *p);
return 0; } OUTPUT: 0x601038
10