C UNIT 4 Notes

Download as pdf or txt
Download as pdf or txt
You are on page 1of 24

UNIT IV FUNCTIONS AND POINTERS

Function – definition of function – Function Prototypes – Pass by value - Pass by


reference– Recursion – Pointers: Definition-Initialization-Pointer Arithmetic-Pointer
and Arrays

Function:

● A function is a block of code that performs a specific task.


● 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

Types of function:

There are two types of function in C programming:

● Standard library functions


● User-defined functions
Function Needs:

There are three aspects of a C function.

Function declaration :A function must be declared globally in a c program


to tell the compiler about the function name, function parameters, and return
type.

Function call :Function can be called from anywhere in the program. The
parameter list must not differ in function calling and function declaration.
We must pass the same number of functions as it is declared in the function
declaration.

Function definition :It contains the actual statements which are to be


executed. It is the most important aspect to which the control comes when
the function is called. Here, we must notice that only one value can be
returned from the function.

S.N function aspects Syntax_______________

1 Function declaration return_type function_name (argument list);

2 Function call function_name (argument_list)

3 Function definition return_type function_name (argument list)

function body

Standard library functions:

● The standard library functions are built-in functions in C programming.


● These functions are defined in header files.
● For example,
The printf() is a standard library function to send formatted output to
the screen (display output on the screen). This function is defined in the
stdio.h header file.

User-defined functions:

Functions that are created by the user are known as user-defined functions.

#include <stdio.h>

void functionName()

... .. ...

... .. ...

int main()

... .. ...

... .. ...

functionName();

... .. ...

... .. ...

Advantages of user-defined function

● The program will be easier to understand, maintain and debug.


● Reusable codes that can be used in other programs
● A large program can be divided into smaller modules. Hence, a large project
can be divided among many programmers.
Return Statement: The return statement terminates the execution of a function
and returns a value to the calling function. The program control is transferred to
the calling function after the return statement.

Different aspects of function calling:

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.

● function without arguments and without return value


● function without arguments and with return value
● function with arguments and without return value
● function with arguments and with return value

C Programming Functions Without Arguments and Without Return Value:

A function in C programming may not accept an argument and a Return Value.


Here’s an example of such a function.

#include<stdio.h>
void sum();
void main()
{
printf("\nGoing to calculate the sum of two numbers:");
sum();
}
void sum()
{
int a,b;
printf("\nEnter two numbers");
scanf("%d %d",&a,&b);
printf("The sum is %d",a+b);
}

Output
Going to calculate the sum of two numbers:

Enter two numbers 10


24

The sum is 34

C programming Functions without Arguments But has a Return Value:

A function can return a value without accepting any arguments. Here’s an example
for calculating and returning the area of a rectangle without taking any argument.
#include<stdio.h>
int sum();
void main()
{
printf("Going to calculate the area of the square\n");
float area = square();
printf("The area of the square: %f\n",area);
}
int square()
{
float side;
printf("Enter the length of the side in meters: ");
scanf("%f",&side);
return side * side;
}

Output

Going to calculate the sum of two numbers:

Enter two numbers 10


24

The sum is 34

C programming Functions With Arguments and With a Return Value:


Most C functions will accept arguments and provide a return value. The
following program demonstrates a function in C programming that takes
arguments and returns a value.

#include<stdio.h>
int sum(int, int);
void main()
{
int a,b,result;
printf("\nGoing to calculate the sum of two numbers:");
printf("\nEnter two numbers:");
scanf("%d %d",&a,&b);
result = sum(a,b);
printf("\nThe sum is : %d",result);
}
int sum(int a, int b)
{
return a+b;
}

Output

Going to calculate the sum of two numbers:


Enter two numbers:10
20
The sum is : 30

C programming Functions With Arguments But No Return Value:


C functions may accept arguments but not provide any return value. Given below
is an example of such a function.

#include<stdio.h>
void sum(int, int);
void main()
{
int a,b,result;
printf("\nGoing to calculate the sum of two numbers:");
printf("\nEnter two numbers:");
scanf("%d %d",&a,&b);
sum(a,b);
}
void sum(int a, int b)
{
printf("\nThe sum is %d",a+b);
}

Output

Going to calculate the sum of two numbers:

Enter two numbers 10


24

The sum is 34

Difference Between Argument and Parameter in C:

Argument Parameter
Arguments are used while calling Parameters are used during the
the function declaration of the function

Argument is the actual value of Parameter is variable in the


this variable that gets passed to declaration of the function
function.

