Lortnok - 9 months ago 49

C++ Question

I am writing a program that should be able to calculate the product of first n-1 digits.

Note: If treble first 2 digits.

The code is working when 4 digits entered , example : 1234 , product is 6 . Cant figure out the treble part

So far I tried this, but no solution:

`using namespace std;`

int main()

{

int n , sum = 0, s,d,k,w, product ;

cout <<"Enter number: " << endl;

cin >> n;

if ((n>1) && (n<10000)) {

{

s= n/10;

d = n/100%10; // 2.

k = n/1000%100%10; //1.

w = n/10%10; //3.

//1234

product = w*d*k;

if ((n>1) && (n<1000)) {

s = n/10;

d = n/100%10; // 2.

k = n/1000%100%10; //1.

w = n/10%10; //3.

product = k*d;

}

cout <<"Sum of digits inp numb is : " << d+k+w << " and product is : " << product << endl;

cout << "w: " << w << " k: " << k << " d: " << d << " s: " << s << endl;

}

}

return 0;

}

Answer

```
if ((n>1) && (n<1000)) {
s = n/10;
d = n/100%10; // 2.
k = n/1000%100%10; //1.
w = n/10%10; //3.
product = k*d;
}
```

This part should be your "treble" part. This line is the issue:

```
product = k*d;.
```

If `n < 1000`

, then k becomes `0%100%10`

which is `0`

. Thus your product is 0. I think your intention was:

```
product = w*d;
```

For the general solution, repeatedly divide and take the running product of the modulus. Like this:

```
n = n/10;
product = 1;
while (n > 0){
product = product * (n%10);
n = n/10;
}
```

Source (Stackoverflow)