0% found this document useful (0 votes)
20 views48 pages

C Programming: Functions and Pointers Guide

Unit III of CS8251 Programming in C covers functions and pointers, including function prototypes, definitions, calls, and built-in functions. It explains recursion, types of recursion, and provides example programs for various concepts such as sine series computation and sorting names. The unit emphasizes the advantages of using functions, such as code reusability and easier debugging.

Uploaded by

Sundari
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views48 pages

C Programming: Functions and Pointers Guide

Unit III of CS8251 Programming in C covers functions and pointers, including function prototypes, definitions, calls, and built-in functions. It explains recursion, types of recursion, and provides example programs for various concepts such as sine series computation and sorting names. The unit emphasizes the advantages of using functions, such as code reusability and easier debugging.

Uploaded by

Sundari
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

CS8251 Programming in C – UNIT III

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

3.1 Introduction to functions


A function is a subprogram of one or more statements that performs a specific task
when called.
Advantages of Functions:
1. Code reusability
2. Better readability
3. Reduction in code redundancy
4. Easy to debug & test.
Classification of functions:
 Based on who develops the function
 Based on the number of arguments a function accepts
1. Based on who develops the function
There are two types.
1. Library functions
2. User-defined functions
1. Library functions [Built-in functions]

B. Shanmuga Sundari, ASP/CSE, 9632 PET Engineering College, Vallioor 1


CS8251 Programming in C – UNIT III

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.

3.2 Function Prototype


Before using a function, the compiler must know the number of parameters
and the type of parameters that the function expects to receive and the data type of
value that it will return to the calling program. Placing the function declaration

B. Shanmuga Sundari, ASP/CSE, 9632 PET Engineering College, Vallioor 2


CS8251 Programming in C – UNIT III

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.

3.3 Function definition


When a function is defined, space is allocated for that function in the memory. A
function definition comprises of two parts:
 Function header
 Function body
The syntax of a function definition can be given as:
return_data_type function_name(data_type variable1, data_type variable2,..)
{
.............
statements
.............
return(variable);

B. Shanmuga Sundari, ASP/CSE, 9632 PET Engineering College, Vallioor 3


CS8251 Programming in C – UNIT III

}
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.

3.4 Function Call


The function call statement invokes the function. When a function is invoked, the
compiler jumps to the called function to execute the statements that are a part of
that function. Once the called function is executed, the program control passes
back to the calling function.
Syntax:
function_name(variable1, variable2, ...);
The following points are to be noted while calling a function:
 Function name and the number and the type of arguments in the function call
must be same as that given in the function declaration and the function
header of the function definition.
 Names (and not the types) of variables in function declaration, function call,
and header of function definition may vary.
 Arguments may be passed in the form of expressions to the called function.
In such a case, arguments are first evaluated and converted to the type of
formal parameter and then the body of the function gets executed.
 If the return type of the function is not void, then the value returned by the
called function may be assigned to some variable as given below.
variable_name = function_name(variable1, variable2, ...);

B. Shanmuga Sundari, ASP/CSE, 9632 PET Engineering College, Vallioor 4


CS8251 Programming in C – UNIT III

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

}

int abc(int i, int j, int k) // Function definition


{ Formal arguments
…….
….
return (value);
}

Calling function – The function that calls a function is known as a calling


function.
Called function – The function that has been called is known as a called function.
Actual arguments – The arguments of the calling function are called as actual
arguments.
Formal arguments – The arguments of called function are called as formal
arguments.

B. Shanmuga Sundari, ASP/CSE, 9632 PET Engineering College, Vallioor 5


CS8251 Programming in C – UNIT III

Steps for function Execution:


1. After the execution of the function call statement, the program control is
transferred to the called function.
2. The execution of the calling function is suspended and the called function
starts execution.
3. After the execution of the called function, the program control returns to
the calling function and the calling function resumes its execution.

3.5 Built-in functions (string functions, math functions)


The standard library functions are built-in functions in C programming to
handle tasks such as mathematical computations, I/O processing, string handling
etc. These functions are defined in the header file.
The printf() is a standard library function to send formatted output to the
screen (display output on the screen). This function is defined in "stdio.h" header
file.
There are other numerous library functions defined under "stdio.h", such
as scanf(), fprintf(), getchar() etc. Once you include "stdio.h" in your program, all
these functions are available for use.

