swap program

hello I have to write a swap program for school and im on break now so i have no access to help.. the program has to look somewhat like this
#include <iostream>
using namespace std;

float lbstokg(float);
int variable;
void main ()
{
float lbs,kgs;

cout << "enter your weight in pounds";
cin >> lbs;
variable=lbstokg(lbs);
cout << "your weight in kilograms is " << variable;
system ("pause");
}

//lbstokg()
//converts pounds to kilograms
float lbstokg (float pounds)
{
float kilograms=0.45392*pounds;
return kilograms;
}




because thats what we learned for that week I know i could just put in a swap but we learned the swap function a week later so its against policy to re do something after you learned another way to do something. My professor wants the code all in the main and this is what I have so far

{
float num1,num2, number3;

cout << "enter a first number";
cin >> num1;
cout << "enter a second number";
cin >> num2;
float num1tonum2 (float number3);
float num2tonum1=number3;
cout << number3;



system ("pause");

}


all I need it to do is display the second number than the first number.
I think im close
thanks for the help






Not sure, if you studied reference, but this will get what you want. Basically it takes num1 and num2 from standard input and swaps their values.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
swap(float& f1, float& f2)
{
  float tmp = f1;
  f1 = f2;
  f2 = tmp;
}

void main()
{
  float num1,num2;

  cout << "enter a first number";
  cin >> num1;
  cout << "enter a second number";
  cin >> num2;

  swap(num1, num2);

  cout << num1 << endl;
  cout << num2 << endl;



  system ("pause");

}
Last edited on
yea we studied it but we used swap (num1, num2) the week after. is there any other way to do it
There is another way you can do in the main itself, without using swap.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
void main()
{
  float num1, num2;

  cout << ....
  cin >> num1;

  cout << ...
  cin >> num2;

  num1 = num1 + num2;  //Following 3 will swap num1, num2 values
  num2 = num1 - num2;
  num1 = num1 - num2;

  cout << num1 << endl; // Display swapped values
  cout << num2 << endl;
}
Last edited on
thanks so much
Topic archived. No new replies allowed.