Saturday, January 21, 2023

C# Sharp program to swap two numbers

 Write a C# Sharp program to swap two numbers.

Swapping:

Swapping in computer science means shuffling or interchanging. Mutually exchanging two values is called swapping.

Using a temporary variable :

The simplest method to swap two variables is to use a third temporary variable. The temporary variable is used to keep the value of one of the variables temporarily. The values in variables may be a numeric or alphabetic or any other characters I.e. alphanumeric, symbols etc. Temporary variable is a third variable along with two other variables carrying values. Temporary variable is empty but initialized at declaration and no value is assigned. The value is assigned at the time of shuffling of variables. For this , the value of one variable carrying values is assigned to the temporary variable thus that variable becomes empty. Now the value of the other value variable is assigned to the first recently emptied variable. At the end the value of the temporary variable is assigned to the second variable. Now the temporary variable is again empty and both the numbers are swapped. The same is shown in figure.

 

Psuedo code:

Here is the psuedo code for swapping two numbers.

define swap(x, y)

    temp := x

    x := y

y := temp

Code:

C# code for swapping the two numbers is here:

using System; 

public class Exercise1 { 

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: 5

Input the second number: 4

After swapping:

First number: 4

Second number: 5

Here is the flowchart of the above program:












 

No comments:

Post a Comment

Popular Posts