0% found this document useful (0 votes)
244 views

MODULE 4 Functions and Pointers

The document discusses functions and pointers in C programming. It defines functions and explains that they allow programmers to modularize code. It also describes different types of functions like predefined standard library functions and user-defined functions. The key reasons for using functions are to improve readability, reusability, and debuggability of code. The document then explains function prototypes, syntax, and different types of user-defined functions based on arguments and return values. It also covers function calls, recursion, and provides examples.

Uploaded by

manoj hm
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)
244 views

MODULE 4 Functions and Pointers

The document discusses functions and pointers in C programming. It defines functions and explains that they allow programmers to modularize code. It also describes different types of functions like predefined standard library functions and user-defined functions. The key reasons for using functions are to improve readability, reusability, and debuggability of code. The document then explains function prototypes, syntax, and different types of user-defined functions based on arguments and return values. It also covers function calls, recursion, and provides examples.

Uploaded by

manoj hm
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
You are on page 1/ 19

MODULE 4: FUNCTIONS AND POINTERS

Definition:A function is a set of instructions to carry out a particular task. They allow the
programmer to modularize a program. All variables defined in function are local variables,
they are known only in the function in which they are defined .They are also defined as list of
parameter which provide means of communicating information between function and are
also local variables.
Types of functions
1) Predefined standard library function such as puts( ),gets( ), printf( ), scanf( ) theses are
function which already have been defined in the header file (for example stdio.h) so we can
use them whenever required
2) User defined function are function which can be created by the user.

Why do we need functions?


 To increase the readability of the code. Breaking down the program into small pieces
of sub programs makes it easier to read and understand the implementation.
 To improve the reusability of the code. The functions written can be reused by other
programmers.
 Debugging the code would be easier. Since the program is broken down into smaller
pieces, debugging the code becomes much easier and less time consuming.
 Reducing the size of the code. Writing functions reduces the size of the code, a set of
lines in the program converted to a function, get reduced to one line function call in
the main program.

A function that calls another function is called as calling function a function that is being
called is known as called functions.

Function Prototype:
Function prototype tells compiler about number of parameters function accepts,data-types of
parameters and return type of function. By using this information, compiler cross checks
function parameters and their data-type with function definition and function call.
Function prototype declaration is placed before the main() function. The syntax of prototype
declaration is as shown below. The function prototype is always terminated using a
semicolon.
return_data_typefunction_name (data_type_list);
return_data_type is the return type provided by the function, function_name specifies the
name of the function that follows the similar rules of naming a variable, the data_type_list is
the list of parameters or arguments along with their data types that a function accepts.
Syntax of Function:
return_data_type function name(data_type variable1,data_type variable2,……)

/* Function Body */

return_data_type is the return type provided by the function, function_name specifies the
name of the function that follows the similar rules of naming a variable, the data_type_list is
the list of parameters or arguments along with their data types that a function accepts.
The portion of the program code that is part of the function is written in the function body.

Example 1: Program to find square of a number using function


#include<stdio.h>
int square(int x);
int main( )
{
int y;
printf(“\n Enter the value of y:”);
scanf(“%d”,&y);
printf(The square of a number is :%d”,square(y));
return 0;
}
int square(int x)
{
intsqr;
sqr= x* x;
returnsqr; // Return type of integer
}

Types of User Defined Functions in C Programming

In C Programming, as per our requirement, we can define the User defined functions in
multiple ways

1. Function with no argument and no Return value


2. Function with no argument and with Return value
3. Function with argument and No Return value
4. Function with argument and Return value

From the above, 1 and 3 types does not return any value when the function is called so, We
use void return type while defining the function.

When we call the function 2 and 4 types will return some value so, we have to use the
appropriate data type (int, float, double etc) as return type while defining the function. We
use return keyword inside the function to return some value when the function is called from
the main() function or any sub functions.

1. Function with no argument and no Return value

In this method, we won’t pass any arguments to the function while defining, declaring or
calling the function. This type of functions will not return any value when we call the
function from main() or any sub function. When we are not expecting any return value but,
we need some statements to be printed as output then, these types of functions are very
useful.

Example Code:
/* Function with No argument and No Return value Example */
#include<stdio.h>

// Function Declaration
void Addition();

void main()
{
printf("\n ............. \n");

Addition();
}

