Daniel Duffy
C++ author, trainer
- Joined
- 10/4/07
- Messages
- 10,437
- Points
- 648
how to swap two numbers without temp program in c(++)
The question is ambiguous.
Without 'temp variables' you mean? I suppose you don't mean a 'temp program'?(?)
how to swap two numbers without temp program in c(++)
integers? doubles? no temp variables?how to swap two numbers without temp program in c(++)
nope! you are using two extra temp variables A & BGeneral idea
A = a
B = b
A = A*B = (ab)
B = b
B = A/B = (ab/b) = a
A = (ab)
A = A/B = (ab/a) = b
A = b
B = a
this is a question i see in the baruch interview booknope! you are using two extra temp variables A & B
a and b are given, you have no more resources
yeap !To be quite blunt, how does swap() prove you can program! It's so K&R..
There's more to life than that.
1. If a and b are double, who cares?
2. It they are array, use std::move.
nope! you are using two extra temp variables A & B
a and b are given, you have no more resources
// Roundoff.cpp
// DD
#include <iostream>
#include <iomanip>
namespace NOT_STL_SWAP
{
template <typename T>
void swap(T& a, T& b)
{
a = a + b; // a += b !!
b = a - b;
a = a - b;
}
}
int main()
{
using NOT_STL_SWAP::swap;
float a = 1.0F;
float b = 1.0001012345679F;
int N = 1;
for (int n = 1; n <= N; ++n)
{
swap(a, b);
}
std::cout << std::setprecision(8) << a << ", " << b << '\n';
a = 1.0F;
b = 1.0001012345679F;
for (int n = 1; n <= N; ++n)
{
std::swap(a, b);
}
std::cout << std::setprecision(8) << a << ", " << b << '\n';
return 0;
}
namespace YET_NOT_STL_SWAP
{
template <typename T>
void swap(T& a, T& b)
{
a * / b;
b = a / b;
a = a / b;
}
}
no i meant a and b as the values themselves, i shouldve clarified.
A, B are the var names.
example
int A = 4
int B = 5
A *=B -> A = 20
B = A/B -> B = 4
A = A/B ->A= 5
now A = 5, B = 4
yeap?yeap !