easy question

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
#include <cmath>

using namespace std;
int main()
{
    int i;
    int z;
    int x;
    
    for (i = 1; i< 10; i++)
    {
        x = 2;
        z = i * x;
        x++;
        cout<< z<< endl;    
    }
   
    
system ("pause");
return 0;
}


what i am trying to do is this:
Write a program to generate the product of the numbers in the range [1, 10).

my problem is that x++ is not working for some reason and also z should be (1*2*3*4*5*6*7*8*9)
but i dont how to do that
Last edited on
are you saying youre trying to make a times table for the numbers 1-10? if so just make some nested for loops like so:
1
2
3
4
5
for (int i = 1; i <= 10; i++)
{
	for (int j = 1; j <= 10; j++)
		cout << i * j << endl;
}
what i need for the program to do is multiply 1*2*3*4*5*6*7*8*9 =z
but my program overrides the z value and doesnt save it anywhere so i end up with getting all the values differently but i just need 1 answer
1
2
3
4
5
6
    z = 1;
    for (i = 2; i< 10; i++)
    {
        z *= i;   
    }
    cout<< z<< endl; 

the result of z after the loop will be 9! if that's what you're looking for
Last edited on
what is the *= operand called?
and also why do the previous values of z stay o.o i dont get it
Last edited on
i dunno, "times equal" is what i say in my head. think of it like this

z *= i == z = z * i
i got that lol but y does the value of z doesnt get override next time the loops comes around?
sorry about my english i m not the best at it
Last edited on
the value of z does get overwritten every time through the loop. let's walk through it

z == 1
enter loop

i == 2 and 2 < 10
z = z * i (same as z = 1 * 2)
i++

i == 3 and 3 < 10
z = z * i (same as z = 2 *3)
i++

i == 4 and 4 < 10
z = z * i (same as z = 6 * 4)
i++

i == 5 and 5 < 10
z = z * i (same as z = 24 * 5)
i++

i == 6 and 6 < 10
z = z * i (same as z = 120 * 6)
i++

i == 7 and 7 < 10
z = z * i (same as z = 720 * 7)
i++

i == 8 and 8 < 10
z = z * i (same as z = 5040 * 8)
i++

i == 9 and 9 < 10
z = z * i (same as z = 40320 * 9)
i++

i == 10 and 10 !< 10
exit loop

output z (362880)
Last edited on
by using the = operator z is getting a new value each time. what *= does is multiply z by the value on the other side of the = sign. these two statements are equivalent
1
2
z *= 3;
z = z * 3;


so all you need to do your code is this:
1
2
3
int z = 1;
for (int i = 2; i < 10; i++)
    z *= i;


simple see?
Topic archived. No new replies allowed.