void Addition()
{
int Sum, a = 10, b = 20;
Sum = a + b;

printf("\n Sum of a = %d and b = %d is = %d", a, b, Sum);


}

2. Function with no argument and with Return value

In this method, we won’t pass any arguments to the function while defining, declaring or
calling the function. This type of functions will return some value when we call the function
from main() or any sub function. Data Type of the return value will depend upon the return
type of function declaration. For instance, if the return type is int then return value will be int.
#include<stdio.h>

int Multiplication();

int main()
{
int Multi;

Multi = Multiplication();
printf("\n Multiplication of a and b is = %d \n", Multi );

return 0;
}

int Multiplication()
{
int Multi, a = 20, b = 40;

Multi = a * b;

return Multi;
}

3. Function with argument and No Return value


This method allows us to pass the arguments to the function while calling the function. But,
this type of functions will not return any value when we call the function from main () or any
sub function.
#include<stdio.h>

void Addition(int, int);

void main()
{
int a, b;

printf("\n Please Enter two integer values \n");


scanf("%d %d",&a, &b);

//Calling the function with dynamic values


Addition(a, b);
}

void Addition(int a, int b)


{
int Sum;

Sum = a + b;

printf("\n Addition of %d and %d is = %d \n", a, b, Sum);


}

4. Function with argument and Return value

This method allows us to pass the arguments to the function while calling the function. This
type of functions will return some value when we call the function from main () or any sub
function. Data Type of the return value will depend upon the return type of function
declaration. For instance, if the return type is int then return value will be int.
#include<stdio.h>
int Multiplication(int, int);

int main()
{
int a, b, Multi;

printf("\n Please Enter two integer values \n");


scanf("%d %d",&a, &b);

//Calling the function with dynamic values


Multi = Multiplication(a, b);

printf("\n Multiplication of %d and %d is = %d \n", a, b, Multi);


return 0;
}

int Multiplication(int a, int b)


{
int Multi;

Multi = a * b;

return Multi;
}

Example:
Types of calling a function:

1. Call by Value
2. Call by Reference

Call by Value:

In call by value, a copy of the data is made and the copy is sent to the function. The copies of
the value held by thearguments are passed by the function call. Since only copies of values
held in the arguments are passed by the functioncall to the formal parameters of the called
function, the value in the arguments remains unchanged. In other words, as onlycopies of the
values held in the arguments are sent to the formal parameters, the function cannot directly
modify thearguments passed. This can be demonstrated by deliberately trying to do so.

Call by Reference:

Pass by reference, sends the address of the data rather than a copy. In this case, the called
function can change the original data in the calling function. Whenever the data in the calling
function has to be changed, one must pass the variable’s address and use it to change the
value. Here, the values are passed by handing over the addresses of arguments to the called
function, it is possible to change the values held within these arguments by executing the
function. This appears as if multiple values are returned by the called function.

#include<stdio.h>
void swap(int*n1,int*n2);

int main()
{
int num1 =5, num2 =10;
// address of num1 and num2 is passed
swap(&num1,&num2);
printf("num1 = %d\n", num1);
printf("num2 = %d", num2);
return0;
}
// pointer n1 and n2 stores the address of num1 and num2 respectively
void swap(int* n1,int* n2)
{
int temp;
temp=*n1;
*n1 =*n2;
*n2 = temp;
}

Recursion

A recursive function is one that calls itself directly or indirectly to solve a smaller version of
its task until a final call which does not require a self-call.

What is needed for implementing recursion?


1. The problem should be decomposed into smaller problems of same type.
2. Recursive calls must diminish problem size.
3. A base case is needed.
4. Base case must be reached. A recursive function acts as a terminating condition. Without
an explicitly defined base case, a recursive function would call itself indefinitely.
5. It is the building block to the complete solution. In a sense, a recursive function determines
its solution from the base case(s) it reaches.
The recursive algorithms will generally consist of an ifstatement with the following form:

if(this is a base case) then

solve it directly

else

redefine the problem using recursion.

Programs on Recursive functions

1. Factorial of number using recursive functions.


#include<stdio.h>
long factorial(int);
int main()
{
int n;
long f;

printf("Enter an integer to find its factorial\n");


scanf("%d", &n);

if (n < 0)
printf("Factorial of negative integers isn't defined.\n");
else
{
f = factorial(n);
printf("%d! = %ld\n", n, f);
}

return 0;
}

