C# Program to Swap 2 Numbers


This is a C# Program to swap 2 numbers.

Problem Description

This C# Program Swaps 2 Numbers.

Problem Solution

It obtains two numbers from the user and swaps the numbers using a temporary variable.

Program/Source Code

Here is source code of the C# program that swaps two numbers. The C# program is successfully compiled and executed with Microsoft Visual Studio. The program output is also shown below.

 * C# Program to Swap two Numbers
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Program
    class Program
        static void Main(string[] args)
            int num1, num2, temp;
            Console.Write("\nEnter the First Number : ");
            num1 = int.Parse(Console.ReadLine());
            Console.Write("\nEnter the Second Number : ");
            num2 = int.Parse(Console.ReadLine());
            temp = num1;
            num1 = num2;
            num2 = temp;
            Console.Write("\nAfter Swapping : ");
            Console.Write("\nFirst Number : "+num1);
            Console.Write("\nSecond Number : "+num2);
Program Explanation

In this C# program, we are reading the numbers using ‘num1’ and ‘num2’ variables respectively. Interchange the values of the ‘num1’ and ‘num2’ variables using temporary variable ‘t’. Print the swapped value of 2 numbers.

Runtime Test Cases
Enter the First Number : 23
Enter the Second Number : 25
After Swapping :
First Number : 25
Second Number : 23

Sanfoundry Global Education & Learning Series – 1000 C# Programs.

If you wish to look at all C# Programming examples, go to 1000 C# Programs.

Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He is Linux Kernel Developer & SAN Architect and is passionate about competency developments in these areas. He lives in Bangalore and delivers focused training sessions to IT professionals in Linux Kernel, Linux Debugging, Linux Device Drivers, Linux Networking, Linux Storage, Advanced C Programming, SAN Storage Technologies, SCSI Internals & Storage Protocols such as iSCSI & Fiber Channel. Stay connected with him @ LinkedIn | Youtube | Instagram | Facebook | Twitter