w3resource

C#: Program to swap two numbers


C# Sharp Basic: Exercise-5 with Solution

Swap Two Numbers

Write a C# Sharp program to swap two numbers.

C# Sharp: swapping two variables

The act of swapping two variables refers to mutually exchanging the values of the variables. Generall, this is done with the data in memory.

Using a temporary variable :

The simplest method to swap two variables is to use a third temporary variable :

define swap(x, y)
    temp := x
    x := y
    y := temp
C# sharp Exercises: swap two variables

Sample Solution:

C# Sharp Code:

using System;

// This is the beginning of the Exercise5 class
public class Exercise5
{
    // This is the main method where the program execution starts
    public static void Main(string[] args)
    {
        // Declaration of variables to store numbers and temporary value for swapping
        int number1, number2, temp;

        // Prompting the user to input the first number
        Console.Write("\nInput the First Number : ");
        // Reading the first number entered by the user and converting it to an integer
        number1 = int.Parse(Console.ReadLine());

        // Prompting the user to input the second number
        Console.Write("\nInput the Second Number : ");
        // Reading the second number entered by the user and converting it to an integer
        number2 = int.Parse(Console.ReadLine());

        // Swapping the values of number1 and number2 using a temporary variable
        temp = number1;
        number1 = number2;
        number2 = temp;

        // Displaying the result after swapping
        Console.Write("\nAfter Swapping : ");
        Console.Write("\nFirst Number : " + number1); // Displaying the first number after swapping
        Console.Write("\nSecond Number : " + number2); // Displaying the second number after swapping

        Console.Read(); // Keeping the console window open until a key is pressed
    }
}

Sample Output:

Input the First Number : 2    
Input the Second Number : 5    
After Swapping :                                                                                              
First Number : 5                                                                                              
Second Number : 2 

Flowchart:

Flowchart: C# Sharp Exercises - Program to swap two numbers

C# Sharp Code Editor:

Previous: Write a C# Sharp program to print the result of the specified operations.
Next: Write a C# Sharp program to print the output of multiplication of three numbers which will be entered by the user.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/csharp-exercises/basic/csharp-basic-exercise-5.php