Thursday, February 14, 2013

swap two values without third variable



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

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

            Console.ReadLine();
        }
    }
}

1 comment:

Deepak jaiswal said...

good example
This change my concept good one
thanks for your post
keep it up man