Write A program for Swapping in C# ?

Asked 09-Sep-2018
Updated 09-Sep-2018
Viewed 464 times

0

1 Answer


0

1). Swapping With Temporary variable

using System;

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

namespace ConsoleApplication7
{

    class Program
    {
        static void Main(string[] args)
        {
            int A, B, temp;
            Console.Write("\nEnter the First Number(for A) : ");
            A = int.Parse(Console.ReadLine());
            Console.Write("\nEnter the Second Number(for B) : ");
            B = int.Parse(Console.ReadLine());
            temp = A;
            A = B;
            B = temp;
            Console.Write("\nAfter Swapping : ");
            Console.Write("\nFirst Number A is : " + A);
            Console.Write("\nSecond Number B is : " + B);
            Console.Read();
        }
    }
}

2). Without temp variable used in swapping 

  1.  Use + and -
  2. Use *and /

* and /

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication8
{
    class Program
    {
        public static void Main(string[] args)
        {
            int a = 15, b = 30;
            Console.WriteLine("Before swap a= " + a + " b= " + b);
            a = a * b; //a=450 (15*30)
            b = a / b; //b=15 (450/30)
            a = a / b; //a=30 (450/15)
            Console.Write("After swap a= " + a + " b= " + b);
            Console.WriteLine("\n");
        }
    }
}

+ and -

using System;

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

namespace ConsoleApplication8
{
    class Program
    {
        public static void Main(string[] args)
        {
            int a = 30, b = 10;
            Console.WriteLine("Before swap a= " + a + " b= " + b);
            a = a + b;
            b = a - b;
            a = a - b;
            Console.Write("After swap a= " + a + " b= " + b);
            Console.WriteLine("\n");
        }
    }
}