Swap Two Numbers Without a Temp variable in C

We had previously seen a C Program on How to Swap Two Numbers. In that program, we used a temporary variable. Now, let’s take a look at how to swap two numbers without a temp variable in C. I am referring to an awesome book called “Let us C” by “Yashwant Kanetkar” and I will post solutions to the questions asked in exercises.This is the sixth program of [I] section of Chapter 1: Getting Started of the book. If you are unsure about any part and more information, put it down in the comments section below or look it up on Google if you want a quick response. We try to answer all the queries as soon as possible.

Question:

Two numbers are input through the keyboard in two locations C and D. Write a C program to swap the contents of C and D without using a temp variable.

Solution to Swap Two Numbers Without a Temp variable in C:

First, ask the user to input the two numbers C and D. Then we store both the numbers in variables one and two. Add the numbers and store it in the one variable. Then, subtract the second number from the first and store it in the two variable. Now, subtract the first number from the second and store it in the one variable. The final step is to print the swapped variables.

Download the source code:

Download Program

Program to Swap Two Numbers Without a Temp variable in C:

//C Program to Swap Two Numbers Without a Temp variable in C - ReadMeNow
#include<stdio.h>
#include<conio.h>
  void main()
{
  int one,two;
  clrscr();
  printf("\n Enter two numbers separated by a space - ")
  scanf("\n %d %d",&one,&two);
  one=one+two;
  two=one-two;
  one=one-two;
  printf("\n Swapped numbers are - %d %d",one,two);
  return (0);
}

Output

Enter two numbers separated by a space –  20 33

Swapped numbers are – 33 20

Download the source code:

Download Program

Read Also:

Introduction to C Programming

How to Calculate Simple Interest in C Programming

Check Leap Year in C

Calculate gross salary in C

Print ASCII Values Using While Loop in C Program

cc programc programminghow totutorial
Comments (0)
Add Comment