Professional Documents
Culture Documents
UNIT – III
FUNCTIONS AND POINTERS Introduction to functions: Function prototype, function definition, function
call, Built-in functions (string functions, math functions) – Recursion – Example Program: Computation of
Sine series, Scientific calculator using built-in functions, Binary Search using recursive functions – Pointers
– Pointer operators – Pointer arithmetic – Arrays and pointers – Array of pointers – Example Program:
Sorting of names – Parameter passing: Pass by value, Pass by reference – Example Program: Swapping of
two numbers and changing the value of a variable using pass by reference
#include <stdio.h>
void functionName()
{
... .. ...
... .. ...
}
int main()
{
... .. ...
... .. ...
functionName();
... .. ...
... .. ...
}
54
CS8251 Programming in C
void functionName()
And, the compiler starts executing the codes inside the user-defined function.
The control of the program jumps to statement next to functionName(); once all the codes inside the function
definition are executed.
A function is a block of code that performs a specific task.
C allows you to define functions according to your need. These functions are known as user-defined
functions. For example:
Suppose, you need to create a circle and color it depending upon the radius and color.
You can create two functions to solve this problem:
createCircle() function
color() function
Example: User-defined function
Here is a example to add two integers. To perform this task, a user-defined function addNumbers() is
defined.
#include <stdio.h>
int addNumbers(int a, int b); // function prototype
int main()
{
int n1,n2,sum;
printf("Enters two numbers: ");
scanf("%d %d",&n1,&n2);
sum = addNumbers(n1, n2); // function call
printf("sum = %d",sum);
return 0;
}
int addNumbers(int a,int b) // function definition
{
int result;
result=a+b;
return result; //return statement
}
In the above example, int addNumbers(int a, int b); is the function prototype which provides
following information to the compiler:
1. name of the function is addNumbers()
2. return type of the function is int
3. two arguments of type int are passed to the function
The function prototype is not needed if the user-defined function is defined before the main ()
function.
55
CS8251 Programming in C
When a function is called, the control of the program is transferred to the function definition. And, the
compiler starts executing the codes inside the body of a function.
3.1.3 Function Call
Control of the program is transferred to the user-defined function by calling it.
Syntax of function call
In the above example, function call is made using addNumbers(n1,n2); statement inside the main().
The type of arguments passed to a function and the formal parameters must match, otherwise the compiler
throws error.
If n1 is of char type, a also should be of char type. If n2 is of float type, variable b also should be of float
type.
A function can also be called without passing an argument.
56
CS8251 Programming in C
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 return statement.
In the above example, the value of variable result is returned to the variable sum in the main() function.
Syntax of return statement
return (expression);
For example,
return a;
return (a+b);
The type of value returned from the function and the return type specified in
function prototype and function definition must match
return 0;
}
// return type of the function is void becuase no value is returned from the function void
checkPrimeNumber()
{
int n, i, flag=0;
printf("Enter a positive integer: ");
scanf("%d",&n);
for(i=2; i <= n/2; ++i)
{
if(n%i == 0)
{
flag = 1;
}
}
if (flag == 1)
printf("%d is not a prime number.", n);
else
printf("%d is a prime number.", n);
}
The checkPrimeNumber() function takes input from the user, checks whether it is a prime number or
not and displays it on the screen.
The empty parentheses in checkPrimeNumber(); statement inside the main()function indicates that no
argument is passed to the function.
The return type of the function is void. Hence, no value is returned from the function.
The empty parentheses in n = getInteger(); statement indicates that no argument is passed to the
function. And, the value returned from the function is assigned to n. Here, the getInteger() function
takes input from the user and returns it. The code to check whether a number is prime or not is inside
the main() function.
break;
}
}
if(flag == 1)
printf("%d is not a prime number.",n);
else
printf("%d is a prime number.", n);
}
The integer value entered by the user is passed to checkPrimeAndDisplay()function. Here, the
checkPrimeAndDisplay() function checks whether the argument passed is a prime number or not and
displays the appropriate message.
int n, flag;
printf("Enter a positive integer: ");
scanf("%d",&n);
// n is passed to the checkPrimeNumber() function
// the value returned from the function is assigned to flag variable flag =
checkPrimeNumber(n);
if(flag==1)
printf("%d is not a prime number",n);
else
printf("%d is a prime number",n);
return 0;
}
// integer is returned from the function int
checkPrimeNumber(int n)
{
/* Integer value is returned from function checkPrimeNumber() */ int i;
for(i=2; i <= n/2; ++i)
{
if(n%i == 0)
return 1;
}
return 0;
}
Function Description
floor ( ) This function returns the nearest integer which is less than or equal
to the argument passed to this function.
round ( ) This function returns the nearest integer value of the
float/double/long double argument passed to this function. If decimal
value is from “.6 to .9”, it returns the integer value greater than the
argument.
ceil ( ) This function returns nearest integer value which is greater than or
equal to the argument passed to this function.
sin ( ) This function is used to calculate sine value.
cos ( ) This function is used to calculate cosine.
cosh() This function is used to calculate hyperbolic cosine.
exp() This function is used to calculate the exponential “e” to the xth
power.
tan() This function is used to calculate tangent.
tanh() This function is used to calculate hyperbolic tangent.
sinh() This function is used to calculate hyperbolic sine.
log() This function is used to calculate natural logarithm.
Log10() This function is used to calculate base 10 logarithm
sqrt ( ) This function is used to find square root of the argument passed
to this function.
pow() This is used to find the power of the given number.
trunc.(.) This function truncates the decimal value from floating point value
and returns integer value.
61
CS8251 Programming in C
3.2 Recursion
Recursion is the process of repeating items in a self-similar way. In programming languages, if a program
allows you to call a function inside the same function, then it is called a recursive call of the function.
void recursion() {
recursion(); /* function calls itself */
}
int main() {
recursion();
}
62
CS8251 Programming in C
The C programming language supports recursion, i.e., a function to call itself. But while using recursion,
programmers need to be careful to define an exit condition from the function, otherwise it will go into an
infinite loop.
Recursive functions are very useful to solve many mathematical problems, such as calculating the factorial
of a number, generating Fibonacci series, etc. Number Factorial
The following example calculates the factorial of a given number using a recursive function −
#include <stdio.h>
int main() {
int i = 12;
printf("Factorial of %d is %d\n", i, factorial(i)); return 0;
}
When the above code is compiled and executed, it produces the following result −
Factorial of 12 is 479001600
Fibonacci Series
The following example generates the Fibonacci series for a given number using a recursive function −
#include <stdio.h>
int fibonacci(int i) {
if(i == 0) {
return 0;
}
if(i == 1) {
return 1;
}
return fibonacci(i-1) + fibonacci(i-2);
}
int main() {
int i;
for (i = 0; i < 10; i++) {
printf("%d\t\n", fibonacci(i));
}
return 0;
}
When the above code is compiled and executed, it produces the following result −
0
1
1
2
3
5
8
13
63
CS8251 Programming in C
21
34
For example,
Let the value of x be 30.
64
CS8251 Programming in C
Working:
First the computer reads the value of „x‟ and „n‟ from the user.
Then „x‟ is converted to radian value.
Then using for loop the value of Sin(x) is calculate.
Finally the value of Sin(x) is printed.
Step by Step working of the above Program Code:
Let us assume that the user enters the value of „x‟ as 45 and „n‟ as 4.
1. Converting „x‟ to radian value
x = x * 3.14159 / 180(x = 45 * 3.14159 / 180) So, x=0.785398
2. It assigns t=x and sum=x (i.e. t=0.785398 and sum=0.785398)
3. It assigns the value of i=1 and the loop continues till the condition of the for loop is true.
3.1.i<=n (1<=4) for loop condition is true
t = (0.785398 * (-1) * 0.785398 * 0.785398)/(2 * 1 * (2 * 1 + 1))
So, t = – 0.08074
sum = 0.785398 + (- 0.08074)
So, sum=0.70465
i++
So, i=2
3.2. i<=n (2<=4) for loop condition is true
t = (- 0.08074 * (-1) * 0.785398 * 0.785398)/(2 * 2 * (2 * 2 + 1))
So, t = 0.00249
sum = 0.70465 + 0.00249
So, sum=0.70714
i++
So, i=3
3.3. i<=n (3<=4) for loop condition is true
t = (0.00249 * (-1) * 0.785398 * 0.785398)/(2 * 3 * (2 * 3 + 1))
So, t = – 0.000032
sum = 0.70714 + (- 0.000032)
So, sum=0.707108
i++
So, i=4
3.4. i<=n (4<=4) for loop condition is true
t = (- 0.000032 * (-1) * 0.785398 * 0.785398)/(2 * 4 * (2 * 4 + 1))
So, t = 0.000000274
sum = 0.707108 + 0.000000274
So, sum=0.707108274
i++
So, i=5
3.5. i<=n (5<=4) for loop condition is false
It comes out of the for loop.
4. Finally it prints The value of Sin(0.785398) = 0.7071
5. Thus program execution is completed.
Output:
Enter the value for x: 45
Enter the value for m: 5
The value of sin(0.7853920)=0.7071
3.3.3 Binary Search using Recursion
/** C Program to Perform Binary Search using Recursion*/
#include <stdio.h>
void binary_search(int [], int, int, int);
65
CS8251 Programming in C
3.4 Pointers
Pointers in C are easy and fun to learn. Some C programming tasks are performed more easily with pointers,
and other tasks, such as dynamic memory allocation, cannot be performed without using pointers. So it
becomes necessary to learn pointers to become a perfect C programmer. Let's start learning them in simple
and easy steps.
As you know, every variable is a memory location and every memory location has its address defined which
can be accessed using ampersand (&) operator, which denotes an address in memory. Consider the
following example, which prints the address of the variables defined −
#include <stdio.h>
int main ()
{
int var1;
char var2[10];
printf("Address of var1 variable: %x\n", &var1 );
printf("Address of var2 variable: %x\n", &var2 );
return 0;
}
When the above code is compiled and executed, it produces the following result −
Address of var1 variable: bff5a400
Address of var2 variable: bff5a3f6
What are Pointers?
A pointer is a variable whose value is the address of another variable, i.e., direct address of the memory
location. Like any variable or constant, you must declare a pointer before using it to store any variable
address. The general form of a pointer variable declaration is −
type *var-name;
Here, type is the pointer's base type; it must be a valid C data type and var-name is the name of the
pointer variable. The asterisk * used to declare a pointer is the same asterisk used for multiplication.
However, in this statement the asterisk is being used to designate a variable as a pointer. Take a look at
some of the valid pointer declarations −
int *ip; /* pointer to an integer */
double *dp; /* pointer to a double */
float *fp; /* pointer to a float */
char *ch /* pointer to a character */
The actual data type of the value of all pointers, whether integer, float, character, or otherwise, is the
same, a long hexadecimal number that represents a memory address. The only difference between
pointers of different data types is the data type of the variable or constant that the pointer points to.
67
CS8251 Programming in C
68
CS8251 Programming in C
In order to create pointer to a variable we use “*” operator and to find the address of Variable we use “&”
operator.
Don‟t Consider “&” and “*” operator as Logical AND and Multiplication Operator in Case of Pointer.
Important Notes :
1. „&‟ operator is called as address Operator
2. ‘*’ is called as ‘Value at address’ Operator
3. „Value at address’ Operator gives „Value stored at Particular address.
4. ‘Value at address’ is also called as ‘Indirection Operator’
Pointer Operators :
#include<stdio.h>
int main()
{
int n = 20;
printf("\nThe address of n is %u",&n);
printf("\nThe Value of n is %d",n);
printf("\nThe Value of n is %d",*(&n));
}
Output:
The address of n is 1002
The Value of n is 20
The Value of n is 20
How *(&n) is same as printing the value of n ?
&n Gives address of the memory location whose name is „n‟
So Ccompiler must provide space for it in memory.Below is Step by Step Calculation to compute the value –
m = * ( &n )
= * ( Address of Variable 'n')
= * ( 1000 )
= Value at Address 1000
= 20
What Does following declaration tells compiler?
int *ptr;
1. „ptr‟ is declared as that „ptr‟ will be used only for storing the address of the integer valued variables
2. We can also say that „ptr‟ points to integer
3. Value at the address contained in „ptr‟ is integer .
S. Memory
no. Declaration Explanation Required
p is going to store address of
1 int *p integer value 2 bytes
q is going to store address of
2 float *q floating value 2 bytes
ch is going to store address of
3 char *ch character variable 2 bytes
69
CS8251 Programming in C
Decrementing a Pointer
The same considerations apply to decrementing a pointer, which decreases its value by the number of bytes
of its data type as shown below −
#include <stdio.h>
const int MAX = 3;
int main () {
int var[] = {10, 100, 200};
int i, *ptr;
/* let us have array address in pointer */
ptr = &var[MAX-1];
for ( i = MAX; i > 0; i--) {
70
CS8251 Programming in C
Pointer Comparisons
Pointers may be compared by using relational operators, such as ==, <, and >. If p1 and p2 point to
variables that are related to each other, such as elements of the same array, then p1 and p2 can be
meaningfully compared.
The following program modifies the previous example − one by incrementing the variable pointer so
long as the address to which it points is either less than or equal to the address of the last element of the
array, which is &var[MAX - 1] −
#include <stdio.h>
const int MAX = 3;
int main () {
int var[] = {10, 100, 200};
int i, *ptr;
/* let us have address of the first element in pointer */
ptr = var;
i = 0;
while ( ptr <= &var[MAX - 1] ) {
printf("Address of var[%d] = %x\n", i, ptr );
printf("Value of var[%d] = %d\n", i, *ptr );
/* point to the previous location */
ptr++;
i++;
}
return 0;
}
When the above code is compiled and executed, it produces the following result –
Address of var[0] = bfdbcb20
Value of var[0] = 10
Address of var[1] = bfdbcb24
Value of var[1] = 100
Address of var[2] = bfdbcb28
Value of var[2] = 200
71
CS8251 Programming in C
int arr[4];
In C programming, name of the array always points to address of the first element of an array.
In the above example, arr and &arr[0] points to the address of the first element. &arr[0] is
equivalent to arr Since, the addresses of both are the same, the values of arr and &arr[0] are also
the same.
arr[0] is equivalent to *arr (value of an address of the pointer)
Similarly,
&arr[1] is equivalent to (arr + 1) AND, arr[1] is equivalent to *(arr + 1).
&arr[2] is equivalent to (arr + 2) AND, arr[2] is equivalent to *(arr + 2).
&arr[3] is equivalent to (arr + 3) AND, arr[3] is equivalent to *(arr + 3).&arr[i] is equivalent to (arr
+ i) AND, arr[i] is equivalent to *(arr + i).
In C, you can declare an array and can use pointer to alter the data of an array.
Example: Program to find the sum of six numbers with arrays and pointers
#include <stdio.h>
int main()
{
int i, classes[6],sum = 0;
72
CS8251 Programming in C
printf("Enter 6 numbers:\n");
for(i = 0; i < 6; ++i)
{
// (classes + i) is equivalent to &classes[i]
scanf("%d",(classes + i));
Enter 6 numbers:
2
3
4
5
3
4
Sum = 21
When the above code is compiled and executed, it produces the following result −
Value of var[0] = 10
Value of var[1] = 100
Value of var[2] = 200
There may be a situation when we want to maintain an array, which can store pointers to an int or char or
any other data type available. Following is the declaration of an array of pointers to an integer −
int *ptr[MAX];
It declares ptr as an array of MAX integer pointers. Thus, each element in ptr, holds a pointer to an int
value. The following example uses three integers, which are stored in an array of pointers, as follows −
#include <stdio.h>
73
CS8251 Programming in C
int main () {
return 0;
}
When the above code is compiled and executed, it produces the following result −
Value of var[0] = 10
Value of var[1] = 100
Value of var[2] = 200
You can also use an array of pointers to character to store a list of strings as follows − #include <stdio.h>
const int MAX = 4;
int main () {
char *names[] = {
"Zara Ali",
"Hina Ali",
"Nuha Ali",
"Sara Ali"
};
int i = 0;
for ( i = 0; i < MAX; i++) {
printf("Value of names[%d] = %s\n", i, names[i] );
}
return 0;
}
When the above code is compiled and executed, it produces the following result −
Value of names[0] = Zara Ali
Value of names[1] = Hina Ali
Value of names[2] = Nuha Ali
Value of names[3] = Sara Ali
74
CS8251 Programming in C
int main(){
int i,j,count;
char str[25][25],temp[25];
puts("How many strings u are going to enter?: ");
scanf("%d",&count);
puts("Enter Strings one by one: ");
for(i=0;i<=count;i++)
gets(str[i]);
for(i=0;i<=count;i++)
for(j=i+1;j<=count;j++){
if(strcmp(str[i],str[j])>0){
strcpy(temp,str[i]);
strcpy(str[i],str[j]);
strcpy(str[j],temp);
}
}
printf("Order of Sorted Strings:");
for(i=0;i<=count;i++)
puts(str[i]);
return 0;
}
Output:
How many strings u are going to enter?: 3
Enter Strings one by one:
john
Arul
Peter
Order of Sorted Strings:
Arul
Peter
John
3.10 Parameter passing
There are different ways in which parameter data can be passed into and out of methods and functions. Let us
assume that a function B() is called from another function A(). In this case A is called the “caller function”
and B is called the “called
function or callee function”. Also, the arguments which A sends to B are called actual arguments and the
parameters of B are called formal arguments.
Terminology
Formal Parameter : A variable and its type as they appear in the prototype of the function or method.
Actual Parameter : The variable or expression corresponding to a formal parameter that appears in the
function or method call in the calling environment.
Modes:
IN: Passes info from caller to calle.
OUT: Callee writes values in caller.
IN/OUT: Caller tells callee value of variable, which may be updated by callee.
Important methods of Parameter Passing
3.10.1 Pass By Value : This method uses in-mode semantics. Changes made to formal parameter do not get
transmitted back to the caller. Any modifications to the formal parameter variable inside the called
function or method affect only the separate storage location and will not be reflected in the actual
parameter in the calling environment. This method is also called as call by value.
// C program to illustrate
75
CS8251 Programming in C
// call by value
#include <stdio.h>
void func(int a, int b)
{
a += b;
printf("In func, a = %d b = %d\n", a, b);
}
int main(void)
{
int x = 5, y = 7;
Output:
In func, a = 12 b = 7
In main, x = 5 y = 7
Shortcomings:
Inefficiency in storage allocation
For objects and arrays, the copy semantics are costly
3.10.2 Pass by reference(aliasing) :
This technique uses in/out-modesemantics. Changes made to formal parameter do get transmitted back to the
caller through parameter passing. Any changes to the formal parameter are reflected in the
actual parameter in the calling environment as formal parameter receives a reference (or pointer) to the actual
data. This method is also called as <em>call by reference. This method is efficient in both time and space.
// C program to illustrate
// call by reference
// #include <stdio.h>
void swapnum(int* i, int* j)
{
int temp = *i;
*i = *j;
*j = temp;
}
int main(void)
{
int a = 10, b = 20;
// passing parameters
swapnum(&a, &b);
printf("a is %d and b is %d\n", a, b);
return 0;
}
Output:
a is 20 and b is 10
76
CS8251 Programming in C
Output of program:
Enter the value of x and y: 3 5
Before Swapping
x=3
y=5
After Swapping
x=5
y=3
3.11.2 Changing the value of a variable using pass by reference
#include <stdio.h>
void swap(int*, int*); //Swap function declaration
int main()
{
int x, y;
printf("Enter the value of x and y\n");
scanf("%d%d",&x,&y);
printf("Before Swapping\nx = %d\ny = %d\n", x, y);
swap(&x, &y);
printf("After Swapping\nx = %d\ny = %d\n", x, y);
return 0;
}
//Swap function definition
void swap(int *a, int *b)
{
int t;
t = *b; *b =*a; *a
= t;
}
Output of program:
Enter the value of x and y: 3 5
Before Swapping
x=3
y=5
After Swapping
x=5
y=3
77