long factorial(int n)
{
if (n == 0)
return 1;
else
return(n * factorial(n-1));
}

Sample Output

Enter an integer to find its factorial


9
9! = 362880
2. Fibonacci Series using Recursive function
#include<stdio.h>
int f(int);

int main()
{
int n, i = 0, c;

printf("Enter the range\n");

scanf("%d", &n);

printf("Fibonacci series terms are:\n");

for (c = 1; c <= n; c++)


{
printf("%d\n", f(i));
i++;
}

return 0;
}

int f(int n)
{
if (n == 0 || n == 1)
return n;
else
return (f(n-1) + f(n-2));
}

Sample Output
Enter the range
8
Fibonacci series terms are:
0
1
1
2
3
5
8
13

3. Linear Search using recursive function


#include<stdio.h>
int linear(int x[],intnum,int position); // function prototype

void main()
{
inti,n,ans;
int a[5];
printf("Enter 5 numbers\n");
for(i=0;i<=4;i++)
{
scanf("%d", &a[i]);
}
printf("\nEnter the number to be searched\n");
scanf("%d",&n);
ans=linear(a,n,0); //function call
if(ans<=4)
{
printf("Number (%d) found at position (%d)",n,ans+1);
}
else
{
printf("Didnot find the number (%d)",n);
}
getch();
}

int linear(int x[], intnum,int position) //function definition


{
if(num==x[position])
{
return position;
}
else
{
position++;
return linear(x,num,position);
}
}

Sample Output

Enter 5 numbers
25
36
45
-1
10

Enter the number to be searched


-1
Number (-1) found at position (4)
4. GCD and LCM using recursive functions
#include <stdio.h>
intgcd(int x, int y); //function prototype

int main()
{
int num1, num2, hcf, lcm;

printf("Enter two integer Values:\n");


scanf("%d %d", &num1, &num2);

hcf = gcd(num1, num2);


printf("GCD: %d", hcf);
printf("\nLCM: %d", (num1 * num2) / hcf);
return 0;
}
//recursive function
intgcd(int x, int y)
{
if (y == 0) //recursion termination condition
{
return x;
}
else
{
returngcd(y, x % y); //calls itself
}
}

Sample Output
Enter two integer Values:
25
36
GCD: 1
LCM: 900

POINTERS
In programming with C, there are far too many things that can only be done with pointers. In
many cases, C programmers use pointers because they make the code more efficient. But
at the same time, pointers seem to make the code harder to understand. However, with
increased power, pointers bring increased responsibility. Pointers allow new and ugly types
of bugs, and pointer bugs can crash in random ways making them more difficult to debug.
Nonetheless, even with their problems, pointers are a powerful programming construct.

Pointers are also variables and play a very important role in C programming language. They
are used for several reasons, such as:
 Strings
 Dynamic memory allocation
 Sending function arguments by reference
 Building complicated data structures
 Pointing to functions
 Building special data structures (i.e. Tree, Tries, etc...)

A pointer is essentially a simple variable which holds a memory address that points to a
value, instead of holding the actual value itself.

Pointer is a variable which holds the address of another variable.

The computer's memory is a sequential store of data, and a pointer points to a specific part of
the memory. Our program can use pointers in such a way that the pointers point to a large
amount of memory - depending on how much we decide to read from that point on.

A simple example to understand how to access the address of a variable without


pointers

In this program, we have a variable num of int type. The value of num is 10 and this value
must be stored somewhere in the memory, right? A memory space is allocated for each
variable that holds the value of that variable; this memory space has an address. For example
we live in a house and our house has an address, which helps other people to find our house.
The same way the value of the variable is stored in a memory address, which helps the C
program to find that value when it is needed.

So let’s say the address assigned to variable num is 0x7fff5694dc58, which means whatever
value we would be assigning to num should be stored at the location: 0x7fff5694dc58. See
the diagram below.

#include <stdio.h>
int main()
{
int num = 10;
printf("Value of variable num is: %d", num);
/* To print the address of a variable we use %p
* format specifier and ampersand (&) sign just
* before the variable name like &num.
*/
printf("\nAddress of variable num is: %p", &num);
return 0;
}
Output:

