C Program to swap two numbers using a temporary variable.

29 Dec 2022 Balmiki Kumar 0 C Programming

C Programming: Swap Two Numbers with a Temporary Variable

A program to swap two numbers using a temporary variable is a computer program written in the C programming language that allows the user to input two numbers and swap their values using a temporary variable

In this program, a temporary variable is used to hold the value of one of the numbers while the values of the two numbers are interchanged. This is a commonly used technique to swap the values of two variables in programming languages.

Logic: 

step1: temp=x;
step2: x=y;
step3: y=temp;

Example:

if x=5 and y=8, consider a temporary variable temp.
step1: temp=x=5;
step2: x=y=8;
step3: y=temp=5;
Thus the values of the variables x and y are interchanged.

 

Swapping Two Numbers in C: Using a Temporary Variable

#include<stdio.h>
int main() {
 int a, b, temp;
 printf("Enter the value of a and b: \n");
 scanf("%d %d", &a, &b);
 printf("Before swapping a=%d, b=%d \n", a, b);
 /*Swapping logic */
 temp = a;
 a = b;
 b = temp;
 printf("After swapping a=%d, b=%d", a, b);
 return 0;
}

Output:

Enter the values of a and b: 2 3
Before swapping a=2, b=3
After swapping a=3, b=2

 

BY: Balmiki Kumar

Related Blogs

Post Comments.

Login to Post a Comment

No comments yet, Be the first to comment.