Write a program to swap the contents of two variables in C++

Index « Previous Next »

Question

Write a program that prompts the user to enter number in two variables and Swap the contents of the variables.

Source Code

#include <stdio.h> int main() { int num1, num2, temp; printf("Enter first number :"); scanf("%d", &num1); printf("Enter second number :"); scanf("%d", &num2); temp = num1; num1 = num2; num2 = temp; printf("After swapping, first is %d and second is %d.", num1, num2); return 0; }

Output

Enter first number :10 Enter second number :15

After swapping, first is 15 and second is 10.

Last update on August 19 2022 21:50:43 (UTC/GMT +8 hours)

Write a C program that swaps two numbers without using third variable.

Pictorial Presentation:

Write a program to swap the contents of two variables in C++

Sample Solution:

C Code:

#include<stdio.h> int main() { int x, y; printf("Input value for x & y: \n"); scanf("%d%d",&x,&y); printf("Before swapping the value of x & y: %d %d",x,y); x=x+y; y=x-y; x=x-y; printf("\nAfter swapping the value of x & y: %d %d",x,y); return 0; }

Sample Output:

Input value for x & y: Before swapping the value of x & y: 5 7 After swapping the value of x & y: 7 5

Flowchart:

Write a program to swap the contents of two variables in C++

C programming Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a C program that accepts a distance in centimeters and prints the corresponding value in inches.
Next: Write a C program to shift given data by two bits to the left.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Share this Tutorial / Exercise on : Facebook and Twitter

How to check substring exists in a string in C?

if(strstr(sent, word) != NULL) { /* ... */ }

Note: strstr returns a pointer to the start of the word in sent if the word word is found.

Ref : https://bit.ly/2VOpo2K

  • Exercises: Weekly Top 16 Most Popular Topics
  • SQL Exercises, Practice, Solution - JOINS
  • SQL Exercises, Practice, Solution - SUBQUERIES
  • JavaScript basic - Exercises, Practice, Solution
  • Java Array: Exercises, Practice, Solution
  • C Programming Exercises, Practice, Solution : Conditional Statement
  • HR Database - SORT FILTER: Exercises, Practice, Solution
  • C Programming Exercises, Practice, Solution : String
  • Python Data Types: Dictionary - Exercises, Practice, Solution
  • Python Programming Puzzles - Exercises, Practice, Solution
  • C++ Array: Exercises, Practice, Solution
  • JavaScript conditional statements and loops - Exercises, Practice, Solution
  • C# Sharp Basic Algorithm: Exercises, Practice, Solution
  • Python Lambda - Exercises, Practice, Solution
  • Python Pandas DataFrame: Exercises, Practice, Solution
  • Conversion Tools
  • JavaScript: HTML Form Validation

Last update on August 19 2022 21:51:29 (UTC/GMT +8 hours)

Write a program in C to swap two numbers using the function.

C programming: swapping two variables

Swapping two variables refers to mutually exchanging the values of the variables. Generally, this is done with the data in memory.

The simplest method to swap two variables is to use a third temporary variable :

define swap(a, b) temp := a a := b b := temp

Pictorial Presentation:

Write a program to swap the contents of two variables in C++

Sample Solution:

C Code:

#include<stdio.h> void swap(int *,int *); int main() { int n1,n2; printf("\n\n Function : swap two numbers using function :\n"); printf("------------------------------------------------\n"); printf("Input 1st number : "); scanf("%d",&n1); printf("Input 2nd number : "); scanf("%d",&n2); printf("Before swapping: n1 = %d, n2 = %d ",n1,n2); //pass the address of both variables to the function. swap(&n1,&n2); printf("\nAfter swapping: n1 = %d, n2 = %d \n\n",n1,n2); return 0; } void swap(int *p,int *q) { //p=&n1 so p store the address of n1, so *p store the value of n1 //q=&n2 so q store the address of n2, so *q store the value of n2 int tmp; tmp = *p; // tmp store the value of n1 *p=*q; // *p store the value of *q that is value of n2 *q=tmp; // *q store the value of tmp that is the value of n1 }

Sample Output:

Function : swap two numbers using function : ------------------------------------------------ Input 1st number : 2 Input 2nd number : 4 Before swapping: n1 = 2, n2 = 4 After swapping: n1 = 4, n2 = 2

Flowchart:

Write a program to swap the contents of two variables in C++

C Programming Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a program in C to find the square of any number using the function.
Next: Write a program in C to check a given number is even or odd using the function.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.

How to check substring exists in a string in C?

if(strstr(sent, word) != NULL) { /* ... */ }

Note: strstr returns a pointer to the start of the word in sent if the word word is found.

Ref : https://bit.ly/2VOpo2K

Swapping two number in C programming language means exchanging the values of two variables. Suppose you have two variable var1 & var2. Value of var1 is 20 & value of var2 is 40. So, after swapping the value of var1 will become 40 & value of var 2 will become 20. In this blog will understand how to swap two variables in C.

We will look at each one of them one by one.

Swapping Two Numbers Using Third Variable

Logic
The idea behind swapping two numbers using 3rd variable is simple. Store the value of 1st variable in temporary variable. Store the value of 2nd variable in the first variable. At last, store the value of temp variable in 2nd variable. In this program, we are using a temporary variable to hold the value of the first variable.

  • Assign var1 value to a temp variable: temp = var1

  • Assign var2 value to var1: var1 = var2

  • Assign temp value to var2: var2 = temp