Function Arguments:
● A function’s arguments are used to receive the necessary values by the
function call.
● Functions can be invoked in two ways: Call by Value or Call by Reference.
These two ways are generally differentiated by the type of values passed to
them as parameters.
● The parameters passed to function are called actual parameters whereas the
parameters received by function are called formal parameters.

Call By Value: In this parameter passing method, values of actual parameters


are copied to function’s formal parameters and the two types of parameters are
stored in different memory locations. So any changes made inside functions are
not reflected in actual parameters of the caller.

Call by Reference: Both the actual and formal parameters refer to the same
locations, so any changes made inside the function are actually reflected in
actual parameters of the caller.
Difference between Call by Value and Call by Reference

Call By Value Call By Reference

While calling a function, we pass values While calling a function, instead of


of variables to it. Such functions are passing the values of variables, we pass
known as “Call By Values”. address of variables (location of
variables) to the function known as
“Call By References.

In this method, the value of each In this method, the address of actual
variable in calling function is copied variables in the calling function are
into corresponding dummy variables of copied into the dummy variables of the
the called function. called function.

With this method, the changes made to With this method, using addresses we
the dummy variables in the called would have an access to the actual
function have no effect on the values of variables and hence we would be able to
actual variables in the calling function. manipulate them.

In call by reference we can alter the


values of variables through function
In call-by-values, we cannot alter the calls
values of actual variables through
function calls.
Pointer variables are necessary to define
Values of variables are passed by the to store the address values of variables.
Simple technique.
PROGRAM TO SWAP 2 NUMBERS USING CALL BY VALUE
// C program to illustrate
// call by value

#include <stdio.h>

// Function Prototype
void swapx(int x, int y);

// Main function
int main()
{
int a = 10, b = 20;

// Pass by Values
swapx(a, b);

printf("a=%d b=%d\n", a, b);


return 0;
}

// Swap functions that swaps


// two values
void swapx(int x, int y)
{
int t;
t = x;
x = y;
y = t;

printf("x=%d y=%d\n", x, y);


}

Output:
x=20 y=10
a=10 b=20

PROGRAM TO SWAP 2 NUMBERS USING CALL BY REFERENCE:

// Call by Reference

#include <stdio.h>

// Function Prototype
void swapx(int*, int*);

// Main function
int main()
{
int a = 10, b = 20;

// Pass reference
swapx(&a, &b);

printf("a=%d b=%d\n", a, b);

return 0;
}
// Function to swap two variables
// by references
void swapx(int* x, int* y)
{
int t;

t = *x;
*x = *y;
*y = t;

printf("x=%d y=%d\n", *x, *y);


}

Output:
x=20 y=10
a=20 b=10

Advantage of functions in C
There are the following advantages of C functions.

● 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 a overhead in a C program.

IMPORTANT POINT TO NOTE FOR FUNCTIONS IN C

● Every program in C has a function. Even if you do not use a library or


user-defined function, you will have to use the main function. The main
function is the program’s entry point, as that is where the compiler will start
executing the code.
● Even if a function does not return a value, it has a return type. If a return
value is provided, the return type is the data type of the value. But if there is
no return value, then the void is the return type of the function.
● C functions cannot return array and function types. However, you can easily
overcome this limitation with the use of pointers.
● While in C++, void func() and void func(void) mean the same; it is not the
case with C programming. In C, a function declared without any parameter
list can be called with any number of parameters. Hence, it is advisable to
declare a function as void func(void) and not void func() if you want to call
a function without any parameter.
● If you call a function before the declaration, the C compiler will by default
consider the return type to be int and show an error if the data type of the
return value is anything except int.

RECURSION
● Recursion is the technique of making a function call itself.
● Recursion is a routine that calls itself again and again directly or indirectly.
There are two types of recursion in the C language namely, Direct
calling and Indirect calling. The calling refers to the recursive call.
● The recursion is possible in C language by using method and function. The
problems like the Tower of Hanoi, the Fibonacci series, and the nth
derivative can be solved using recursion. The recursion uses a stack to store
its calls in memory.
● The recursion contains two cases in its program body.
i. Base case: When you write a recursive method or function, it keeps calling
itself, so the base case is a specific condition in the function. When it is met,
it terminates the recursion. It is used to make sure that the program will
terminate. Otherwise, it goes into an infinite loop.

ii. Recursive case: The part of code inside the recursive function executed
repeatedly while calling the recursive function is known as the recursive
case.
Basic Syntax of Recursion
The syntax for recursion is :
void recursive_fun() //recursive function
{
Base_case; // Stopping Condition

recursive_fun(); //recursive call


}

