In: Computer Science
Make a function that swaps the values that change the values between the parameters as the following rule.
The functions swap takes 2, 3 or 4 parameters and these functions are implemented as the overloading functions.
Below is the swapping program in c# with given requirement. Added comments for each method for better understanding
using System;
namespace SwapNumbers
{
class Program
{
static void Main(string[] args)
{
//default values given in the question are as below
int num1 = 15;
int num2 = 5;
int num3 = 30;
int num4 = 40;
//call overloaded swap functions
swap(num1, num2);
swap(num1, num2, num3);
swap(num1, num2, num3, num4);
Console.ReadLine();
}
static void swap(int num1, int num2)
{
int temp;
Console.WriteLine("Before swapping the numbers, num1 is {0} and num2 is {1}", num1, num2);
temp = num1;
num1 = num2;
num2 = temp;
Console.WriteLine("After swapping the numbers, num1 is {0} and num2 is {1}", num1, num2);
Console.WriteLine("*********************************************************************");
}
//This will print number in [min, medium, max] order
static void swap(int num1, int num2, int num3)
{
int min, medium, max;
Console.WriteLine("Before swapping the numbers, num1 is {0}, num2 is {1} and num3 is {2}", num1, num2, num3);
//Get samallest number among three numbers by calling smallestNumber method
min = smallestNumber(num1, num2, num3);
//Get medium number among three numbers by calling mediumNumber method
medium = mediumNumber(num1, num2, num3);
//Get larget number among three numbers by calling largestNumber method
max = largestNumber(num1, num2, num3);
Console.WriteLine("After swapping the numbers, num1 is {0}, num2 is {1} and num3 is {2}", min, medium, max);
Console.WriteLine("*********************************************************************");
}
//This will print number in circular-shift-right [A, B, C, D] = > [B, C, D, A]
static void swap(int num1, int num2, int num3, int num4)
{
int temp;
Console.WriteLine("Before swapping the numbers, num1 is {0}, num2 is {1}, num3 is {2} and num4 is {3}", num1, num2, num3, num4);
temp = num1;
num1 = num2;
num2 = num3;
num3 = num4;
num4 = temp;
Console.WriteLine("After swapping the numbers, num1 is {0}, num2 is {1}, num3 is {2} and num4 is {3}", num1, num2, num3, num4);
Console.WriteLine("*********************************************************************");
}
public static int smallestNumber(int num1, int num2, int num3)
{
int min = num1;
if (num2 < min)
min = num2;
if (num3 < min)
min = num3;
return min;
}
public static int largestNumber(int num1, int num2, int num3)
{
int max = num1;
if (num2 > max)
max = num2;
if (num3 > max)
max = num3;
return max;
}
public static int mediumNumber(int a, int b, int c)
{
if ((a < b && b < c) || (c < b && b < a))
return b;
else if ((b < a && a < c) || (c < a && a < b))
return a;
else
return c;
}
}
}
Below is the output screenshot