Library of Mathematical functions.


These are defined in math.h header file.
Example:

1 double cos(double x)- Returns the cosine of a radian angle x


2 double sin(double x)- Returns the sine of a radian angle x.
3 double exp(double x)- Returns the value of e raised to the xth power
double log(double x)
4
Returns the natural logarithm (base-e logarithm) of x.
double sqrt(double x)
5
Returns the square root of x.

B. Shanmuga Sundari, ASP/CSE, 9632 PET Engineering College, Vallioor 6


CS8251 Programming in C – UNIT III

double pow(double x, double y)


6
Returns x raised to the power of y.

Library of standard input & output functions


Header file: stdio.h
Example:
1 printf() This function is used to print the character, string, float, integer,
octal and hexadecimal values onto the output screen
2 scanf() This function is used to read a character, string, and numeric data
from keyboard.
3 getc() It reads character from file
4 gets() It reads line from keyboard

Library of String functions:


Header file: string.h
Example:
Functions Descriptions
strlen() Determines the length of a String
strcpy() Copies a String from source to destination
strcmp() Compares two strings
strlwr() Converts uppercase characters to lowercase
strupr() Converts lowercase characters to uppercase

Example: strlen function


#include <stdio.h>
int main() {
char string1[20];
char string2[20];

B. Shanmuga Sundari, ASP/CSE, 9632 PET Engineering College, Vallioor 7


CS8251 Programming in C – UNIT III

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

Example: strcpy function

#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

B. Shanmuga Sundari, ASP/CSE, 9632 PET Engineering College, Vallioor 8


CS8251 Programming in C – UNIT III

Example :strcmp function


#include<stdio.h>
#include<string.h>
void main( )
{
char one[20] = “William Lambton”;
char two[20] = “William Lamberton”;
if(strcmp(one, two) == 0)
printf(“The names are the same.”);
else
printf(“The names are different.”);
}

Output:
The names are different

Example: Strupr() and strlwr()


#include<stdio.h>
#include<string.h>
int main( )
{
char str[] = “ String Functions”;
printf(“%s \n”, strupr(str));
printf(“%s \n”, strlwr(str));
return 0;
}
Output:
STRING FUNCTIONS

B. Shanmuga Sundari, ASP/CSE, 9632 PET Engineering College, Vallioor 9


CS8251 Programming in C – UNIT III

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.

Direct & Indirect Recursion:


Direct Recursion:
A function is directly recursive if it calls itself.
A( )
{
….
….
A( );// call to itself
….
}
Indirect Recursion:
Function calls another function, which in turn calls the original function.
A( )
{


B( );

}
B( )
{

B. Shanmuga Sundari, ASP/CSE, 9632 PET Engineering College, Vallioor 10


CS8251 Programming in C – UNIT III



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)

B. Shanmuga Sundari, ASP/CSE, 9632 PET Engineering College, Vallioor 11


CS8251 Programming in C – UNIT III

{
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

B. Shanmuga Sundari, ASP/CSE, 9632 PET Engineering College, Vallioor 12


CS8251 Programming in C – UNIT III

A function is said to be indirectly recursive if it contains a call to another function


which ultimately calls it. These two functions are indirectly recursive as they both
call each other.
int Funcl (int n)
{
if (n == 0)
return n;
else
return Func2(n);
}
int Func2(int x)
{
return Func1(x–1);
}

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));
}

B. Shanmuga Sundari, ASP/CSE, 9632 PET Engineering College, Vallioor 13


CS8251 Programming in C – UNIT III

The above function is a nontail-recursive function, because there is a


pending operation of multiplication to be performed on return from each recursive
call. Whenever there is a pending operation to be performed, the function becomes
non-tail recursive. In such a non-tail recursive function, information about each
pending operation must be stored, so the amount of information directly depends
on the number of calls.
int Fact(n)
{
return Fact1(n, 1);
}
int Fact1(int n, int res)
{
if (n == 1)
return res;
else
return Fact1(n–1, n*res);
}
The same factorial function can be written in a tail recursive manner. In the code,
Fact1 function preserves the syntax of Fact(n). Here the recursion occurs in the
Fact1 function and not in Fact function. Fact1 has no pending operation to be
performed on return from recursive calls. The value computed by the recursive call
is simply returned without any modification. So in this case, the amount of
information to be stored on the system stack is constant (only the values of n and
res need to be stored) and is independent of the number of recursive calls.

