Computer Concept & Programming In C - Unit IV - 9

Q.17 Explain the use of pointer as function arguments.
Ans. Use of Pointer as Function Arguments: -
# include <stdio.h>
# include <conio.h>
void circumference (float*);
void main ( )
{
float radius;
float *circumference;
printf (“\n Enter radius of circle”);
scanf (“%f ”, &radius);
circumference (& radius);
printf (“\n The circumference is = %f ”, *circumference);
getch ( );
}
void_circumference (float*r)
{
circumference = 2*3.1416*(*r);
}
The above program uses pointer as arguments to function. It uses a function_circumference to calculate the circumference of a circle whose radius is taken as input from the user.
Another program which demonstrate the use of pointers as function arguments is given below:
# include <stdio.h>
# include <conio.h>
void swap_em (int*a, int*b);
/* changing the values of variables using pointers*/
void main ( )
{
int a, b;
a = 5, b = 25;
printf (“\n Values before calling the function: a = %d, b = %d\n”, a, b);
swap_em(&a, &b);
printf (“\n Values after calling the function: a = %d, b = %d\n”, a, b);
getch ( );
}
void swap_em (int*a, int*b)
{
int pot;
pot = *a;
*a = *b;
*b = pot;
}
The output of the program is:
Values before calling the function a = 5, b = 25
Values after calling the function = a = 25, b = 5
In this program “a” and “b” are declared as local variables but when the function is called the address “&a” and “&b” are passed to it. Notice also that the swapping is done on the contents of the address (“*a” and “*b”).
This is the same principle used in the standard function scanf, which reaches the contents of a variable through pointers.

Q.18 Write a program segment in C to swap the values of two variables using pointers.                                                               (AKTU. 2009-10)
Ans.
#include<stdio.h>
#include<conio.h>
void swap(int*, int*);
void main()
{
 int a,b;
 clrscr();
 printf("\nEnter First number\n");
 scanf("%d",&a);
 printf("\nEnter second number\n");
 scanf("%d",&b);
 swap(&a, &b);
 printf("\n After swapping:");
 printf("\nFirst number = %d ", a);
 printf("\nSecond number = %d ", b);
 getch();
}
void swap(int *c, int *d)
{
 int t;
 t = *c;
 *c = *d;
 *d = t;
}