int main()
{

recursive_fun(); //function call


}

The function call inside the main function is normal call, it calls
the recursive_fun() function inside which there is another function
call recursive_fun(); which is termed as recursive call and the
whole recursive_fun() function is recursive function. Base_case is the
stopping condition for the recursive function.
Types of Recursion in C
There are two types of recursion in the C language.
1. Direct Recursion
2. Indirect Recursion

1. Direct Recursion
Direct recursion in C occurs when a function calls itself directly from inside.
Such functions are also called direct recursive functions.
Following is the structure of direct recursion.

function_01()
{
//some code
function_01();
//some code
}
In the direct recursion structure, the function_01() executes, and from inside,
it calls itself recursively.
2. Indirect Recursion
Indirect recursion in C occurs when a function calls another function and if
this function calls the first function again. Such functions are also called
indirect recursive functions.
Following is the structure of indirect recursion.
function_01()
{
//some code
function_02();
}

function_02()
{
//some code
function_01();
}

In the indirect recursion structure the function_01() executes and


calls function_02(). After calling now, function_02 executes where inside it
there is a call for function_01, which is the first calling function.
C Program Function to show direct recursion
Here is a simple C program to print the Fibonacci series using direct
recursion.
#include<stdio.h>
int fibonacci_01(int i)
{
if (i == 0)
{ return 0; }
if (i == 1)
{ return 1; }
return fibonacci_01(i - 1) + fibonacci_01(i - 2);
}
int main()
{
int i, n;
printf("Enter a digit for fibonacci series: ");
scanf("%d", & n);
for (i = 0; i < n; i++) {
printf(" %d ", fibonacci_01(i));
}
return 0;
}

Output:
Enter a digit for fibonacci series: 8
0 1 1 2 3 5 8 13

In the C program above, we have declared a function named fibonacci_01().


It takes an integer i as input and returns the ith element of the Fibonacci
series.
⮚ At first, the main() function will be executed where we have taken two
variables i and n. We will take input from the user that will be stored in n,
and the for loop will execute till n iteration where with each iteration, it will
pass the parameter to fibonacci_01() function where the logic for the
Fibonacci series is written.

⮚ Now inside fibonacci_01() function, we have nested if-else. If input = 0, it


will return 0, and if the input = 1, it will return 1.

⮚ These are the base cases for the Fibonacci function.

⮚ If the value of i is greater than 1, then fibonacci(i) will return fibonacci_01 (i


- 1) + fibonacci_01 (i -2) recursively, and this recursion will be computed till
the base condition.

Advantages and Disadvantages of Recursion


Advantages:
1. The code becomes shorter and reduces the unnecessary calling to functions.
2. Useful for solving formula-based problems and complex algorithms.
3. Useful in Graph and Tree traversal as they are inherently recursive.
4. Recursion helps to divide the problem into sub-problems and then solve
them, essentially divide and conquer.
Disadvantages:
1. The code becomes hard to understand and analyse.
2. A lot of memory is used to hold the copies of recursive functions in the
memory.
3. Time and Space complexity is increased.
4. Recursion is generally slower than iteration.

WHAT IS A POINTER?
DEFINITION:
A pointer is a variable that stores a memory address. Pointers are used to store the
addresses of other variables or memory items. Pointers are essential for dynamic
memory allocation.
INITIALIZATION:
Pointer initialization is nothing but assigning value to the pointer variable. It
contains the address of a variable of the same data type. The ampersand (&)
operator can be used to get the address of a variable.

Example:
#include <stdio.h>
int main ()
{
int var = 5;
int *ptr; // Pointer declaration
ptr = &var; //Pointer initialization
printf ("\n The value at address: %p is: %d\n", ptr, *ptr);
return 0;
}

Output:
The value at address: 0x7ffd33bd5134 is : 5
Fig: Explanation for pointer initialization and declaration

NULL Pointer:

While declaring a pointer variable, if it is not initialized/assigned to anything, it


can point to some random memory location, hence contains garbage value. There it
is recommended to assign a NULL value to it.

int *ptr = NULL;

POINTERS ARITHMETIC:
A pointer in c is an address, which is a numeric value. Therefore, you can perform
arithmetic operations on a pointer just as you can on a numeric value. There are
four arithmetic operators that can be used on pointers: ++, --, +, and –
There are only a few operations that are allowed to perform on Pointers in C
language. The operations are slightly different from the ones that we generally use
for mathematical calculations. The operations are:
1. Increment/Decrement of a Pointer
2. Addition of integer to a pointer
3. Subtraction of integer to a pointer
4. Subtracting two pointers of the same type
5. Comparison of pointers of the same type.

