Here we have a Programe for Interchange Variable Using Third Variable.First of all we have to declare three num1,num2 and temp which is type of Integer.
int num1,num2,temp;
Then We need to take input form user for num1 and num2. Make sure You don't forget & while Taking Input inside 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 inputed from user by using 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 to implement Interchange Varibable using Thired Variable.
Here We have Variable temp. we are first put num1 into temp variable.when we are doing this, we have num1 value in temp variable.
now, we assign num2 value to num1 and similarly assign temp value to num1.so,what will happen here,when you assign num2 value to num1.The value of num2 will move in num1 and that's we need.
now, we you are assign temp value to num2, a temp has num1 value so that num2 has num1 value indirectly.
temp = num1;
num1 = num2;
num2 = temp;
Then we print the values after swap which we takes from user by using 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 Using Third Variable.
*/
#include<stdio.h>
int main(){
int num1,num2,temp;
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);
temp = num1;
num1 = num2;
num2 = temp;
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 : 11.808 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 : 2.572 s Press any key to continue.
0 Comments