Here we have a programe for Interchange Variable Without Using Third Variable. First of all, we have to declare two num1, and num2 which is a type of Integer.
int num1,num2;
Then We need to take input from users for num1 and num2. Make sure You don't forget & while Taking Input inside the Scanf statement.
printf("Enter Value of Number 1:");
scanf("%d",&num1);
printf("Enter Value of Number 2:");
scanf("%d",&num2);
Then we print the values which we inputted from the user by using the print statement. Here we are using %d formate specifier because we are using the Integer dataType.
printf("Before Swap Numbers are...\n");
printf("Number 1:%d\nNumber 2:%d",num1,num2);
Here We Have Actual Logic for interchange two variables without using the third variable. for better understand let's take an example.
let's assume we have num1=5 and num2=10.
now we can add num1 and num2 into num1,so it would be like this num1 = num1 + num2. after doing this, the value of num1 is 15.
now, we want to num2 value 5. then we easily do. we just need to do num1 - num2 and it's store in num2 after doing this it will look like this
num2 = num1 - num2 so we have value 5 in num2 and that's what we want. now we want value 10 in num1.
for as of now we have num1=15 and num2=5. from this value, we can get num1=10.so just do num1 = num1 - num2. and we get num1=10, so this is how you can interchange two variables without using a third variable.
num1 = num1 + num2; // 15 = 5 + 10
num2 = num1 - num2; // 10 = 15 - 5
num1 = num1 - num2; // 5 = 15 - 10
Then we print the values after swap which we take from the user by using the print statement.
printf("\nAfter Swap Numbers are...\n");
printf("Number 1:%d\nNumber 2:%d",num1,num2);
Full Code
/**
Write a C program to demonstrate that Interchange Variable Without
Using Third Variable.
*/
#include<stdio.h>
int main(){
int num1,num2;
printf("Enter Value of Number 1:");
scanf("%d",&num1);
printf("Enter Value of Number 2:");
scanf("%d",&num2);
printf("Before Swap Numbers are...\n");
printf("Number 1:%d\nNumber 2:%d",num1,num2);
num1 = num1 + num2;
num2 = num1 - num2;
num1 = num1 - num2;
printf("\nAfter Swap Numbers are...\n");
printf("Number 1:%d\nNumber 2:%d",num1,num2);
return 0;
}
OUTPUT
Run 1:
Enter Value of Number 1:-5 Enter Value of Number 2:-10 Before Swap Numbers are... Number 1:-5 Number 2:-10 After Swap Numbers are... Number 1:-10 Number 2:-5 Process returned 0 (0x0) execution time : 6.819 s Press any key to continue.
Run 2:
Enter Value of Number 1:5 Enter Value of Number 2:10 Before Swap Numbers are... Number 1:5 Number 2:10 After Swap Numbers are... Number 1:10 Number 2:5 Process returned 0 (0x0) execution time : 4.618 s Press any key to continue.
1 Comments
Thank you, it Helps me
ReplyDelete