Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
Unit 4 (1)
1. 1
INDEX
Unit-4 CONTENT PAGE NO
Function 2
Definition of function 2
Declaration of function 2
Pass by value 10
Pass by reference 11
Recursion 12
Pointers 14
Definition 17
Initialization 14
Pointers arithmetic 16
Pointers and arrays 19
Example Problems
2. 2
UNIT IV FUNCTIONS AND POINTERS
4.1 Functions
4.1.1. Definition of function
Functions are derived data type. Functions are created when the same process or an
algorithm to be repeated several times in various places in the program. By creating function
the source code is reduced significantly.
Functions are used to give modularity.
The function main () invokes other functions within it. It is the first function to be
called when the program starts execution.
Functions are two types :
Built-in functions
ex: printf, scanf, strcmp etc.
User defined functions.
4.1.2. Initialization of functions
The user-defined function has following characteristics:
1. Return type
2. Function name
3. Parameter list
4. Local variables declaration
5. Statements
6. Return value.
3. 3
returntype function name (argument1,argument 2)
{
local variables; // declaration of the local variables
statements;
return variables;
}
The function with return value must be the data type, that is return type and return
value must be of same data type.
Returning function results
Using the keyword return, followed by data variables.
int add(int a,int b)
{
int c = a+b;
return (c);
}
4. 4
The return Keyword is used only when a function returns a value. If you want to
return more than one values, pointers can be used to directly change the values in address
instead of returning those values to the function.
Calling the function:
Function called by function name followed by parameters.
Function_name();
Function_name(parameters);
Return variable= function_name(parameter);
Parameters
The variables are used in between calling function and called function is called
parameters. There are two types of parameters,
Actual parameter:
The parameters in which are transferred from the calling function to the called
program.
Formal parameter:
The parameters are transferred from the called function to the calling program.
Example:
main()
{
…
fun(parameter1,parameter2);
}
5. 5
fun(parameter3,parameter4);
When declaring a function follows the given points:
The data type should be mention
If there is no parameters passed, mention it as void
The function with return value must be the data type, that is return type
and return value must be of same data type.
The no. of actual parameters & formal parameters must match.
The data type of actual parameters & formal parameters must match.
Example:
#include <stdio.h>
int add ( int x, int y );
int main()
{
int x;
int y;
printf( "Please input two numbers to be multiplied: " );
scanf( "%d", &x );
scanf( "%d", &y );
printf( "The product of your two numbers is %dn", add( x, y ) );
getchar();
}
int add (int x, int y)
{
return x + y;
}
6. 6
Local and global variables
Local:
These variables only exist inside the specific function that creates them. They are unknown
to other functions and to the main program. Local variables cease to exist once the function
that created them is completed.
Global:
These variables can be accessed (ie known) by any function comprising the program. They
are implemented by associating memory locations with variable names. If a variable of the
same name is declared both within a function and outside of it, the function will use the
variable that was declared within it and ignore the global one.
/* Demonstrating global variables */
#include <stdio.h>
int add( void);
int value1, value2, value3;
int add(void)
{
auto int result;
result = value1 + value2 + value3;
return result;
}
int main(void)
{
auto int result;
value1 = 10; value2 = 20; value3 = 30;
result = add();
printf(“The sum of %d + %d + %d is %dn”, value1, value2, value3, result);
7. 7
return 0;
}
Advantage of User defined function:
1. Reduce the source code
2. Easy to maintain and modify
3. It can be called anywhere in the program.
Categories of User defined function:
1. Function without return value and without argument.
2. Function without return value and with argument.
3. Function with return value and with argument.
4. Function with return value and without argument
5. Function with more than one return value
1. Functions with no arguments and no return value.
It is one of the simplest types of function in C. This type of function which does not
return any value cannot be used in an expression it can be used only as independent
statement.
Calling function called function
Void function1()
{
------
Function2();
……
}
Void function2()
{
-----
……
}
No argument passing
No return value
8. 8
A C function without any arguments means you cannot pass data (values like int, char
etc) to the called function. Similarly, function with no return type does not pass back data to
the calling function. Let’s have an example to illustrate this.
In this program , no data transfer takes place between the calling function and the called
function. i.e.. the called program does not receive any data from the calling program and does
not send back any value to the calling program.
#include<stdio.h>
#include<conio.h>
void printline()
{
int i;
printf("n");
for(i=0;i<10;i++)
{
printf(i);
}
printf("n");
}
void main()
{
clrscr();
printf("Welcome");
printline();
getch();
}
9. 9
2. Functions with arguments and no return value.
#include<stdio.h>
#include<conio.h>
void add(int x, int y)
{
int result;
result = x+y;
printf("Sum of %d and %d is %d.nn",x,y,result);
}
void main()
{
clrscr();
add(14,15);
getch();
}
3. Functions with arguments and return value.
Void function1()
{
------
Function2();
……
}
Void function2()
{
-----
……
}
argument passing
No return value
Void function1()
{
------
Res = Function2(10);
……
}
Void function2( int x)
{
-----
Return (z)
}
argument passing
return value
10. 10
#include<stdio.h>
#include<conio.h>
int add(int x, int y)
{
int result;
result = x+y;
return(result);
}
void main()
{
int z;
clrscr();
z = add(9,55);
printf("Result %d.nn",add(30,55));
printf("Result %d.nn",z);
getch();
}
4. Functions with no arguments but returns value.
Void function1()
{
------
Res= Function2();
……
}
Void function2()
{
-----
Return (z)
}
No argument passing
return value
11. 11
#include<stdio.h>
#include<conio.h>
int add()
{
int a;
printf("Enter a no : ");
scanf("%d",&a);
return(a);
}
void main()
{
int z;
clrscr();
z = add();
printf("nYou entered : %d.", z);
getch();
}
5. . Functions that return multiple values.
#include<stdio.h>
#include<conio.h>
void calc(int x, int y, int *add, int *sub)
{
*add = x+y;
*sub = x-y;
}
void main()
{
int a=10, b=11, p,q;
12. 12
clrscr();
calc(a,b,&p,&q);
printf("Sum = %d, Sub = %d",p,q);
getch();
}
4.2. Pass by Value
Pass by Value, means that a copy of the data is made and stored by way of the name
of the parameter. Any changes to the parameter have NO affect on data in the calling
function.
When the value is passed directly to the function it is called call by value. In call by
value only a copy of the variable is only passed so any changes made to the variable does not
reflects in the calling function.
/* ******* call by value ******* */
#include<stdio.h>
#include<conio.h>
swap(int,int);
void main()
{
int x,y;
printf("Enter two nos");
scanf("%d %d",&x,&y);
printf("nBefore swapping : x=%d y=%d",x,y);
swap(x,y);
getch();
}
swap(int a,int b)
{
int t;
13. 13
t=a;
a=b;
b=t;
printf("nAfter swapping :x=%d y=%d",a,b);
}
Enter two nos
15
30
Before swapping :
15
30
After swapping :
30
15
4.3. Pass by Reference
A reference parameter "refers" to the original data in the calling function. Thus any
changes made to the parameter are also made to the original variable.
There are two ways to make a pass by reference parameter:
1. Arrays
2. The ampersand used in the function prototype.
function ( & parameter_name )
#include<stdio.h>
#include<conio.h>
swap(int *, int *);
void main()
{
14. 14
int x,y;
printf("Enter two nos");
scanf("%d %d",&x,&y);
printf("nBefore swapping:x=%d y=%d",x,y);
swap(&x,&y);
printf("nAfter swapping :x=%d y=%d",x,y);
getch();
}
swap(int *a,int *b)
{
int t;
t=*a;
*a=*b;
*b=t;
}
Enter two nos
15
30
Before swapping :
15
30
After swapping :
30
15
Pass by value Pass by reference
This method copies the values of actual
parameters into the formal parameters of the
function.
The process of calling a function using
pointers to pass the addresses of variables is
known as “call by reference”.
15. 15
Here, the changes of the formal parameters
cannot affect the actual parameters, because
formal arguments are photocopy of actual
arguments.
Here, the address of arguments are copied
into the parameters inside the function, the
address is used to access the actual arguments
used in the call. Hence changes made in the
arguments are permanent.
The process of passing the actual value of
variables is known as “call by value”.
4.1.5. Recursion in C:
Recursion is calling function by itself again and again until some specified condition
has been satisfied.
This process is used for repetitive computation in which each action is satisfied in
terms of a previous result.
Syntax:
int functionname (int x)
{
local variables;
functionname(y); // this is recursion
statements;
}
16. 16
Example 1: Factorial using Recursion
#include<stdio.h>
#include<conio.h>
int factorial(int n);
void main()
{
int res,x;
printf(“n Enter the value:”);
scanf(“%d”, &x);
res=factorial(x);
printf(“The factorial of %d is ..%d”, res);
}
int factorial(int n)
{
int fact;
if (n==1)
return(1);
else
fact = n*factorial(n-1);
return(fact);
}
Factorial of 5 is 120
i.e., 5 * factorial(5-1)
5 * 4*factorial(4-1)
5 * 4*3*factorial(3-1)
5 * 4*3*2* factorial(2-1)
5 * 4*3*2*1*factorial(1-1)
5*4*3*2*1
17. 17
Example 2: Fibonacci using Recursion
#include<stdio.h>
#include<conio.h>
int Fibonacci(int);
int main()
{
int n,c;
scanf("%d",&n);
printf("Fibonacci seriesn");
for ( c = 1 ; c <= n ; c++ )
{
printf("%dn", Fibonacci(c));
c++;
}
return 0;
}
int Fibonacci(int n)
{
if ( n == 0 )
return 0;
else if ( n == 1 )
return 1;
else
return ( Fibonacci(n-1) + Fibonacci(n-2) );
}
Similarly , recursion of Fibonacci series takes in to another way:
#include <stdio.h>
18. 18
int fibonaci(int i)
{
if(i == 0)
{
return 0;
}
if(i == 1)
{
return 1;
}
return fibonaci(i-1) + fibonaci(i-2);
}
int main()
{
int i;
for (i = 0; i < 10; i++)
{
printf("%dt%n", fibonaci(i));
}
return 0;
}
Example: 3
/* To find sum of first n natural numbers using recursion.*/
#include <stdio.h>
int sum(int n);
int main(){
int n,add;
printf("Enter a positive natural integer:n");
scanf("%d",&n);
add=sum(n);
19. 19
printf("sum=%d",add);
}
int sum(int n){
if(n==0)
return n;
else
return n+sum(n-1);
}
=3+sum(2)
=3+2+sum(1)
=3+2+1+sum(0)
=3+2+1+0
=6
Command line arguments
main() function of a C program accepts arguments from command line or from other shell
scripts by following commands.
They are,
argc
argv[]
where,
argc - Number of arguments in the command line including program name
argv[] – This is carrying all the arguments
20. 20
ex:
>prg1 hello hai
argc = 4
argv[0] = “prg1”
argv[1] = “hello”
argv[2] = “hai”
argv[3] = NULL
ex: program for command line arguments
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) // command line arguments
{
printf("n Program name : %s n", argv[0]);
return 0;
}
4.2. Pointers
Normal variable stores the value whereas pointer variable stores the address of the
variable. The content of the C pointer always be a whole number i.e. address.
A pointer is a variable and contains the address of another variable. It is denoted
by ‘*’ operator. Pointers are called “address variable”.
The indirection operators (*) returns the value of the address stored in a pointer. The
address of operator (&) returns the memory address of the variable.
21. 21
Pointer is a user defined data type which creates special types of variables which
can hold the address of primitive data type like char, int, float, double or user defined data
type like function, pointer etc. or derived data type like array, structure, union, enum.
Null pointer:
A pointer is said to be a null pointer when its right side value is 0.
It can never point valid data.
It is assigned to 0, so it is a null pointer and is not valid.
int *a;
int *b;
b=a=0;
a and b become null pointers
Pointer to pointer
A variable that is a pointer to a pointer must be declared using additional indirection
operator symbols in front of the name.
int ** p;
Pointer is a variable that contains the address of the another variable.
Example
int a=5;
int *b;
int **c;
b=&a;
c=&b;
Display array with addresses:
22. 22
#include<stdio.h>
#include<stdlib.h>
int main() {
int a[3] = { 10, 20, 30 };
printf("n a[0] ,value=%d : address=%u", a[0], &a[0]);
printf("n a[1] ,value=%d : address=%u", a[1], &a[1]);
printf("n a[2] ,value=%d : address=%u", a[2], &a[2]);
return (0);
}
Advantages
Pointers are used for efficient code.
Pointers are access memory efficiently and simplicity.
Difference between arrays and pointers are as follows.
Array Pointer
Array allocates space automatically Pointer is explicitly assigned to point to an
allocated
space.
It cannot be resized. It can be resized using realloc ().
It cannot be reassigned. Pointers can be reassigned.
Size of(array name) gives the number of
bytes occupied by the array.
Sizeof(pointer name) returns the number of
bytes used to store the pointer variable
23. 23
4.2.1. Pointer –Initialization:
Assigning value to pointer:
Only zero (0) and NULL can be assigned to a pointer no other number can be
assigned to a pointer.
Consider the following examples;
int *p=0;
int *p=NULL;
int *p = null.
The value of null pointer is 0. If pointer is assigned to NULL, it means it is pointing to
nothing. The size of any pointer is 2 byte (for 16 bit compiler).
Assigning variable to a pointer:
int a; *p;
p = &a;
A pointer variable p is assigned the address of the variable a. The address of the variables will
be different every time.
& symbol is used to get the address of the variable.
* symbol is used to get the value of the variable.
About variable a:
1. Name of variable : a
2. Value of variable which it keeps: 5
3. Address where it has stored in memory : 1025 (assume)
About variable ptr:
24. 24
1. Name of variable : ptr
2. Value of variable which it keeps: 1025
3. Address where it has stored in memory : 5000 (assume)
/* accessing variable thru pointer */
#include <stdio.h>
main ()
{
int age=39;
printf(“address of age =%u’’ ,&age)
printf(“value of age =%d’’ , age)
}
Output
Address of age =265432
Value of age =39
We are going to add two numbers by using pointer.
/* add two numbers using pointer */
#include<stdio.h>
int main() {
int *ptr1, *ptr2;
int num;
printf("nEnter two numbers : ");
scanf("%d %d", ptr1, ptr2);
25. 25
num = *ptr1 + *ptr2;
printf("Sum = %d", num);
return (0);
}
4.2.2. Pointer Arithmetic
Rule 1: Addition arithmetic with pointers
Address + Number= Address
Address - Number= Address
Address++ = Address
Address-- = Address
++Address = Address
--Address = Address
If we will add or subtract a number from an address result will also be an address.
New address will be:
New address = old address + number*size of data type which pointer is pointing
Or
New address = old address - number*size of data type which pointer is pointing
Example:
#include<stdio.h>
int main()
{
int *ptr=( int *)1000;
26. 26
ptr=ptr+1;
printf(" %u",ptr);
return 0;
}
Output: 1002
Rule 2: Difference arithmetic with pointers
Address - Address=Number
If you will subtract two pointers result will be a number but number will not simple
mathematical subtraction of two addresses but it follow following rule:
If two pointers are of same type then:
Address2 –address1 = subtraction of two address/size of data type which pointer points
Example:
Explanation:
Here two pointer p and temp are of same type and both are pointing to int data type varaible.
p-temp = (1004-1000)/sizeof(int)
=4/2
=2
#include<stdio.h>
int main()
{
int *p=(int *)1000;
27. 27
int *temp;
temp=p;
p=p+2;
printf("%u %un",temp,p);
printf("difference= %d",p-temp);
return 0;
}
Output: 1000 1004
Difference= 2
Pointer to function
Function pointer definition: A pointer which keeps address of a function is known as
function pointer
Example:
#include<stdio.h>
int * function();
int main(){
auto int *x;
int *(*ptr)();
ptr=&function;
x=(*ptr)();
printf("%d",*x);
return 0;
}
int *function(){
static int a=10;
return &a;
}
28. 28
Output: 10
Here function is function whose parameter is void data type and return type is pointer to int
data type.
x=(*ptr)()
x=(*&functyion)() //ptr=&function
x=function() //From rule *&p=p
x=&a
So, *x = *&a = a =10
Pointer to structure:
A pointer which is pointing to a structure is known as pointer to structure.
Example:
#include<stdio.h>
struct address
{
char *name;
char street[10];
int pin;
} cus;
cus={"pandi","H",625003},*p=&cus;
int main()
{
printf("%s %s",p->name,(*p).street);
return 0;
}
• p is pointer to structure address.
29. 29
• -> and (*). Both are same thing. These operators are used to access data member of
structure by using structure’s pointer.
Output: pandi H
Pointer to union:
Pointer to union: A pointer which is pointing to a union is know as pointer to union
Example:
#include<stdio.h>
union address{
char *name;
char street[10];
int pin;
};
int main(){
union address emp,*p;
emp.name="jai";
p=&emp;
printf("%s %s",p->name,(*p).name);
return 0;
}
• p is pointer to union address.
• -> and (*). Both are same thing. These operators are used to access data member of
union by using union’s pointer.
• %s is used to print the string up to null character i.e. ‘0’
Output: jai
4.2.4. Pointer to array
30. 30
Here an array is declared, the memory should be allocated in contiguous location. The
memory location as a base address plus sufficient amount of storage .
base address = location of the first element (index 0) of the array.
farray [][3];
It is two dimension array and its content are float constants. array [3]:It is one
dimension array and its content are address of such one dimension array which content are
float constant. ptr: It is pointer to one dimension array which content are address of such one
dimension array which content are float constant.
Example:
#include<stdio.h>
int main(){
static float farray[][3]={0.0f,1.0f,2.0f,3.0f,4.0f,5.0f,6.0f,7.0f,8.0f};
float (*array[3])[3]={&farray[0],&farray[1],&farray[2]};
float (*(*ptr)[])[3]=&array;
printf("%f ",2[(*(**ptr+1))]);
return 0;
}
Output: 5.000000
Pointer to array of character:
A pointer to such an array which contents is character constants is known as pointer to
array of character constant.
Example:
#include<stdio.h>
char display(char (*)[]);
31. 31
int main(){
char c;
char character[]={65,66,67,68};
char (*ptr)[]=&character;
c=display(ptr);
printf("%c",c);
return 0;
}
char display(char (*s)[]){
**s+=2;
return **s;
}
Output: C
Here function display is passing pointer to array of characters and returning char data type.
**s+=2
=>**s=**s+2
=>**ptr=**ptr+2 //s=ptr
=>**&character= **&character+2 //ptr=&character
=>*character=*character+2 //from rule *&p =p
=>character[0]=character[0]+2 //from rule *(p+i)=p[i]
=>character [0] =67
**s=character [0] =67
Note: ASCII value of ‘C’ is 67
When an array name is passed to a function, what is passed is the location of the
initial element. Within the called function, this argument is a local variable, and so an array
32. 32
name parameter is a pointer, that is, a variable containing an address. We can use this fact to
write another version of strlen, which computes the length of a string.
/* strlen: return length of string s */
int strlen(char *s)
{
int n;
for (n = 0; *s != '0', s++)
n++;
return n;
}
Since s is a pointer, incrementing it is perfectly legal; s++ has no effect on the character
string in the function.
Pointer to array of integers:
A pointer to such an array which contents are integer numbers is known as pointer to
array of integer.
#include<stdio.h>
int main()
{
static int i,j,k;
int *(*ptr)[];
int *array[3]={&i,&j,&k};
ptr=&array;
j=i+++k+10;
++(**ptr);
printf("%d",***ptr);
return 0;
}
Output: 10
33. 33
Note: In the above figure upper part of box represent content and lower part represent
memory address. We have assumed arbitrary address.
j=i+++k+10
=i++ + k+10
=0 +0 +10=10
***ptr = *** (&array) //ptr=&array
= **array //From rule *&p=p
//From rule array [0] =*(array+0) and ++ (**ptr)
=*array [1]
=*&j
=j
=10