All about swapping variables, using temp, without temp, call by value and call by reference.

// The purpose of this program is to learn different swap methods
#include<stdio.h>
// This is my function to print values of a and b
void printmyvars(int a,int b)
{
 printf("\na= %3d b =%3d",a,b);
 return;
}

void swapCallByValue(int a,int b)
{
 int temp;
 temp = a;
 a=b;
 b=temp;
 printf("\nInside swapCallByValue");
 printmyvars(a,b);
 printf("\nFinished swapCallByValue");
 return;
}

void swapCallByReference(int* a,int* b)
{
 int temp;
 temp = *a;
 *a=*b;
 *b=temp;
 printf("\nInside swapCallByReference");
 printmyvars(*a,*b);
 printf("\nFinished swapCallByReference");
 return;
}

void main()
{

 int a = 5, b=17;
 printmyvars(a,b);
 // Swap using temp variable
 int temp;
 temp = a;
 a=b;
 b=temp;
 printmyvars(a,b);
// Swap without using temp variable
 a=a+b;
 b=a-b;
 a=a-b;
 printmyvars(a,b);
 swapCallByValue(a,b);
 printmyvars(a,b);
 swapCallByReference(&a,&b); 
 printmyvars(a,b);
return;
}

About Sumant Sumant

I love Math and I am always looking forward to collaborate with fellow learners. If you need help learning math then please do contact me.
This entry was posted in Programming and tagged . Bookmark the permalink.

Leave a comment