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
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:
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?
Test your Programming skills with w3resource's quiz.
- New Content published on w3resource:
- HTML-CSS Practical: Exercises, Practice, Solution
- Java Regular Expression: Exercises, Practice, Solution
- Scala Programming Exercises, Practice, Solution
- Python Itertools exercises
- Python Numpy exercises
- Python GeoPy Package exercises
- Python Pandas exercises
- Python nltk exercises
- Python BeautifulSoup exercises
- Form Template
- Composer - PHP Package Manager
- PHPUnit - PHP Testing
- Laravel - PHP Framework
- Angular - JavaScript Framework
- Vue - JavaScript Framework
- Jest - JavaScript Testing Framework