E.g. Program:
#include<stdio.h>
#include<conio.h>

B. Shanmuga Sundari, ASP/CSE, 9632 PET Engineering College, Vallioor 14


CS8251 Programming in C – UNIT III

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

Pattern of Recursive Calls:


Based on the number of recursive calls, the recursion is classified in to 3
types. They are,
1. Linear Recursion - Makes only one recursive call.
2. Binary Recursion - Calls itself twice.
3. N-ary recursion - Calls itself n times.

B. Shanmuga Sundari, ASP/CSE, 9632 PET Engineering College, Vallioor 15


CS8251 Programming in C – UNIT III

Converting Recursive Functions to Tail Recursive


A non-tail recursive function can be converted into a tail-recursive function
by using an auxiliary parameter as we did in case of the Factorial function. The
auxiliary parameter is used to form the result. When we use such a parameter, the
pending operation is incorporated into the auxiliary parameter so that the recursive
call no longer has a pending operation.
Recursive functions can also be characterized depending on the way in
which the recursion grows in a linear fashion or forming a tree structure as shown
below:
int Fibonacci(int num)
{
if(num == )
return ;
else
return (Fibonacci(num - 1) + Fibonacci(num – 2));
}
else if (num == 1)
return 1;
Observe the series of function calls. When the function pending operations in turn
calls the function
Fibonacci(7) = Fibonacci(6) + Fibonacci(5)
Fibonacci(6) = Fibonacci(5) + Fibonacci(4)
Fibonacci(5) = Fibonacci(4) + Fibonacci(3)
Fibonacci(4) = Fibonacci(3) + Fibonacci(2)
Fibonacci(3) = Fibonacci(2) + Fibonacci(1)
Fibonacci(2) = Fibonacci(1) + Fibonacci(0)
Now we have, Fibonacci(2) = 1 + 0 = 1

B. Shanmuga Sundari, ASP/CSE, 9632 PET Engineering College, Vallioor 16


CS8251 Programming in C – UNIT III

Fibonacci(4) = 2 + 1 = 3
Fibonacci(5) = 3 + 2 = 5
Fibonacci(6) = 3 + 5 = 8
Fibonacci(7) = 5 + 8 = 13

On the contrary, a recursive function is said to be tree recursive (or non-


linearly recursive) if the pending operation makes another recursive call to the
function. For example, the Fibonacci function in which the pending operations
recursively call the Fibonacci function.

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

B. Shanmuga Sundari, ASP/CSE, 9632 PET Engineering College, Vallioor 17


CS8251 Programming in C – UNIT III

 Move the ring from A to C using B as spare


Recursive case:
 Move n – 1 rings from A to B using C as spare
 Move the one ring left on A to C using B as spare
 Move n – 1 rings from B to C using A as spare

Figure (a)

Figure (b)

Figure (c)

B. Shanmuga Sundari, ASP/CSE, 9632 PET Engineering College, Vallioor 18


CS8251 Programming in C – UNIT III

Figure (d)

3.7 Example Program


1. Program for Computation of Sine series
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
int i, n ;
float x, val, sum, t ;
clrscr() ;
printf("Enter the value for x : ") ;
scanf("%f", &x) ;
printf("\nEnter the value for n : ") ;
scanf("%d", &n) ;
val = x ;
x = x * 3.14159 / 180 ;
t=x;
sum = x ;
for(i = 1 ; i < n + 1 ; i++)
{
t = (t * pow((double) (-1), (double) (2 * i - 1)) * x * x) / (2 * i * (2 * i + 1)) ;

B. Shanmuga Sundari, ASP/CSE, 9632 PET Engineering College, Vallioor 19


CS8251 Programming in C – UNIT III

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

2. Program for Scientific calculator using built-in functions


#include<stdio.h>
#include <math.h>
#define PI 3.14159265
float sine(float x);
float cosine(float x);
float tangent(float x);
float sineh(float x); float cosineh(float x);
float tangenth(float x);
float logten(float x);
float squareroot(float x);
float exponent(float x);
float power(float x,float y);
int main()
{
int x,y,n,answer;
printf("What do you want to do?\n");

B. Shanmuga Sundari, ASP/CSE, 9632 PET Engineering College, Vallioor 20


CS8251 Programming in C – UNIT III

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)

B. Shanmuga Sundari, ASP/CSE, 9632 PET Engineering College, Vallioor 21


CS8251 Programming in C – UNIT III

{
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));

