C program to swap two numbers using call by reference

 
Swapping two numbers is simple and a fundamental thing. You need not to know any rocket science for swapping two numbers. Simple swapping can be achieved in three steps -
  1. Copy the value of first number say num1 to some temporary variable say temp.
  2. Copy the value of second number say num2 to the first number. Which is num1 = num2.
  3. Copy back the value of first number stored in temp to second number. Which is num2 = temp.

#include <stdio.h>
#include<conio.h>
void swap(int * num1, int * num2);/*Function protoype*/

int main()
{
     int num1, num2;

     /* Input numbers */
     printf("Enter two numbers: ");
     scanf("%d%d", &num1, &num2);

     /* Print original values of num1 and num2 */
     printf("Before swapping in main n");
     printf("Value of num1 = %d \n", num1);
     printf("Value of num2 = %d \n\n", num2);

     /* Pass the addresses of num1 and num2 */
     swap(&num1, &num2);/*Function Call*/

     /* Print the swapped values of num1 and num2 */
     printf("After swapping in main n");
     printf("Value of num1 = %d \n", num1);
     printf("Value of num2 = %d \n\n", num2);

     return 0;
     getch();
}
void swap(int * num1, int * num2)/*Function Defination*/
{
     int temp;

     // Copy the value of num1 to some temp variable
     temp = *num1;

     // Copy the value of num2 to num1
     *num1= *num2;

     // Copy the value of num1 stored in temp to num2
     *num2= temp;

     printf("After swapping in swap function n");
     printf("Value of num1 = %d \n", *num1);
     printf("Value of num2 = %d \n\n", *num2);
}



Run:

No comments:

Post a Comment

100 C Programs with Code and Output

Program 1: C Program To Read Two Numbers And Print The Sum Of Given Two Numbers. Program 2: C Program To Read Three Numbers And Prin...