C Programming: Functions and Pointers Guide
C Programming: Functions and Pointers Guide
Library functions are predefined functions. These functions are already developed
by someone and are available to the user for use. Ex. printf( ), scanf( ).
2. User-defined functions
User-defined functions are defined by the user at the time of writing a program.
Ex. sum( ), square( )
Using Functions
A function can be compared to a black box that takes in inputs, processes it, and
then outputs the
result. Terminologies using functions are:
A function f that uses another function g is known as the calling function,
and g is known as the called function.
The inputs that a function takes are known as arguments.
When a called function returns some result back to the calling function, it is
said to return that result.
The calling function may or may not pass parameters to the called function.
If the called function accepts arguments, the calling function will pass
parameters, else not.
Function declaration is a declaration statement that identifies a function’s
name, a list of arguments that it accepts, and the type of data it returns.
Function definition consists of a function header that identifies the function,
followed by the body of the function containing the executable code for that
function.
statement prior to its use enables the compiler to make a check on the arguments
used while calling that function.
Syntax:
return_data_type function_name(data_type variable1, data_type variable2,..);
Here, function_name is a valid name for the function. Naming a function
follows the same rules that are followed while naming variables. A function should
have a meaningful name that must specify the task that the function will perform.
return_data_type specifies the data type of the value that will be returned
to the calling function as a result of the processing performed by the called
function.
(data_type variable1, data_type variable2, ...) is a list of variables of
specified data types.
These variables are passed from the calling function to the called function.
They are also known as arguments or parameters that the called function accepts to
perform its task.
}
While return_data_type function_name(data_type variable1, data_type
variable2,...) is known as the function header, the rest of the portion comprising of
program statements within the curly brackets { } is the function body which
contains the code to perform the specific task.
Note that the function header is same as the function declaration. The only
difference between the two is that a function header is not followed by a semi-
colon.
Working of a function
void main()
{
int x,y,z;
int abc(int, int, int) // Function declaration
…..
…..
abc(x,y,z) // Function Call
… Actual arguments
…
}
strcpy(string1, "Hello");
strcpy(string2, "Hellooo");
printf("Length of string1 : %d\n", strlen( string1 ));
printf("Length of string2 : %d\n", strlen( string2 ));
return 0;
}
Output:
Length of string1 : 5
Length of string2 : 7
#include <stdio.h>
int main() {
char input_str[20];
char *output_str;
strcpy(input_str, "Hello");
printf("input_str: %s\n", input_str);
output_str = strcpy(input_str, "World");
printf("input_str: %s\n", input_str);
printf("output_str: %s\n", output_str);
return 0;
}
Output:
input_str: Hello
input_str: World
output_str: World
Output:
The names are different
string functions
3.6 Recursion
A function that calls itself is known as a recursive function. Recursion is a process
by which a function calls itself repeatedly until some specified condition has been
satisfied.
…
…
A( );// function B calls A
…
}
Consider the calculation of 6! ( 6 factorial )
ie 6! = 6 * 5 * 4 * 3 * 2 * 1
6! = 6 * 5!
6! = 6 * ( 6 - 1 )!
n! = n * ( n - 1 )!
Example: Write a program to print Fibonacci series using recursion
#include<stdio.h> // include stdio.h library
int fibonacci(int);
int main(void)
{
int terms;
printf("Enter terms: ");
scanf("%d", &terms);
for(int n = 0; n < terms; n++)
{
printf("%d ", fibonacci(n));
}
return 0; // return 0 to operating system
}
int fibonacci(int num)
{
//base condition
if(num == 0 || num == 1)
{
return num;
}
else
{
// recursive call
return fibonacci(num-1) + fibonacci(num-2);
}
}
Output:
Enter terms: 20
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181
Types of Recursion
Direct Recursion
A function is said to be directly recursive if it explicitly calls itself. Here, the
function Func() calls itself for all positive values of n, so it is said to be a directly
recursive function.
int Func (int n)
{
if (n == 0)
return n;
else
return (Func (n–1));
}
Indirect Recursion
Tail Recursion
A recursive function is said to be tail recursive if no operations are pending to be
performed when the recursive function returns to its caller. When the called
function returns, the returned value is immediately returned from the calling
function.
int Fact(int n)
{
if (n == 1)
return 1;
else
return (n * Fact(n–1));
}
E.g. Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int fact(int);
int n,f;
printf(“Enter the number \n”);
scanf(“%d”,&n);
f=fact(n);
printf(“The factorial of a number =%d”,f);
getch();
}
int fact(int n)
{
if(n==1)
return(1);
else
return n*fact(n-1);
}
OUTPUT
Enter the number to find the factorial
5
The factorial of a number=120
Fibonacci(4) = 2 + 1 = 3
Fibonacci(5) = 3 + 2 = 5
Fibonacci(6) = 3 + 5 = 8
Fibonacci(7) = 5 + 8 = 13
Tower of Hanoi
The tower of Hanoi is one of the main applications of recursion. It says, ‘if
you can solve n–1 cases, then you can easily solve the nth case’. The figure (a)
below shows three rings mounted on pole A. The problem is to move all these
rings from pole A to pole C while maintaining the same order. The main issue is
that the smaller disk must always come above the larger disk.
In our case, A is the source pole, C is the destination pole, and B is the spare
pole. To transfer all the three rings from A to C, we will first shift the upper two
rings (n–1 rings) from the source pole to the spare pole. We move the first two
rings from pole A to B as shown in figure (b) .
Now that n–1 rings have been removed from pole A, the nth ring can be
easily moved from the source pole (A) to the destination pole (C). Figure (c) shows
this step.
The final step is to move the n–1 rings from the spare pole (B) to the
destination pole (C). This is shown in Fig. (d)
To summarize, the solution to our problem of moving n rings from A to C using B
as spare can be given as:
Base case: if n=1
Figure (a)
Figure (b)
Figure (c)
Figure (d)
sum = sum + t ;
}
printf("\nSine value of %f is : %8.4f", val, sum) ;
getch() ;
}
Output:
Enter the value for x : 30
Enter the value for n : 20
Sine value of 30.000000 is : 0.5000
printf("[Link] [Link] 3. tan 4. sinh [Link] [Link] 7.1og10 8. square root. [Link]
[Link]."); scanf ("%d",&n);
if (n<9 && n>0)
{
printf("\n What is x? ");
scanf("%f",&x);
switch (n)
{
case 1: answer = sine(x);
break;
case 2: answer = cosine(x);
break;
case 3: answer = tangent(x);
break;
case 4: answer = sineh(x);
break;
case 5: answer = cosineh(x);
break;
case 6: answer = tangenth(x);
break;
case 7: answer = logten(x);
break;
case 8: answer = squareroot(x);
break;
case 9: answer = exponent(x);
break;
}}
if (n==10)
{
printf("What is x and y?\n");
scanf("%f%f",&x,&y);
answer = power(x,y);
}
if (n>0 && n<11)
printf("%f",answer);
else
printf("Wrong input.\n");
return 0;
}
float sine(float x)
{ return (sin (x*PI/180));
}
float cosine(float x)
{ return (cos (x*PI/180));
}
float tangent(float x)
{ return (tan(x*PI/180));
}
float sineh(float x)
{ return (sinh(x));
}
float cosineh(float x)
{ return (sinh(x));
}
float tangenth(float x)
{ return (sinh(x));
}
float logten(float x)
{ return (log10(x));
}
float squareroot(float x)
{ return (sqrt(x));
}
float exponent(float x)
{ return(exp(x));
}
float power(float x, float y)
{ return (pow(x,y));
}
int a[10],i,n,m,c,l,u;
l=0,u=n-1;
c=binary(a,n,m,l,u);
if(c==0)
printf("Number is not found.");
else
printf("Number is found.");
return 0;
}
}
else
return binary(a,n,m,mid+1,u);
}
else
return c;
}
Output:
Enter the size of an array: 5
Enter the elements of the array: 8 9 10 11 12
Enter the number to be search: 8
Number is found.
3.8 Pointers
Definition:
A pointer is a variable that stores the address of a variable or a function
Advantages
1. Pointers save memory space
2. Faster execution
3. Memory is accessed efficiently.
Declaration
datatype *pointername;
int a=10; p a
int *p=&a;
2000 10
4000 2000
Pointer to pointer
A pointer that holds the address of another pointer variable is known as a
pointer to pointer.
E.g.
int **p;
6000
6000 pptr
8000
So **pptr=12
a 12.5
1000 1000
P
2000
2. Dereferencing a pointer
Eg) int b;
int a=12;
a 12 int *p;
1000 p=&a;
b=*p; \\value pointed by p(or)value
1000 at 1000=12,
p so b=12
2000
Example program
#include<stdio.h>
void main() Note
{
int a=12; %p is used for addresses;
int *p; %u can also be used.
int **pptr;
*p=value at p
p=&a;
=value at (1000)=12
pptr=&p;
printf(“a value=%d”,a); *pptr=value at(pptr)
printf(“value by dereferencing p is %d \n”,*p); =value at(value at
printf(“value by dereferencing pptr is %d \n”,**pptr); (2000))
printf(“value of p is %u \n”,p); =value at (1000)=12
printf(“value of pptr is %u\n”,pptr);
}
Output:
a value=12
value by dereferencing p is 12
value by dereferencing pptr is 12
value of p is 1000
value of pptr is 2000
a 12
1000 p 1000
3000
1. Addition
(i) An addition of int type can be added to an expression of pointer type. The result
is pointer type.(or)A pointer and an int can be added.
Pre-
increment
Result =
initial value
of pointer +
sizeof (T)
Eg. post float* - float* ftr=p++ ftr=? ftr=2000
increment p=2000 p=2004 Value of ptr
= Value of
ptr
+sizeof(T)
3 - Pointer int Pointer Result =
to type to type initial value
T T of ptr - int
operand *
sizeof (T)
E.g. float* int float* p=p-1 p=2000 1996 2000 – 1 *
4 = 2000-
4=1996
4 -- Pointer Pointer Post
to type - to type decrement
T T Result =
initial value
of pointer
Pre-
decrement
Result =
initial value
of pointer –
sizeof(T)
[Link] float* - float* ftr=--p ftr=? ftr=1996
decrement p=2000 p=1996 Value of ptr
= Value of
ptr –
sizeof(T)
#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
10 20 30
Example:
Now look at another code in which we store the address of three individual arrays
in the array of pointers:
int main()
{
int arr1[]={1,2,3,4,5};
int arr2[]={0,2,4,6,8};
int arr3[]={1,3,5,7,9};
int *parr[3] = {arr1, arr2, arr3};
int i;
for(i = 0;i<3;i++)
printf(«%d», *parr[i]);
return 0;
}
Output
101
for(i=0;i<n;i++)
{
printf("Enter the Strings %d : ",i+1);
x[i]=(char *)malloc(20*sizeof(char));
scanf("%s",x[i]);
}
reorder(n,x);
printf("\nreorder list is : \n");
for(i=0;i<n;i++)
{
printf("%d %s\n",i+1,x[i]);
}
getch();
}
void reorder(int n,char *x[])
{
int i,j;
char t[20];
for(i=0;i<n-1;i++)
for(j=i+1;j<n;j++)
if(strcmp(x[i],x[j])>0)
{
strcpy(t,x[j]);
strcpy(x[j],x[i]);
strcpy(x[i],t);
}
return;
}
Output:
Enter no. of string 5
Enter the Strings 1 kailash
Enter the Strings 2 Aswin
Enter the Strings 3 Zulphia
Enter the Strings 4 Babu
Enter the Strings 5 Clinton
Reorder list is
Aswin
Babu
Clinton
kailash
Clinton
E.g. Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b;
Main function
a b
10 20
1000 1002
Swap function
a1 b1
10 20
2000 2002
After swap function
a1 b1
20 10
2000 2002
Example Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b;
Main function
a b
10 20
1000 1002
Swap function
a1 b1
1000 1002
2000 2002
After swap function
a b
20 10
1000 1002
3.15 Example Program: Swapping of two numbers and changing the value of
a variable using pass by reference
#include<stdio.h>
#include<conio.h>
void swap(int *num1, int *num2);
void main() {
int x, y;
printf("\nEnter First number : ");
scanf("%d", &x);
printf("\nEnter Second number : ");
scanf("%d", &y);
printf("\nBefore Swaping x = %d and y = %d", x, y);
swap(&x, &y); // Function Call - Pass By Reference
printf("\nAfter Swaping x = %d and y = %d", x, y);
getch();
}
void swap(int *num1, int *num2) {
int temp;
temp = *num1;
*num1 = *num2;
*num2 = temp;
}
Output:
Enter First number : 12
Enter Second number : 21
3. A pointer is
A. A variable that stores address of an instruction
B. A variable that stores address of other variable
C. A keyword used to create variables
D. None of these
Answer: B
4.
Mode Purpose
r opens a text file in reading mode
w opens or create a text file in writing mode.
a opens a text file in append mode
r+ opens a text file in both reading and writing mode
w+ opens a text file in both reading and writing mode
a+ opens a text file in both reading and writing mode
rb opens a binary file in reading mode
wb opens or create a binary file in writing mode
ab opens a binary file in append mode
rb+ opens a binary file in both reading and writing mode
wb+ opens a binary file in both reading and writing mode
ab+ opens a binary file in both reading and writing mode
2. What is function?
A. Function is a block of statements that performs specific task.
B. Function is a fundamental modular unit
7. A pointer is
A. A variable that stores address of an instruction
B. A keyword used to create variables
C. A variable that stores address of other variable
Answer: A variable that stores address of other variable
C. address operator
D. none of these
Answer: dereferencing operator
B. *
C. ->
D. None of these
Answer: &
16. Which function is used to request memory ans set all allocated bytes to
zero?
A. malloc()
B. malloc()
C. realloc()
D. free()
Answer: calloc()
A. .
B. &
C. *
D. ->
Answer: ->
18. Which of the following is the correct syntax to send an array as a parameter to
function?
a) func(&array);
b) func(#array);
c) func(*array);
d) func(array[size]);
Answer: func(&array);
A. stdio.h
B. stddef.h
C. all the above
Answer: all the above
A. True
B. False
Answer: False