C Program: Swap Two Numbers (w/ Pointers)

In our earlier two programs for swapping numbers, we have done so with the use of simple assignment and arithmetic operators.

Here, we will be making use of pointers.

Two pointers *p and *q of type int are declared to hold the addresses of two input integers a and b.

We make use of a third variable temp to temporarily hold a value. Swapping is done for the values at the addresses which the pointers *p and *q hold.

				
				#include <stdio.h>
				int main() {
					int a, b, *p, *q,temp;
					// read input numbers
					printf("a: ");
					scanf("%d", &a);
					printf("b: ");
					scanf("%d", &b);
					// assign addresses of a & b to pointers p & q
					p = &a;
					q = &b;
					// swapping starts
					temp = *q;
					*q = *p;
					*p = temp;
					printf("a and b after swapping: %d and %d ", a, b); 
					return 0;
				}