SUMMER TRAINING Free Tutorials  Go To Your University  Placement Preparation 
Project Based Best Summer Training Courses in Jaipur
Join our Telegram Channel To take free Online Courses
0 like 0 dislike
765 views
in GTU B.E. (CSE-I-Sem) Programming For Problem Solving Lab by Goeduhub's Expert (7.1k points)

Write a C program to swap the two values using pointers

1 Answer

0 like 0 dislike
by Goeduhub's Expert (7.1k points)
edited by
 
Best answer

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 :

Output of above program showing swapping of two numbers

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 :

Output of above program showing sum of a and b


For More GTU C Programming Lab Experiments Click Here

Our Mentors(For AI-ML)


Sharda Godara Chaudhary

Mrs. Sharda Godara Chaudhary

An alumna of MNIT-Jaipur and ACCENTURE, Pune

NISHA (IIT BHU)

Ms. Nisha

An alumna of IIT-BHU

Related questions

 Goeduhub:

About Us | Contact Us || Terms & Conditions | Privacy Policy || Youtube Channel || Telegram Channel © goeduhub.com Social::   |  | 
...