Pre-Requisite:
1.Basic knowledge of C language
2.Coding logic understanding
3.Basic knowledge of pointers
As we have mentioned in the heading that we need to swap two numbers using the pointer concept.
Basic logic:
1.Give header file and main function
2.Declare a function prototype with void return-type and 2 pointers of integer datatype as arguments.
3.Print statement for the first element.
4.Take input.
5. Repeat steps 3 and 4 for the second element as well.
6.call the function in which you need to swap it by giving addresses of variables as elements.
7.Print the result of the swapped elements
8.Define the function where you need to swap the elements.
9.Inside the function; declare a temporary variable.
10.Assign the value of the first pointer variable to the temporary variable
11.Now, assign the value of the second pointer variable to the first.
12.Now, assign the value of the temporary variable to the second pointer variable.
#include<stdio.h>
void swap(int *, int *);
int main()
{
int a, b;
printf("\nenter the numbers you want to enter\n");
scanf("%d", &a);
scanf("%d", &b);
printf("\nBefore swapping: %d\n%d\n", a, b);
swap(&a, &b);
printf("\nAfter swapping:%d\n%d\n", a, b);
return 0;
}
void swap(int *p, int *q)
{
int temp;
temp = *p;
*p = *q;
*q = temp;
}
How the code works??
- After taking input as the first variable(a) and input of the second variable(b). The function is called where the addresses(&) of both variables are kept as parameters.
2. Now the addresses of variables are stored in the pointer variables.
3. Again the argument is passed and it goes on to the function definition where the values of the addresses are to be passed then by simple swapping and exchanging of values from *p to the temporary variable and then *q to the *p and at last temporary variable is stored at *q.
4. After this, the values are printed.
5. The difference between the normal swapping and swapping of the pointer is in normal swapping the values are exchanged while in pointer swapping the addresses are exchanged and it is more memory efficient.
If you find any issue on this article please contact us.
Join the what’s app for more information.