Write A program for Swapping in C# ?

0 votes
75 views
Rahul Ahuja asked 09-Sep-2018 in programming by Rahul Ahuja
edited 09-Sep-2018 by Rahul-Ahuja

1). With temp variable And  2). Without Temp variable ?

1 Answer

0 votes
Sanat Shukla answered 10-Sep-2018 by Sanat Shukla

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");
        }
    }
}