C program to Swap two Numbers using Pointers

In this C Programming example, we will implement the program to swap two numbers using pointers and print the output on the console.

1. How to Swap two Numbers?

In this program, we are given two numbers and we have to swap those numbers using a temporary variable.

Example

Input:
Before Swapping
number 1 = 10 and number 2 = 20

Output:
After Swapping
number 1 = 20 and number 2 = 10

Helpful topics to understand this program better are-


2. C program to Swap two Numbers using Pointers

Let’s discuss the execution(kind of pseudocode) for the program to swap two numbers using pointers in C.

  1. Initially, the program will prompt the user to enter two numbers, number1 and number2.
  2. Then number1 and number2 are passed in the swappingNumbers() function as int *a, int *b respectively.
  3. In the void swappingNumbers(int *a,int *b) function we declare a temporary variable int temp and then
    • assign *a to temp
    • assign *a to *b
    • again re-assign *b to temp.
  4. In this way, the numbers are swapped and then we print them on the console.

Let us now implement the above execution of the program to swap two numbers using pointers in C.

#include <stdio.h>

void swapNumbers(int *a, int *b) {
  int temp;
  temp = *a;
  *a = *b;
  *b = temp;
}

int main() {
  int number1, number2;
  printf("Enter the value of number1: ");
  scanf("%d", &number1);
  printf("Enter the value of number2: ");
  scanf("%d", &number2);

  printf("Before Swapping the numbers: number1 is: %d, number2 is: %d\n",
         number1, number2);

  swapNumbers(&number1, &number2);

  printf("After Swapping the numbers we have: number1 is: %d, number2 is: %d\n",
         number1, number2);
  return 0;
}
Output
Enter the value of number1: 55
Enter the value of number2: 44
Before Swapping the numbers: number1 is: 55, number2 is: 44
After Swapping the numbers we have: number1 is: 44, number2 is: 55

3. Conclusion

In this C Programming example, we have discussed how to swap two numbers using the pointers in C and also discussed the execution and pseudocode in detail.


Helpful Links

Please follow C Programming tutorials or the menu in the sidebar for the complete tutorial series.

Also for the example C programs please refer to C Programming Examples.

All examples are hosted on Github.


Recommended Books


An investment in knowledge always pays the best interest. I hope you like the tutorial. Do come back for more because learning paves way for a better understanding

Do not forget to share and Subscribe.

Happy coding!! 😊

Recommended -

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x