C Program to Swap Two Numbers Using Pointers

 Ex: Write a C program to swap two numbers using pointers. How to write a C program to swap two numbers using pointers. C program to swap two numbers using pointers.


Input from user:

Enter first number: 10

Enter second number: 20


Expected output:

Numbers after swapping:

Number1=20

Number2=10



In this program we will use two pointer operators:

1. Reference operator (&)

2. Dereference operator (*)




  Step by step logic of the given program:


1. Accept two numbers from user declare variable say no1 & no2.


2. Use third variable(temp) to swap two numbers, shown as follow:

temp=*ptr1;

*ptr1=*ptr2;

*ptr2=temp;


3. Last print swapped numbers.




  C Program to Swap Two Numbers Using Pointers :


#include<stdio.h>

int main()

{


int no1,no2,temp;      

int *ptr1=&no1,*ptr2=&no2;

printf("Enter first number:\n");

scanf("%d",&no1);

printf("Enter second number:\n");

scanf("%d",&no2);  


         temp=*ptr1;

*ptr1=*ptr2;

*ptr2=temp;


printf("Numbers after swapping:\nNumber1=%d\nNumber2=%d",*ptr1,*ptr2);


        return 0;


}


Above program shows the following output:


C Program to Swap Two Numbers Using Pointers


No comments:

Post a Comment

If you have any doubts, please discuss here...👇