How to swap two numbers in C#

5 Answers

0 votes
using System;

class Program
{
    static void Main() {
        int x = 345;
        int y = 10;
        
        int tmp = x;
        x = y;
        y = tmp;

        Console.Write(x + " " + y);
    }
}





/*
run:

10 345         

*/

 



answered Aug 22, 2022 by avibootz
0 votes
using System;

class Program
{
    static void Main() {
        int x = 345;
        int y = 10;
        
        x = x + y; 
        y = x - y;
        x = x - y; 

        Console.Write(x + " " + y);
    }
}





/*
run:

10 345         

*/

 



answered Aug 22, 2022 by avibootz
0 votes
using System;

class Program
{
    static void Main() {
        int x = 9382;
        int y = 55;
        
        x = x * y; 
        y = x / y; 
        x = x / y; 

        Console.Write(x + " " + y);
    }
}





/*
run:

55 9382        

*/

 



answered Aug 22, 2022 by avibootz
0 votes
using System;

class Program
{
    static void Swap<T> (ref T a, ref T b) {
        T temp = a;
        a = b;
        b = temp;
    }
    static void Main() {
        float x = 3.14f;
        float y = 7.89f;
         
        Swap(ref x, ref y);
 
        Console.Write(x + " " + y);
    }
}




/*
run:

7.89 3.14

*/

 



answered Nov 5, 2022 by avibootz
0 votes
using System;
 
class Program
{
    static void Swap<T> (ref T a, ref T b) {
        T temp = a;
        a = b;
        b = temp;
    }
    static void Main() {
        int x = 3;
        int y = 7;
          
        Swap(ref x, ref y);
  
        Console.Write(x + " " + y);
    }
}
 
 
 
 
/*
run:
 
7 3
 
*/

 



answered Apr 19, 2023 by avibootz

Related questions

1 answer 185 views
185 views asked Apr 30, 2019 by avibootz
1 answer 201 views
1 answer 202 views
202 views asked Apr 8, 2014 by avibootz
1 answer 100 views
100 views asked Apr 19, 2023 by avibootz
1 answer 199 views
1 answer 103 views
103 views asked Sep 24, 2021 by avibootz
...