Thursday, February 14, 2013

swap two values with third variable



using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    public class swapClass 
    {
        // Swap using third variable
        public  void swapMethod(ref int a, ref int b)
        {
            int Temp;
            Temp = a;
            a = b;
            b = Temp;
        }
    }
    public class Program
    {
        static void Main(string[] args)
        {
            swapClass obj = new swapClass();
            int a=10;
            int b=20;
            Console.WriteLine("Before Swap A= "+a + " B ="+b);
            obj.swapMethod(ref a, ref b);
            Console.WriteLine("After Swap A= " + a + " B =" + b);
            Console.ReadLine();
        }
    }
}

No comments: