Tuesday, 19 March 2019

C program to swap two numbers using temporary variable(method 1)

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 1: Using third variable
#include<stdio.h>
int main(){
    int num1=10,num2=20;
    void swapUsingTemp(int,int);  //function prototype
   printf("Values before swapping by call by value: num1=%d,num2=%d.\n",num1,num2);
    swapUsingTemp (num1,num2);
    return 0;
}
//function definition: using third variable
void swapUsingTemp (int n1,int n2){
  int temp;
  temp=n1;
  n1=n2;
  n2=temp;
  printf("Inside swap1 : 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