c-sharp
  1. c-sharp-program-to-swap-two-numbers

Program to Swap Two Numbers - (C# Basic Programs)

Swapping two numbers is a basic programming exercise that helps improve problem-solving skills. In this tutorial, we will discuss a program to swap two numbers using the C# programming language.

Syntax

The syntax for swapping two numbers in C# is as follows:

int temp = num1;
num1 = num2;
num2 = temp;

Example

using System;

class SwapNumbers {
  static void Main(string[] args) {
    int num1 = 10, num2 = 20;
    Console.WriteLine("Before swap: num1 = {0}, num2 = {1}", num1, num2);

    // Swapping logic
    int temp = num1;
    num1 = num2;
    num2 = temp;

    Console.WriteLine("After swap: num1 = {0}, num2 = {1}", num1, num2);
  }
}

Output:

Before swap: num1 = 10, num2 = 20
After swap: num1 = 20, num2 = 10

Explanation

Swapping two numbers involves temporarily storing one of the values in a third variable while the other value is copied into its place. The temporarily stored value can then be copied into the other variable. This process effectively swaps the values of the two variables.

Use

Swapping two numbers is a fundamental programming exercise that is used in a wide variety of programs. It is particularly useful in sorting algorithms, such as bubble sort and insertion sort.

Summary

In this tutorial, we have discussed a program to swap two numbers using the C# programming language. We have seen the syntax, example, explanation, use, and importance of swapping two numbers. By practicing these exercises, programmers can improve their problem-solving skills and become better equipped to tackle complex coding challenges.

Published on: