Swapping is used in sorting
algorithms like in bubble sort,that is when we wish to arrange numbers in a
particular order either in ascending order or in descending order.
Problem:
Given two numbers num1=a and num2=b,
task is exchange values of these numbers i.e num1=b and num2=a;
Method
2: Without using third variable
#include<stdio.h>
int main(){
int
num1=10,num2=20;
void swapWithoutTemp
(int,int); //function prototype
printf("Values
before swapping by call by value: num1=%d,num2=%d.\n",num1,num2);
swapWithoutTemp
(num1,num2);
return 0;
}
//function definition : without using third variable
void swapWithoutTemp(int n1,int n2){
n1=n1+n2;
n2=n1-n2;
n1=n1-n2;
printf("Inside swap2 : num1=%d,num2=%d\n",n1,n2);
}
Output:
Please comment if you find anything incorrect, or you want to improve the topic discussed above.
No comments:
Post a Comment