C program for Swapping Numbers - using different methods
In this c tutorial we understand the concept of swapping numbers using another variable or without using another variable in C programming language, let's go
Swap number using temporary variable.
#include<stdio.h>
int main() {
int a, b, temp;
printf("Enter first number: ");
scanf("%d", &a);
printf("Enter second number: ");
scanf("%d", &b);
// Swaping code
temp = a;
first = b;
b = temp;
printf("After swapping, first second Numbers= %.d\n", a, b);
return 0;
}
In this program, we are swapping two numbers using another variable temp. Firstly we accepting values from user which are stored in a and b variable.
For accept first number from user:-
printf(" Enter first number: ");
scand(" %d", &a);
For accepting second number from user
printf (" Enter second number: ");
scand ("%d", &b );
For swap number we need to another temporary variable for holding a value
int temp;
Then put/store (a variable) first number into temp variable, a variable store second number that store into variable b, and we know first value store into temp variable This value store into b variable.
temp = a;
a = b;
b = temp;
Swaping is complete using another variable now print output a& b after swapping. Using printf() method.
printf ("after swapping first second numbers= %d",a,b);
Ex.
Let consider
a,b,temp is a variable
a =10; a store value 10
b= 20; b store value 20
temp= 0; temp variable is null
temp=a; value of a assen temp variable
Hence, temp=10
a=b; value of b assen to a
Hence, a= 20
b =temp;. Value of temp assen to b variable
Hence, b=10.
Output
a= 20
b= 10
Swap number without using any another variable
#include<stdio.h>
int main() {
int x, y;
printf("Enter two numbers : ");
scanf("%d %d", &x, &y);
// Swaping code without using variable
x = x - y;
y = x + y;
x = y - x;
printf("After swapping Numbers= %.d\n", x, y);
return 0;
}
In this program, x and y is two variables , user put numbers/ values for swapping .
printf("Enter two numbers: ");
scanf("%d %d", &a, &b);
Then apply logic for swapping Numbers
We are learn using simple example below
Consider :-
x=15 y=9
x = x - y. : x = 15-9
x = 6.
y = x + y. : y = 9+6. Always put leatest value
y = 15
x = y - x. : x= 15 - 6
x = 9
Output
x = 9 y = 15
Recommended for you: