MODULE 4 Functions and Pointers
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.
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.
In C Programming, as per our requirement, we can define the User defined functions in
multiple ways
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.
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;
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;
}
void main()
{
int a, b;
Sum = a + b;
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;
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.
solve it directly
else
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
int main()
{
int n, i = 0, c;
scanf("%d", &n);
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
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();
}
Sample Output
Enter 5 numbers
25
36
45
-1
10
int main()
{
int num1, num2, hcf, lcm;
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.
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.
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:
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;
return 0;
}
Output:
Address of variable num is: 0x7fff5694dc58
content of variable num is: 10
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.
#include <stdio.h>
int main()
{
int var =10;
int *p;
p= &var;
return 0;
}
Output:
Pointer to Array
Consider the following program:
#include<stdio.h>
int main()
{
int arr[5] = { 1, 2, 3, 4, 5 };
int *ptr = arr;
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:
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.
Example: for integer variable on 32 bit machine where int is 4 bytes and ptr is 2100
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.
Output: