C Program to Swap Two Numbers without using Temporary Variables and Bitwise Operations

This is a C Program to swap two integers without using temporary variables and bitwise operations.

Problem Description

This C Program swap two integers without using temporary variables and bitwise operations.

Problem Solution

Take input from the user and swap two integers without using bitwise operations as shown in the program below.

Program/Source Code

Here is source code of the C Program to swap two integers without using temporary variables and bitwise operations. The C program is successfully compiled and run on a Linux system. The program output is also shown below.

/*
 * C Program to Swap two Integers without using Temporary Variables 
 * and Bitwise Operations
 */
#include <stdio.h>
 
// Function Prototype
void swap(int *, int *);
 
void main()
{
    int x, y;
    printf("Enter 2 nos: \n");
    scanf("%d %d", &x, &y);
    printf("\nYou have entered x = %d y = %d \n", x, y);
    swap(&x,&y);    // passing the 2 nos to the swap function
}
 
// function to swap the two numbers
void swap(int *a, int *b)
{
    *a = *a + *b;
    *b = *a - *b;
    *a = *a - *b;
    printf("Swapped . . . .\n"); // printing the swapped numbers
    printf("x = %d y = %d\n", *a, *b);
}
Program Explanation

In this C Program, we are reading the integer value using ‘x’ and ‘y’ variables respectively. The swap function is used to swap the two numbers.

advertisement
advertisement

Compute the summation of ‘a’ and ‘b’ variable values and the difference of ‘a’ and ‘b’ variable values. Assign the swapped numbers to the ‘a’ and ‘b’ variables. Print the swap of two integers using printf statement.

Runtime Test Cases
 
$ gcc bit28.c
$ a.out
Enter 2 nos:
4
7
 
You have entered x=4 y=7
Swapped . . . .
x=7 y=4

Sanfoundry Global Education & Learning Series – 1000 C Programs.

Here’s the list of Best Books in C Programming, Data-Structures and Algorithms

If you wish to look at programming examples on all topics, go to C Programming Examples.

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.