×

C Programs

C Basic & Conditional Programs

C Looping Programs

C String Programs

C Miscellaneous Programs

How to swap two numbers without using a temporary variable using C program?

C program to swap two integer numbers without using temporary variable: Here, we will learn how to swap numbers without taking help of another variable in C?

Problem statement

Given two integer numbers "a" and "b" and we have to swap their values without using any temporary variable.

Example

Input: a=10, b=20
Output: a=20, b=10

Logic to swap number using temporary variable

In this program, we are writing code that will swap numbers without using other variable.

  • Step 1: Add the value of a and b and assign the result in a.
    a = a+b;
  • Step 2: To get the swapped value of b: Subtract the value of b from a (which was the sum of a and b).
    b = a-b;
  • Step 3: To get the swapped value of a: Subtract the value of b from a.
    a = a-b;

These are the above written three statements to swap two numbers:

//swapping numbers
a = a+b;	//step 1
b = a-b;	//step 2
a = a-b; 	//step 3

Let’s understand with the values:

Input: a=10 and b=20 

Step1: a = a+b → a= 10+20  → a=30
Now: a=30 and b=20

Step2: b = a-b → a= 30-20  → b=10
Now: a=30 and b=10

Step3: a = a-b → a= 30-10  → a=20
Now: a=20 and b=10

Values are swapped now,
Output: a=20 and b=10

Program to swap numbers without using temporary variable in C

#include <stdio.h>

int main()
{
    //variable declarations
    int a,b;
	
    //Input values
    printf("Enter the value of a: ");
    scanf("%d",&a);
    printf("Enter the value of b: ");
    scanf("%d",&b);	
	
    //Numbers before swapping
    printf("Before swapping... a: %d, b: %d\n",a,b);
	
    //swapping numbers
    a = a+b;	//step 1
    b = a-b;	//step 2
    a = a-b; 	//step 3
	
    //Numbers after swapping 
    printf("After swapping...  a: %d, b: %d\n",a,b);

    return 0;
}

Output

First run:
Enter the value of a: 10
Enter the value of b: 20
Before swapping... a: 10, b: 20 
After swapping...  a: 20, b: 10 

Second run:
Enter the value of a: -100  
Enter the value of b: -200  
Before swapping... a: -100, b: -200  
After swapping...  a: -200, b: -100  

In first run, the input values of a and b are 10 and 20 respectively, after swapping values of a and b are 20 and 10 (swapped values).

Same as second run, the input values of a and b are -100 and -200 respectively, after swapping values of a and b are -200 and -100 (swapped values).

C Basic Programs »

Related Programs

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.