Feb 23, 2011 at 9:10am UTC
Calculate the product of odd integers 1 to 10 using while loop and display result.
#include <iostream>
using namespace std;
int main()
{
int count = 1;
int product = 1;
cout << "EXCERISE: Product of odd numbers from 1 to 10 " << endl;
while (count <= 10)
{
count += 2;
product = product * count;
}
cout << " \nProduct of odd number from 1 to 10: " << product << endl;
cout << endl;
system("Pause");
return 0;
}
I keep getting 10395 when it should be 945.
Feb 23, 2011 at 9:23am UTC
You want to swap
1 2
count += 2;
product = product * count;
you can also do it with a for loop:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
#include <iostream>
using namespace std;
int main()
{
int product = 1;
cout << "EXCERISE: Product of odd numbers from 1 to 10 " << endl;
for (int i = 1; i < 10; i += 2)
{
product *= i;
}
cout << " \nProduct of odd number from 1 to 10: " << product << endl;
cout << endl;
system("Pause" );
return 0;
}
Last edited on Feb 23, 2011 at 9:28am UTC
Feb 23, 2011 at 1:00pm UTC
the only problem is while loop condition
it should be while(count<9)
that's it :)
Feb 23, 2011 at 1:54pm UTC
While that would give a correct answer, It makes no sense to have the loop bail at 9 when the top limit is 10. The fundamental problem is that the incrementing of the loop condition is in the wrong place.
Last edited on Feb 23, 2011 at 2:40pm UTC
Feb 23, 2011 at 2:27pm UTC
Note that in most cases, the counter incrementing is done immediately before the comparison. This is a very common pattern that lets you test the condition before doing any processing.
Feb 23, 2011 at 3:16pm UTC
It's because your method is wrong.
1 2 3 4 5
while (count <= 10)
{
count += 2;
product = product * count;
}
These codes calculate 1*3*5*7*9*
11 .
1 2 3 4 5
while (count <= 10)
{
product = product * count;
count += 2;
}
These codes calculate 1*1*3*5*7*9, which gets 945.
Last edited on Feb 23, 2011 at 3:16pm UTC
Feb 23, 2011 at 3:57pm UTC
thank you so much everyone, that was dumb of me.
Feb 23, 2011 at 7:13pm UTC
If you want to make this program to work, just swap line 14 with 15, that's all )