Simple Swap Program:
#include <stdio.h>
int main()
{
int a = 23, b = 47;
int t;
printf("Before. a: %d, b: %d\n", a, b);
t = a;
a = b;
b = t;
printf("After. a: %d, b: %d\n", a, b); return 0;
}
Out Put:
% cc -o swap_simple0 swap_simple0.c
% swap_simple0
#include <stdio.h>
#include <stdio.h>
int main()
{
int a = 23, b = 47;
int t;
printf("Before. a: %d, b: %d\n", a, b);
t = a;
a = b;
b = t;
printf("After. a: %d, b: %d\n", a, b); return 0;
}
Out Put:
% cc -o swap_simple0 swap_simple0.c
% swap_simple0
Before. a: 23, b: 47
After. a: 47, b: 23
Using Exclusive-OR
int main()
{
int a = 23, b = 47;
printf("Before. a: %d, b: %d\n", a, b);
a ^= b;
b ^= a;
a ^= b;
printf("After. a: %d, b: %d\n", a, b); return 0;
}
Out Put:
% cc -o swap_simple1 swap_simple1.c
% swap_simple1
Before. a: 23, b: 47
After. a: 47, b: 23
Using Preprocessor Directive:
#define swap(type, i, j) {type t = i; i = j; j = t;}
int main()
{
int a = 23, b = 47;
printf("Before swap. a: %d, b: %d\n", a, b);
swap(int, a, b)
printf("After swap. a: %d, b: %d\n", a, b); return 0;
}
Out Put:
% cc -o swap_p swap_p.c
% swap_p
Before swap: a: 23, b: 47
After swap: a: 47, b: 23
Swap Program with Functions
#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);
}
Out Put:
% cc -o swap1 swap1.c
% swap1
Before. a: 23, b: 47
After. a: 47, b: 23
C++: Swap Program Using References:
#include <iostream>
C++: Swap Program Using References:
#include <iostream>
using std::cout;
void swap(int& i, int& j)
{
int t = i;
i = j;
j = t;
}
int main()
{
int a = 23, b = 47;
cout << "Before. a: " << a << ", b: " << b << "\n";
swap(a, b);
cout << "After. a: " << a << ", b: " << b << "\n";
return 0;
}
Out Put:
% CC -o swap_CC swap.cpp
% swap_CC
Before: a: 23, b: 47
After: a: 47, b: 23
No comments:
Post a Comment