B. Shanmuga Sundari, ASP/CSE, 9632 PET Engineering College, Vallioor 22


CS8251 Programming in C – UNIT III

}
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));
}

3. Program for binary search using recursive function


#include<stdio.h>
int main()
{

int a[10],i,n,m,c,l,u;

printf("Enter the size of an array: ");


scanf("%d",&n);

printf("Enter the elements of the array: " );


for(i=0;i<n;i++)
{
scanf("%d",&a[i]);

B. Shanmuga Sundari, ASP/CSE, 9632 PET Engineering College, Vallioor 23


CS8251 Programming in C – UNIT III

printf("Enter the number to be search: ");


scanf("%d",&m);

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;
}

int binary(int a[],int n,int m,int l,int u)


{
int mid,c=0;
if(l<=u)
{
mid=(l+u)/2;
if(m==a[mid])
{
c=1;
}
else if(m<a[mid])
{
return binary(a,n,m,l,mid-1);

B. Shanmuga Sundari, ASP/CSE, 9632 PET Engineering College, Vallioor 24


CS8251 Programming in C – UNIT III

}
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;

E.g ) int *p //p is an pointer to an int


float *fp //fp is a pointer to a float

int a=10; p a
int *p=&a;
2000 10

4000 2000

B. Shanmuga Sundari, ASP/CSE, 9632 PET Engineering College, Vallioor 25


CS8251 Programming in C – UNIT III

p is an integer pointer & holds the address of an int variable a.

Pointer to pointer
A pointer that holds the address of another pointer variable is known as a
pointer to pointer.
E.g.
int **p;

p is a pointer to a pointer to an integer.


int a=12;
int *p=&a; a
int **pptr=&p;
12
p 4000 4000

6000

6000 pptr
8000
So **pptr=12

3.9 Operations on pointers

1. Referencing operation: A pointer variable is made to refer to an object.


Reference operator(&) is used for this. Reference operator is also known as
address of (&) operator.

Eg) float a=12.5;


float *p;
p=&a;

a 12.5

1000 1000
P
2000

2. Dereferencing a pointer

B. Shanmuga Sundari, ASP/CSE, 9632 PET Engineering College, Vallioor 26


CS8251 Programming in C – UNIT III

The object referenced by a pointer can be indirectly accessed by


dereferencing the pointer. Dereferencing operator (*) is used for this .This
operator is also known as indirection operator or value- at-operator

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

2000 pptr 2000

3000

B. Shanmuga Sundari, ASP/CSE, 9632 PET Engineering College, Vallioor 27


CS8251 Programming in C – UNIT III

3.10 Pointer arithmetic


Arithmetic operations on pointer variables are also possible.
E.g.) Addition, Increment, Subtraction, Decrement.

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.

Eg) if p is a pointer to an object then


p+1 =>points to next object
p+i=>point s to ith object after p

(ii)Addition of 2 pointers is not allowed.


2. Increment
Increment operator can be applied to an operand of pointer type.
3. Decrement
Decrement operator can be applied to an operand of pointer type.
4. Subtraction
i) A pointer and an int can be subtracted.
ii) 2 pointers can also be subtracted.

B. Shanmuga Sundari, ASP/CSE, 9632 PET Engineering College, Vallioor 28


CS8251 Programming in C – UNIT III

[Link] Operator Type of Type of Result Example Initial Final Description


operand operand type value value
1 2
1 + Pointer int Pointer Result =
to type to type initial value
T T of ptr +int
operand *
sizeof (T)

Eg. int * int int * p=p+5 p=2000 2010 2000+5*2=


2010
2 ++ Pointer Pointer Post
to type - to type increment
T T Result =
initial value
of pointer

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

B. Shanmuga Sundari, ASP/CSE, 9632 PET Engineering College, Vallioor 29