Value of variable num is: 10


Address of variable num is: 0x7fff5694dc58

A Simple Example of Pointers in C

This program shows how a pointer is declared and used. There are several other things
that we can do with pointers. For now, we just need to know how to link a pointer to the
address of a variable.

Important point to note is: The data type of pointer and the variable must match, an int
pointer can hold the address of int variable, and similarly a pointer declared with float data
type can hold the address of a float variable. In the example below, the pointer and the
variable both are of int type.

#include <stdio.h>
int main()
{
//Variable declaration
int num = 10;

//Pointer declaration
int *p;

//Assigning address of num to the pointer p


p = &num;

printf("Address of variable num is: %p", p);


printf("Content of variable num is: %d", *p);

return 0;
}

Output:
Address of variable num is: 0x7fff5694dc58
content of variable num is: 10

“Address of”(&) Operator


We have already seen in the first example that we can display the address of a variable using
ampersand sign. The &num is used to access the address of variable num. The & operator is
also known as “Address of” Operator.

printf("Address of var is: %p", &num);


Point to note: %p is a format specifier which is used for displaying the address in hex
format.
Pointer is just like another variable, the main difference is that it stores address of another
variable rather than a value.

“Value at Address”(*) Operator


The * Operator is also known as Value at address operator.

How to declare a pointer?


int *p1 /*Pointer to an integer variable*/
double *p2 /*Pointer to a variable of data type double*/
char *p3 /*Pointer to a character variable*/
float *p4 /*pointer to a float variable*/
The above are the few examples of pointer declarations. If you need a pointer to store the
address of integer variable then the data type of the pointer should be int. same case is with
the other data types.
By using * operator we can access the value of a variable through a pointer.

For example:
double a = 10;
double *p;
p = &a;
*p would give us the value of the variable a. The following statement would display 10
as output.
printf("%d", *p);
Similarly if we assign a value to *pointer like this:

*p = 200;
It would change the value of variable a. The statement above will change the value of a
from 10 to 200.

Example program on pointers


#include <stdio.h>
int main()
{
/* Pointer of integer type, this can hold the
* address of a integer type variable.
*/
int *p;

int var = 10;


/* Assigning the address of variable var to the pointer
* p. The p can hold the address of var because var is
* an integer type variable.
*/
p= &var;

printf("Value of variable var is: %d", var);


printf("\nValue of variable var is: %d", *p);
printf("\nAddress of variable var is: %p", &var);
printf("\nAddress of variable var is: %p", p);
printf("\nAddress of pointer p is: %p", &p);
return 0;
}
Output:
Value of variable var is: 10
Value of variable var is: 10
Address of variable var is: 0x7fff5ed98c4c
Address of variable var is: 0x7fff5ed98c4c
Address of pointer p is: 0x7fff5ed98c50

Can you guess the output of following C program?

#include <stdio.h>
int main()
{
int var =10;
int *p;
p= &var;

printf ( "Address of var is: %p", &var);


printf ( "\nAddress of var is: %p", p);

printf ( "\nValue of var is: %d", var);


printf ( "\nValue of var is: %d", *p);
printf ( "\nValue of var is: %d", *( &var));

/* Note I have used %p for p's value as it represents an address*/


printf( "\nValue of pointer p is: %p", p);
printf ( "\nAddress of pointer p is: %p", &p);

return 0;
}
Output:

Address of var is: 0x7fff5d027c58


Address of var is: 0x7fff5d027c58
Value of var is: 10
Value of var is: 10
Value of var is: 10
Value of pointer p is: 0x7fff5d027c58
Address of pointer p is: 0x7fff5d027c50

Pointer to Array
Consider the following program:
#include<stdio.h>

int main()
{
int arr[5] = { 1, 2, 3, 4, 5 };
int *ptr = arr;

printf("%p\n", ptr); //display the starting address of array


return 0;
}

In this program, we have a pointer ptr that points to the 0th element of the array. Similarly,
we can also declare a pointer that can point to whole array instead of only one element of the
array. This pointer is useful when talking about multidimensional arrays.

Syntax:
data_type (*var_name)[size_of_array];

