Program to swap two numbers [4 methods]

0 Suresh Chand June 2, 2021

In this example, We will learn to write c program to swap two numbers. For this, You have to knowledge in following topics.

Download Application: Learn C Programming with Live Compiler

First we will look on algorithm and flowchart then we will look on the code.

Algorithm

This is the algorithm of program to swap two numbers

Step 1: Start

Step 2: Initialize three variables x, y and temp

Step 3: Assign the value of x = 10 and y = 15

Step 4: temp = x;

Step 5: x = y;

Step 6: y = temp;

Step 7: End

Flowchart

This is the flowchart of program to swap two numbers

Flowchart : Program to swap two numbers [4 methods]

Methods or Program to swap two numbers

In this example, We will swap two numbers using 4 methods. Here, We will use following methods.

  • Using Temporary Variable
  • Without using temporary Variable
  • Bitwise Operator Methods
  • Using Multiplication and Division

Let’s look each topics methods individually.

1. Using Temporary Variable

In this methods, We will use one temporary variables. We will assign one variable value to temporary variable and second one to first variable and again assign temporary variable value to second one. Let’s look an code

#include<stdio.h>

int main(){
    
    int x = 10, y = 15, temp;
    
    temp = x;
    x = y;
    y = temp;
    
    printf("x = %d and y = %d", x, y);
    
    return 0;
}

2. Without using temporary Variable

In this methods, We will write program to swap two numbers without using temporary variables.

#include<stdio.h>

int main(){

    int x = 10, y = 15;

    x = x + y - (y = x);
    
    printf("x = %d and y = %d",x,y);

    return 0;

}
Download Application: Learn C Programming with Live Compiler

3. Bitwise Operator Methods

In this methods, We will use Bitwise Operator to swap two numbers.

#include<stdio.h>

int main(){

    int x = 10, y = 15;

    x = x^y;
    y = x^y;
    x = x^y;

    printf("x = %d and y = %d", x, y);

    return 0;

}

4. Using Multiplication and Division

In this methods, We will use multiplication and division to swap two numbers.

#include<stdio.h>

int main(){

    int x = 10, y = 15;
    
    x = x*y;
    y = x/y;
    x = x/y;

    printf("x = %d and y = %d", x, y);

    return 0;

}

The output of above programs is

x = 15 and y = 10
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

Join Our Newsletter Now

Get the latest tutorials, examples and projects updates.

!

Ads

Ads Blocker Detected!!!

We have detected that you are using extensions to block ads. Please support us by disabling these ads blocker.

Disable Ad Block

Want Same System