Code:

temp = var1; var1 = var2; var2 = temp;

Now, let’s look at the complete code.

Example

#include <stdio.h> int main() { int var1, var2, temp; printf("Enter two integersn"); scanf("%d%d", &var1, &var2); printf("Before SwappingnFirst variable = %dnSecond variable = %dn", var1, var2); temp = var1; var1 = var2; var2 = temp; printf("After SwappingnFirst variable = %dnSecond variable = %dn", var1, var2); return 0; }

Output:

Write a program to swap the contents of two variables in C++

Moving on with this article on Swapping of Two Numbers in C

Swapping Two Numbers Using Without Using Third Variable

In this variation of swapping two variables, we are not using any temporary variable to store the value. In the first variable we are storing the sum of both variable. Then, in next step we are we are extracting the value of 1st variable by subtracting the value of 2nd variable form the sum & storing it in 2nd variable. At last, we are extracting the original value of the 2nd variable & storing it in the 1st variable.

Code:

var1 = var1 + var2; var2 = var1 - var2; var1 = var1 - var2;

Now, let’s look at the complete code.

Example

#include <stdio.h> int main() { int var1, var2, temp; printf("Enter two integersn"); scanf("%d%d", &var1, &var2); printf("Before SwappingnFirst variable = %dnSecond variable = %dn", var1, var2); var1 = var1 + var2; var2 = var1 - var2; var1 = var1 - var2; printf("After SwappingnFirst variable = %dnSecond variable = %dn", var1, var2); return 0; }

Output:

Write a program to swap the contents of two variables in C++

Moving on with this article on Swapping of Two Numbers in C

Swapping Function in C

You can create a swapping function in C implementing any of the swapping variation, wherein you can call the function anytime when you want to swap two variables. Since we want the local variables of main to modified by swap function, we must them using pointers.

Example

void swap(int *num1, int *num2) { int temp = *num1; *num1 = *num2; *num2 = temp; } int main() { int var1, var2; printf("Enter Value of var1 "); scanf("%d", &var1); printf("nEnter Value of var2 "); scanf("%d", &var2); swap(&var1, &var2); printf("nAfter Swapping: var1 = %d, var2 = %d", var1, var2); return 0; }

Output:

Write a program to swap the contents of two variables in C++

Moving to the next variation we have swapping two numbers using pointers.

Swap two numbers using pointers in C

You can also swap two variables using pointers, wherein you pass the address of the variables to two different variables. Then, swap their values.

Code

num1 = &var1; num2 = &var2; temp = *num2; *num2   = *num1; *num1   = temp;

Now, let’s look at the complete code.

Example

#include <stdio.h> int main() { int var1, var2, *num1, *num2, temp; printf("Enter the value of var1 and var2n"); scanf("%d%d", &var1, &var2); printf("Before Swappingnvar1 = %dnvar2 = %dn", var1, var2); num1 = &var1; num2 = &var2; temp = *num2; *num2 = *num1; *num1 = temp; printf("After Swappingnvar1 = %dnvar2 = %dn", var1, var2); return 0; }

Output:

Write a program to swap the contents of two variables in C++

Moving to the last variation of swapping variables in C. Let’s understand how to swap two variables using bitwise XOR operator.

Swap Two Numbers Using Bitwise XOR

XOR operator works in the similar manner as swapping without using temporary variable works. We extract calculate the XOR of both the variables. Then we extract individual values and swap them.

Suppose var1 = 20 and var2 = 40. The binary values of 20 = 10100 and 40 = 101000.

Example:

Var1 = Var1 ^ Var2 Var1 = 10100 ^ 101000

Var1 = 111100

Var2 = Var1 ^ Var2 Var2 = 111100 ^ 101000

Var2 = 10100

Var1 = Var1 ^ Var2; Var1 = 111100 ^ 10100 Var1 = 101000

Final Values after swapping 2 numbers: var1 = 40 and var2 = 20

var1 = var1 ^ var2; var2 = var1 ^ var2;

var1 = var1 ^ var2;

Now, let’s look at the complete code.

#include <stdio.h> int main() { int var1, var2, temp; printf("Enter two integersn"); scanf("%d%d", &var1, &var2); printf("Before SwappingnFirst variable = %dnSecond variable = %dn", var1, var2); var1 = var1 ^ var2; var2 = var1 ^ var2; var1 = var1 ^ var2; printf("After SwappingnFirst variable = %dnSecond variable = %dn", var1, var2); return 0; }

Output:

Write a program to swap the contents of two variables in C++

Now after going through the above programs you would have understood all the variations of swapping two numbers in C. I hope this blog is informative and added value to you.

Now after executing the above program you would have understood the Swapping of Two Numbers in C. Thus we have come to an end of this article on ‘Quicksort in Java’. If you wish to learn more, check out the Java Training by Edureka, a trusted online learning company. Edureka’s Java J2EE and SOA training and certification course is designed to train you for both core and advanced Java concepts along with various Java frameworks like Hibernate & Spring.

Got a question for us? Please mention it in the comments section of this blog and we will get back to you as soon as possible.