Carbon Program for Swap Points

In this we will learn about two ways to swap two numbers in carbon, and those are mentioned below:

  1. Using a temporary variable.
  2. without using a temporary variable.

1. Using a Temporary Variable

The idea for this approach for swapping two numbers is simple:

  1. Assign the x variable to a temporary variable: temp = x
  2. Assign the y variable to the x variable: x = y
  3. Assign a temporary variable to the y variable: y = temp

Below is the Carbon program to implement swapping with temporary variable approach:

package sample api;

fn Main() -> i32 {

    // using temp variable
    var x: i32 = 1;
    var y: i32 = 2;
    var temp: i32 = x;
    x = y;
    y = temp;


    Print("SWAPPING");
    Print("x: {0}", x);
    Print("y: {0}", y);

    return 0;
}
enter fullscreen mode

exit fullscreen mode

Output:

SWAPPING
x: 2
y: 1
enter fullscreen mode

exit fullscreen mode

2. Without using temporary variables

The idea for this approach for swapping two numbers is simple:

  • Assign y the sum of x and b i.e. y = x + y.
  • Assign the x difference of y and x i.e. x = y – x.
  • Assign y to the difference of y and x i.e. y = y – x.

Below is the Carbon program to implement the swapping without temporary variable approach:

package sample api;

fn Main() -> i32 {

    // without temporary variable
    var x: i32 = 10;
    var y: i32 = 2;

    y = x + y;
    x = y - x;
    y = y - x;

    Print("SWAPPING");
    Print("x: {0}", x);
    Print("y: {0}", y);

    return 0;
}
enter fullscreen mode

exit fullscreen mode

Output:

SWAPPING
x: 2
y: 10
enter fullscreen mode

exit fullscreen mode

learn more

You can find more content like this at Programeeksclub.com

Leave a Comment