c-sharp
  1. c-sharp-program-swap-numbers-in-cyclic-order-using-call-by-reference

Program Swap Numbers in Cyclic Order Using Call by Reference - (C# Basic Programs)

Swapping numbers in cyclic order is a common programming exercise that helps improve problem-solving skills. In this tutorial, we will discuss a program to swap two numbers in cyclic order using call by reference in C# programming language.

Syntax

The syntax for swapping numbers in cyclic order using call by reference in C# is as follows:

static void swap(ref int a, ref int b, ref int c) {
  int temp = a;
  a = c;
  c = b;
  b = temp;
}

Example

using System;

public class Program {
  public static void Main() {
    int num1 = 10, num2 = 20, num3 = 30;
    Console.WriteLine("Before swapping:");
    Console.WriteLine("num1 = " + num1);
    Console.WriteLine("num2 = " + num2);
    Console.WriteLine("num3 = " + num3);
    swap(ref num1, ref num2, ref num3);
    Console.WriteLine("After swapping:");
    Console.WriteLine("num1 = " + num1);
    Console.WriteLine("num2 = " + num2);
    Console.WriteLine("num3 = " + num3);
  }

  static void swap(ref int a, ref int b, ref int c) {
    int temp = a;
    a = c;
    c = b;
    b = temp;
  }
}

Output:

Before swapping:
num1 = 10
num2 = 20
num3 = 30
After swapping:
num1 = 30
num2 = 10
num3 = 20

Explanation

Swapping numbers in cyclic order involves swapping the values of three variables in the order A -> B -> C -> A. In this C# program, we use call by reference to pass the values of the three variables to the swap() function. Inside the swap() function, we use a temporary variable to store the value of A, then swap the values of A, B, and C in the desired order.

Use

Swapping numbers in cyclic order using call by reference in C# is a great exercise for practicing problem-solving skills and learning how to use call by reference in C#. It can help programmers to become more familiar with the concept of function calls by reference, which is a powerful tool for manipulating variables within a program.

Summary

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

Published on: