Please help me with the task: "Swap the values"

Hello, I’m working on this task:

  1. Write a program that swaps the values of two int variables x and y, using a third variable to temporarily hold one value. Initial values for x and y are already given. The output of the program should be “x is {x} and y is {y}” after you swap the values. Use string interpolation.

Here is my code:


class SwapTheValues
{
   static void Main()
   {
       int x = 10;
       int y = 20;
   }
}

Can anyone please help me to solve it?

Alright, for this one you need to create a third int. You can call it whatever you want. You’re going to want to assign that new int to x to save it’s value. Then you will assign x to y’s value. After that you will assign y to the new int’s value. Sorry if this is confusing but here’s what I mean. Try this code:

using System;

class SwapTheValues
{
static void Main()
{
int x = 10;
int y = 20;
int z = x;
x = y;
y = z;
Console.WriteLine($“x is {x} and y is {y}”);
}
}

2 Likes