Swapping of Two Numbers Using Pointers
In this program we are going to swap two numbers using pointers. The pointer will be used to hold the address of the variable and using pointer address of the variables will be swepped. In the following example we are going to implement this theory.
Example :
#include<stdio.h>
#include<conio.h>
void main()
{
//Declaration of variables and pointer variables
int x,y,*ptr_x,*ptr_y,temp;
clrscr();
//Insert value of x and y
printf("Enter the value of x and y\n");
scanf("%d%d", &x, &y);
//Printing value before swapping
printf("Before Swapping\nx = %d\ny = %d\n", x, y);
//Assigning address of variables to pointers
ptr_x = &x;
ptr_y = &y;
//Swapping pointer address with the help of temp variable
temp = *ptr_y;
*ptr_y = *ptr_x;
*ptr_x = temp;
//printing values of x and y
printf("After Swapping\nx = %d\ny = %d\n", x, y);
getch();
} |
Output :
Add Two Numbers Using Pointers
In this program we are going to add two numbers using pointers
Example :
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,sum=0;
//pointers pointing at a and b
int *ptr_a=&a,*ptr_b=&b;
clrscr();
printf("Enter a and b:");
scanf("%d%d",&a,&b);
//sum of a and b using pointers
sum=*ptr_a+*ptr_b;
printf("\nSum = %d",sum);
getch();
} |
Output :
For More GTU C Programming Lab Experiments Click Here