I have to write a loop code that sorts the inputs from a user from lowest to highest when they enter 2 separate integers. This loops 3 times. Then at the end it is suppose print out the sum of all the integers entered. My code is printing the sum between each request for integers rather than at the end. How can I have it only print at the end.
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
usingnamespace std;
/**
* This program uses if statments to sort 2 integers entered in by a user in
* numerical order from lowest to highest. Then it will find the sum of all
* the integers entered and the average.
*
* @creator
*/
int main(int, char**) {
for(int i= 0, sum=0; i<3; ++i) {
int x,y;
cout<<"Enter 2 integers: ";
cin>>x>>y;
if (x>y)
cout<<x<<" "<<y<<" sorted is "<<y<<" "<<x<<endl ;
else
cout<<x<<" "<<y<<" sorted is "<<x<<" "<<y<<endl;
sum+= x+y;
cout <<sum<<endl;
}
(void) system("pause");
return EXIT_SUCCESS;
}
When I have tried taking the cout for the sum out of the for{ } statement it comes back with an error code saying the sum has changed as well as an obsolete binding error.
[name lookup of `sum' changed for new ISO `for' scoping]
[using obsolete binding at `sum']
This code shows the cout sum outside the for statement but it won't compile because of the above errors. Same kind problem if I pull the sum+= out of the for statement
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
usingnamespace std;
/**
* This program uses if statments to sort 2 integers entered in by a user in
* numerical order from lowest to highest. Then it will find the sum of all
* the integers entered and the average.
*
* @creator
int main(int, char**) {
for(int i= 0, sum=0; i<3; ++i) {
int x,y;
cout<<"Enter 2 integers: ";
cin>>x>>y;
if (x>y)
cout<<x<<" "<<y<<" sorted is "<<y<<" "<<x<<endl ;
else
cout<<x<<" "<<y<<" sorted is "<<x<<" "<<y<<endl;
sum+= x+y;
}
cout <<sum<<endl;
(void) system("pause");
return EXIT_SUCCESS;
} */
#include <iostream>
usingnamespace std;
/**
* This program uses if statements to sort 2 integers entered in by a user in
* numerical order from lowest to highest. Then it will find the sum of all
* the integers entered and the average.
*
* @creator Kelly McAbee
*/
int main()
{
int sum = 0;
for(int i=0; i<3; ++i)
{
cout<<"Enter 2 integers: ";
int x, y;
cin >> x >> y;
if(!cin)
return 1;
if (x>y)
cout<<x<<" "<<y<<" sorted is "<<y<<" "<<x<<endl;
else
cout<<x<<" "<<y<<" sorted is "<<x<<" "<<y<<endl;
sum += x + y;
}
cout << "The sum is: " << sum << endl;
//todo work out average
cout << "Press any key to continue . . .\n";
cin.ignore(99999, '\n');
cin.get();
}