Example:
int (*ptr)[10];
Here ptr is pointer that can point to an array of 10 integers. Since subscript have higher
precedence than indirection, it is necessary to enclose the indirection operator and pointer
name inside parentheses. Here the type of ptr is ‘pointer to an array of 10 integers’.
The pointer that points to the 0th element of array and the pointer that points to the whole
array are totally different. The following program shows this:

// C program to understand difference between // pointer to an integer and pointer to an


// array of integers.
#include<stdio.h>
int main()
{
// Pointer to an integer
int *p;

// Pointer to an array of 5 integers


int (*ptr)[5];
int arr[5];
// Points to 0th element of the arr.
p = arr;
// Points to the whole array arr.
ptr = &arr;
printf("p = %p, ptr = %p\n", p, ptr);

p++; //address increased by size of the datatype


ptr++; //address increased by size of the entire array

printf("p = %p, ptr = %p\n", p, ptr);


getch();
}
Output:
p = 0x7fff4f32fd50, ptr = 0x7fff4f32fd50
p = 0x7fff4f32fd54, ptr = 0x7fff4f32fd70
When ptr is incremented, it increments by the size of the array than just one integer.

Pointer Arithmetic:
C language provides a set of operators to perform arithmetic and comparison of memory
addresses. Pointer arithmetic and comparison in C is supported by following operators -
1. Increment and decrement ++ and --
2. Addition and Subtraction + and -
3. Comparison <, >, <=, >=, ==, !=

If a pointer ptr is declared to a particular data type then the pointer arithmetic for
addition/subtraction or increment/decrement operations would follow the below equation.

ptr++;

which is equivalent of
ptr = ptr + 1*size of data type

if data type is float and ptr was holding a initial value of 2100 the ptr++ would result in 2104
as the size of the data type float is 4.

Similarly if ptr = ptr + x

Where x is integer value, the above equation would result in


ptr = ptr + x * size of data type

Example: for integer variable on 32 bit machine where int is 4 bytes and ptr is 2100

ptr = ptr + 20; would result in

ptr = ptr + 20 * size of int


ptr = ptr + 20 * 4;
2100 = 2100 + 80;
New ptr = 2180

Pointer arithmetic in case of arrays

Pointers do not have to point to single variables. They can also point at the cells of an array.
For example, we can write

int *ip;
int a[10];
ip = &a[3];
and we would end up with ip pointing at the fourth cell of the array a (remember, arrays are
0-based, so a[0] is the first cell). We could illustrate the situation like this:

We'd use this ip just like the one in the previous section: *ip gives us what ip points to, which
in this case will be the value in a[3].
Once we have a pointer pointing into an array, we can start doing pointer arithmetic. Given
that ip is a pointer to a[3], we can add 1 to ip:

ip + 1
What does it mean to add one to a pointer? In C, it gives a pointer to the cell one farther on,
which in this case is a[4]. To make this clear, let's assign this new pointer to another pointer
variable:
ip2 = ip + 1;
Now the picture looks like this:

If we now do
*ip2 = 4;
we've set a[4] to 4. But it's not necessary to assign a new pointer value to a pointer variable in
order to use it; we could also compute a new pointer value and use it immediately:
*(ip + 1) = 5;
In this last example, we've changed a[4] again, setting it to 5. The parentheses are needed
because the unary ``contents of'' operator * has higher precedence (i.e., binds more tightly
than) the addition operator. If we wrote *ip + 1, without the parentheses, we'd be fetching the
value pointed to by ip, and adding 1 to that value. The expression *(ip + 1), on the other
hand, accesses the value one past the one pointed to by ip.
Given that we can add 1 to a pointer, it's not surprising that we can add and subtract other
numbers as well. If ip still points to a[3], then
*(ip + 3) = 7;
sets a[6] to 7, and
*(ip - 2) = 4;
sets a[1] to 4.

Program to print an array elements using pointer


#include<stdio.h>
#include<conio.h>
int main()
{
// Pointer to an integer
int arr[5]= {1,2,3,4,5};
int *p;
int i;
p=arr;
printf("array elements using pointers\n");
for(i=0; i<5;i++)
printf("\n *(p + %d): = %d", i, *(p+i));

printf("\narray elements using array name as an address\n");


for(i=0; i<5;i++)
printf("\n *(arr + %d): = %d", i, *(arr+i));
getch();
}

Output:

You might also like