Monday, May 24, 2010

Cannot get this C++ program to compile using bounds.. help plz!?

Okay, this program consists of repeated calls to 2 functions to compute the sum and product of all integers between two bounds. For my example, the user is imputing 3 for lower bound, and 7 for upper bound.





I cannot get this program to compile, and suggestions would be great! I will need to add a count controlled loop to this program later, I will just have to try to figure that out once i can get this portion to work though.





My code so far:





#include %26lt;iostream%26gt;


using namespace std;





int main();


int sum(int lower, int upper){


cout %26lt;%26lt; " Enter a lower and upper bound: ";


cin %26gt;%26gt; lower %26gt;%26gt; upper;





int total = 0; //holds the total that will be returned


for(int i = lower; i %26lt;= upper; i++); //calculate the total


total += i; //returns the total, which is the sum 25 (3 + 4 + 5 + 6 + 7)


return total;


}











Thanks in advance!!

Cannot get this C++ program to compile using bounds.. help plz!?
First you ask for product and now you are asking about sum,. It would be better if you do it yourself
Reply:this should work





#include %26lt;iostream%26gt;





using namespace std;





int getNums(int %26amp;lower, int %26amp;upper);


int sum(int, int);





int main(){


int upper=0, lower=0, total=0;





getNums(lower, upper);


total = sum(upper, lower);


return 0;


}





int sum(int upper, int lower){


int total=0;


for(int i=lower; i%26lt;=upper; i++)


i+=total;





return total;


}





int sum(int %26amp;lower, int %26amp;upper){


cout %26lt;%26lt; "Type a lower and upper bounds:\n";


cin %26gt;%26gt; lower;


cin %26gt;%26gt; upper;


return 0;


}
Reply:In C++, to get this to compile you have a bad arrangement of braces that must be remedied. I'll show them in a better light below.





#include %26lt;iostream%26gt;


using namespace std;





int sum(void){//definition of function. { required.





int lower, upper;


cout %26lt;%26lt; " Enter a lower and upper bound: ";


cin %26gt;%26gt; lower %26gt;%26gt; upper;


int total = 0; //holds the total that will be //returned


for(int i = lower; i %26lt;= upper; i++){ //calculate the //total


total += i; //returns the total, which is the sum //25 (3 + 4 + 5 + 6 + 7)


}//end of for loop.


return total;


} // end of function sum.





int main(){


cout %26lt;%26lt; sum();


return 0;


}// end of main.





I've got it so it will compile, so start in from there and reread any material you've got on what demarcates a function in C/C++. I hope this helps. Pivy.


No comments:

Post a Comment