Hi folks, what’s happening? My last tutorial was about Calculate circumference, area and perimeter in C. Let’s look at how to swap two numbers in C Programming Language.This is the sixth program of [I] section of Chapter 1:Getting Started of the book, “Let us C” by “Yashwant Kanetkar”.Do let us know if you have any doubts or suggestions in the comments section below.
Question:
Two numbers are input through the keyboard in two locations C and D. Write a C program to interchange the contents of C and D.
Solution to swap two numbers in C
We accept two numbers from the user. We write a function swap with two parameters to allocate the memory locations. We then use a temporary location to store a number and then swap the numbers. We then, display the swapped numbers in the console. This program also displays the use of pointers.
Download the solution:
Download ProgramProgram to swap two numbers in C
#include<stdio.h> #include<conio.h> void main() { int a,b; clrscr(); printf("Enter two numbers separated by space: "); scanf("%d%d",&a ,&b); printf("\nBefore swapping: "); printf("%d %d",a,b); swap(&a,&b); printf("\nAfter swapping: "); printf("%d %d", a, b); getch(); } swap(int *x, int *y) { int t; t = *x; *x = *y; *y = t; }
Output
Enter two numbers separated by a space: 4 2
Before swapping: 4 2
After swapping: 2 4