w3resource
C# Sharp Programming Exercises

C# Sharp Exercises: Program to swap two numbers


C# Sharp Basic: Exercise-5 with Solution

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;
public class Exercise5
{
       public static void Main(string[] args)
         {
            int number1, number2, temp;
            Console.Write("\nInput the First Number : ");
            number1 = int.Parse(Console.ReadLine());
            Console.Write("\nInput the Second Number : ");
            number2 = int.Parse(Console.ReadLine());
            temp = number1;
            number1 = number2;
            number2 = temp;
            Console.Write("\nAfter Swapping : ");
            Console.Write("\nFirst Number : "+number1);
            Console.Write("\nSecond Number : "+number2);
            Console.Read();
        }
}

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:

Improve this sample solution and post your code through Disqus

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?



New Content: Composer: Dependency manager for PHP, R Programming