1. Increment/Decrement of a Pointer
Increment:
It is a condition that also comes under addition. When a pointer is incremented, it
increments by the number equal to the size of the data type for which it is a pointer.
When a pointer is incremented, it increments by the number equal to the size of the
data type for which it is a pointer.
For Example:
If an integer pointer that stores address 1000 is incremented, then it will
increment by 4(size of an int) and the new address it will points to 1004.
Decrement:
It is a condition that also comes under subtraction. When a pointer is decremented,
it decrements by the number equal to the size of the data type for which it is a
pointer.

For example:

If an integer pointer that stores address 1000 is decremented, then it will


decrement by 4(size of an int) and the new address it will points to 996. While if a
float type pointer is decremented then it will decrement by 4(size of a float) and
the new address will be 996.
2. Addition of integer to a pointer

When a pointer is added with a value, the value is first multiplied by the size of
data type and then added to the pointer.

3. Subtraction of integer to a pointer


When a pointer is subtracted with a value, the value is first multiplied by the size
of the data type and then subtracted from the pointer.
4. Subtracting two pointers of the same type

The subtraction of two pointers is possible only when they have the same data
type. The result is generated by calculating the difference between the addresses of
the two pointers and calculating how many bits of data it is according to the pointer
data type. The subtraction of two pointers gives the increments between the two
pointers.

For Example:
Two integer pointers
say ptr1(address:1000) and ptr2(address:1004) are subtracted. The difference
between address is 4 bytes.
Since the size of int is 4 bytes, therefore the increment between ptr1 and ptr2 is
given by (4/4) = 1.

5. Comparison of pointers of the same type:

We can compare the two pointers by using the comparison operators in C. We can
implement this by using all operators in C >, >=, <, <=, ==,!=. It returns true for
the valid condition and returns false for the unsatisfied condition.

Step 1: Initialize the integer values and point these integer


values to the pointer.
Step 2: Now, check the condition by using comparison or
relational operators on pointer variables.
Step 3: Display the output.
DOUBLE POINTERS :
A pointer is used to store the address of variables. So, when we define a
pointer to pointer, the first pointer is used to store the address of the second pointer.
Thus, it is known as double pointers.
The syntax of declaring a double pointer is given below.
int **p; // pointer to a pointer which is pointing to an integer.
Example
int main()
{
int v = 76;
int *p1;
int **p2;
p1 = &v;
p2 = &p1;
printf("Value of v = %d\n", v);
printf("Value of v using single pointer = %d\n", *p1 );
printf("Value of v using double pointer = %d\n", **p2);
return 0;
}
Output
Value of v = 76
Value of v using single pointer = 76
Value of v using double pointer = 76

POINTERS AND ARRAYS


In C language, pointers and arrays are so closely related.
i) An array name itself is an address or pointer. It points to the address of first
element (0th element) of an array.
Example
#include<stdio.h>
void main()
{
int a[3]={10,15,20};
printf(“First element of array is at %u\n”, a);
printf(“2nd element of array is at %u\n”, a+1);
printf(“3nd element of array is at %u\n”, a+2);
}
1000 1002 1004
10 15 20
Output
First element of array is at 1000
2 nd element of array is at 1002
3 nd element of array is at 1004

ii)Any operation that involves array subscripting is done by using pointers in c


language.

E.g.) E1[E2]=>*(E1+E2)
Example
#include<stdio.h>
void main()
{
int a[3]={10,15,20};
printf(“Elements are %d %d %d\n”, a[0],a[1],a[2]);
printf(“Elements are %d %d %d\n”, *(a+0),*(a+1),*(a+2);
}
Output:
Elements are 10 15 20
Elements are 10 15 20

Difference between Array and Pointers

S.No Pointer Array

It is declared as -: It is declared as -:
1.
*var_name; data_type var_name[size];

2. It is a variable that stores the It is the collection of elements


address of another variable. of the same data type.

3. We can create a pointer to an We can create an array of


array. pointers.

A pointer variable can store An array can store a number of


4. the address of only one elements the same size as the
variable at a time. size of the array variable.

5. Pointer allocation is done Array allocation is done during


during runtime. compile runtime.

The nature of pointers is


dynamic. The size of a pointer
The nature of arrays is static.
in C can be resized according
6. During runtime, the size of an
to user requirements which
array in C cannot be resized
means the memory can be
according to user requirements.
allocated or freed at any point
in time.

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