Swap variables in different languages

 

C swap variables (using pointers)

#include <stdio.h>

void swap(int *i, int *j) {
int t = *i;
*i = *j;
*j = t;
}

void main() {
int a = 23, b = 47;
printf(“Before. a: %d, b: %d\n”, a, b);
swap(&a, &b);
printf(“After . a: %d, b: %d\n”, a, b);
}

PHP swapping two variables

<?php

function swap(&$a, &$b) {
$a = $a ^ $b;
$b = $a ^ $b;
$a = $a ^ $b;
}

$a = 41;
$b = 12;

echo $a . ‘ – ‘ . $b . ‘<br>’;
swap($a, $b);

echo $a . ‘ – ‘ . $b . ‘<br>’;

Ruby swap two variables

In ruby you dont have to write a function for it, its included in the language by default.

x,y = y,x

C# swap variables

class Program
{
static void FunkySwap<T>(T a, T b, Action<T> setA, Action<T> setB)
{
T tempA = a;
setA(b);
setB(tempA);
}
static void Main(string[] args)
{
string s1 = “big”;
string s2 = “apples”;
Console.WriteLine(“BEFORE, s1: {0}, s2: {1}”, s1, s2);
FunkySwap(s1, s2, a => s1 = a, b => s2 = b);
Console.WriteLine(“AFTER,  s1: {0}, s2: {1}”, s1, s2);
}
}

Perl swap numbers or strings

my $a = "TeXT-1";
my $b = "TeXT-2";
print "Original : $a - $b\n";
($a,$b) = ($b,$a);
print "Swap : $a - $b\n";

Python – swap numbers

a = 2
b = 3
print a, b
a, b = b, a
print a, b

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>