Product w/functions problems

The problem asks me to ask for a number between 3 and 8. The calculate the product between 2 and that number. So if the number chosen was 5, the result would be 2x3x4x5=120. I have to use a function to return the the total. and I have to display the numbers that i calculated as well as the answer. So far I have the base of the equation, but everytime I try different equations for my answer, it returns an "undefined value". Below is what I have so far:

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
int product (int num) {
int total;
while (( total*num) <=num) {
total = (num*num);
}
return total;
}
int main() {
int num;
cout<< "please enter a number from 3 to 8: ";
cin>> num;
cout<< num;
cout<< endl;
if (( num<3) || (num>8)) {
cout<< "please follow the directions!";
cout<< endl;
}
else {
int total;
cout<< "=";
cout<< total;
cout<< endl;
}
return 0;
}
You never call your product function in main. In the "else" condition you're declaring a new local variable in main and trying to print out whatever the uninitialized value is in total.

1
2
3
4
5
else 
{
	int total;
	cout<< "=" << total << endl;
}


You're also not initialing the total variable in the function either before you try to use it to multiply.

1
2
3
4
5
6
7
8
9
int product (int num) 
{
	int total;
	while (( total*num) <=num) 
	{
		total = (num*num);
	}
	return total;
}


edit: I think your formula isn't going to give you the result you want.

1
2
while (( total*num) <=num) {
total = (num*num);


assume total is initialized to 1
user entered 5 as num (so they want to multiply 2*3*4*5)
while (total*num) <=5 (while 1*5 <=5)
total = num*num (total = 5*5, or 25)

I might do this with a for loop, printing out with each iteration of the loop so you can see the equation.
1
2
3
4
5
6
7
8
9
10
11
int product (int num) 
{
	int total=2; //minimum number you start with
	cout << total;
	for (int i=3; i<=num; i++)
	{
		total*=i;
		cout << " * " << i;
	}
	return total;
}


please enter a number from 3 to 8: 
2 * 3 * 4 * 5 = 120
Last edited on
Topic archived. No new replies allowed.