Did I do something wrong?

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.
closed account (z05DSL3A)
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
the only problem is while loop condition
it should be while(count<9)
that's it :)
closed account (z05DSL3A)
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
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.
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
thank you so much everyone, that was dumb of me.
If you want to make this program to work, just swap line 14 with 15, that's all )
Topic archived. No new replies allowed.