CS8251 Programming in C – UNIT III

= 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 –

B. Shanmuga Sundari, ASP/CSE, 9632 PET Engineering College, Vallioor 30


CS8251 Programming in C – UNIT III

sizeof(T)

3.11. 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);
10 15 20
printf(“2 element of array is at %u\n”, a+1);
nd

printf(“3nd element of array is at %u\n”, a+2);


1000 1002 1004
}
Output
First element of array is at 1000
2nd element of array is at 1002
3nd 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

B. Shanmuga Sundari, ASP/CSE, 9632 PET Engineering College, Vallioor 31


CS8251 Programming in C – UNIT III

#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

3.12 Array of pointers


An array of pointers is a collection of addresses. Pointers in an array must be
the same type.
int a=10,b=20,c=30;
int *b[3]={&a,&b,&c};
a b c

10 20 30

4000 4100 4400

4000 4100 4400


b

5000 5002 5004

B. Shanmuga Sundari, ASP/CSE, 9632 PET Engineering College, Vallioor 32


CS8251 Programming in C – UNIT III

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

3.13 Example Program


1. Program for Sorting of names
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char *x[20];
int i,n=0;
void reorder(int n,char *x[]);
clrscr();
printf("Enter no. of String : ");
scanf("%d",&n);
printf("\n");

B. Shanmuga Sundari, ASP/CSE, 9632 PET Engineering College, Vallioor 33


CS8251 Programming in C – UNIT III

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

B. Shanmuga Sundari, ASP/CSE, 9632 PET Engineering College, Vallioor 34


CS8251 Programming in C – UNIT III

Aswin
Babu
Clinton
kailash
Clinton

3.14 Parameter passing


Whenever we call a function then sequence of executable statements gets executed.
We can pass some of the information to the function for processing
called argument. There are two ways in which arguments can be passed from
calling function to called function. They are:
1. Pass by value
2. Pass by reference

1. Pass by value (Call by value)


 In this method the values of actual arguments are copied to formal
arguments.
 Any change made in the formal arguments does not affect the actual
arguments.
 Once control, return backs to the calling function the formal
parameters are destroyed.

E.g. Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b;

B. Shanmuga Sundari, ASP/CSE, 9632 PET Engineering College, Vallioor 35


CS8251 Programming in C – UNIT III

void swap(int ,int);


a=10;
b=20;
printf("\n Before swapping: a = %d and b = %d",a,b);
swap(a, b);
printf("\n After swapping: a= %d and b= %d",a,b);
getch();
}
void swap(int a1,int b1)
{
int temp;
temp=a1;
a1=b1;
b1=temp;
}
OUTPUT:
Before swapping: a =10 and b =20
After swapping: a =10 and b = 20

B. Shanmuga Sundari, ASP/CSE, 9632 PET Engineering College, Vallioor 36


CS8251 Programming in C – UNIT III

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

2. Pass by reference ( Call b y reference)


 In this method, the addresses of the actual arguments are passed to formal
argument.
 Thus formal arguments points to the actual arguments.
 So changes made in the arguments are permanent.

Example Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b;

B. Shanmuga Sundari, ASP/CSE, 9632 PET Engineering College, Vallioor 37


CS8251 Programming in C – UNIT III

void swap(int *,int *);


a=10;
b=20;
printf("\n Before swapping: a= %d and b= %d",a,b);
swap(&a,&b);
printf("\n After swapping: a= %d and b= %d",a,b);
getch();
}
void swap(int *a1,int *b1)
{
int t;
t = *a1;
*a1 = *b1;
*b1 = t;
}
OUTPUT:
Before swapping: a = 10 and b = 20
After swapping: a = 20 and b = 10

B. Shanmuga Sundari, ASP/CSE, 9632 PET Engineering College, Vallioor 38


CS8251 Programming in C – UNIT III

Main function
a b

10 20

1000 1002
Swap function
a1 b1
1000 1002

a1, b1 points to a and b.

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 : ");

B. Shanmuga Sundari, ASP/CSE, 9632 PET Engineering College, Vallioor 39


CS8251 Programming in C – UNIT III

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

Before Swaping x = 12 and y = 21


After Swaping x = 21 and y = 12

Multiple Choice Questions:


1. What is the default return type if it is not specified in function definition?
A. void
B. int
C. float
D. short int
Answer: int

B. Shanmuga Sundari, ASP/CSE, 9632 PET Engineering College, Vallioor 40


CS8251 Programming in C – UNIT III

2. In C, what is the meaning of following function prototype with empty parameter


list
void fun()
{
/* .... */
}
A. Function can only be called without any parameter
B. Function can be called with any number of parameters of any types
C. Function can be called with any number of integer parameters.
D. Function can be called with one integer parameter.
Answer: B

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.

B. Shanmuga Sundari, ASP/CSE, 9632 PET Engineering College, Vallioor 41


CS8251 Programming in C – UNIT III

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

Multiple Choice Questions:


1. Any C program
A. Must contain atleast one function
B. Need not contain any function
C. No input
Answer: Must contain atleast one function

2. What is function?
A. Function is a block of statements that performs specific task.
B. Function is a fundamental modular unit

B. Shanmuga Sundari, ASP/CSE, 9632 PET Engineering College, Vallioor 42


CS8251 Programming in C – UNIT III

C. It has a name and it is reusable


D. All the above
Answer: All the bove

3. A function which calls itself is called a ___ function.


A) Self Function
B) Auto Function
C) Recursive Function
D) Static Function
Answer : Recursive Function

4. What is the output of C Program with functions.?


void show();
int main()
{
show();
printf(" C ");
return 0;
}
void show()
{
printf("Programming in ");
}
A. C
B. Programming in C
C. Compiler error
Answer: Programming in C

B. Shanmuga Sundari, ASP/CSE, 9632 PET Engineering College, Vallioor 43


CS8251 Programming in C – UNIT III

5. How many values can a C Function return at a time.?


A) Only One Value
B) Maximum of two values
C) Maximum of three values
D) Maximum of 8 values
Answer: Only One Value

6. In C, what is the meaning of following function prototype with empty


parameter list
void fun()
{
/* .... */
}
[Link] can only be called without any parameter
[Link] can be called with any number of parameters of any types
[Link] can be called with any number of integer parameters.
D. Function can be called with one integer parameter.
Answer: B

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

8. The operator * signifies a


A. referencing operator
B. dereferencing operator

B. Shanmuga Sundari, ASP/CSE, 9632 PET Engineering College, Vallioor 44


CS8251 Programming in C – UNIT III

C. address operator
D. none of these
Answer: dereferencing operator

9. (&num) is equivalent to writing


A. &num
B. *num
C. num
D. None of these
Answer: num

10. Pointers are used to create complex data structures such as


A. Tree
B. Linked list
C. Stack
D. Queue
E. All of these
Answer: all of these

11. While declaring pointer variables, which operator do we use?


A. Address
B. Arrow
C. Indirection
D. Dot
Answer: Address

12. Which operator retrieves the Ivalue of a variable?


A. &

B. Shanmuga Sundari, ASP/CSE, 9632 PET Engineering College, Vallioor 45


CS8251 Programming in C – UNIT III

B. *
C. ->
D. None of these
Answer: &

13. The code of the main () program is stored in memory is


A. Stack
B. Heap
C. Global
D. BSS
Answer: Stack

14. For dynamically allocated variables, memory is allocated from which


memory area?
A. Stack
B. Heap
C. Global
D. BSS
Answer: Heap

15. The function mallaoc () is declared in which header file


A. stdio.h
B. stdlib.h
C. conio.h
D. iostream.h
Answer: stdlib.h

B. Shanmuga Sundari, ASP/CSE, 9632 PET Engineering College, Vallioor 46


CS8251 Programming in C – UNIT III

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()

17. If a variable is a pointer to a structure, then which of the following


operator is used to access data members of the structure through the pointer
variable?

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);

19. In which header file is the NULL macro defined?

B. Shanmuga Sundari, ASP/CSE, 9632 PET Engineering College, Vallioor 47


CS8251 Programming in C – UNIT III

A. stdio.h
B. stddef.h
C. all the above
Answer: all the above

20. Are the expression *ptr++ and ++*ptr are same?

A. True

B. False

Answer: False

B. Shanmuga Sundari, ASP/CSE, 9632 PET Engineering College, Vallioor 48

You might also like