Product of digits of a number using a nested loop

Hi. I think I solved an exercise with the following statement: "Write a code to calculate the product of digits of a given number inserted by keyboard. You must use a nested loop". My code works but I am not convinced since I am being advised that for statement has no effect:
|18|warning: statement has no effect [-Wunused-value]|

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
#include <iostream>
#include <stdio.h>
#include <stdlib.h>

using namespace std;

int main()
{
    cout << "Nested Loops - Product of digits of a given number" << endl;

    int num,rest;
    printf("Insert a number: ");
    scanf("%d", &num);

    long product=1;

    while (num!=0) {
        for (product==1; num>0; num=num/10) {
            rest=num%10;
            product=product*rest;
        }
    }
    printf("The product of digits of the given number is: %ld",product);
    return 0;
}


Variables I declare: num, rest as int and product as long.
The nested loop: While (num=!0) for product=1 and number is >0, num=num/10 (Remove the last digit from n, rest=num%10 (Get the last digit from number and multiplies to product.

This code works, however, can this code be improved using a nested loop while and for?

Thank you in advance.
Last edited on
In line 18, product==1 ; has no effect.

> You must use a nested loop

Why is a nested loop required?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <stdio.h>

int main()
{
    int number = 0 ;

    puts( "insert a number" ) ;
    scanf( "%d", &number ) ;

    int product = number != 0 ? 1 : 0 ; /* take care of edge case: number == 0 */
    if( number < 0 ) number = -number ;

    for( ; number != 0 ; number /= 10 ) product *= number%10 ;

    printf( "The product of digits of the given number is: %d", product ); /* %d */
}
Thank you JLBorges. I removed product==1.

I am taking a course of C/C++ but the teacher doesn't want to help us. The course is face-to-face/residential, I don't know if you understand me, is not online. The course lasts 2 months and we are only 7 students, we are still learning loops and nested loops. Since we are learning nested loops we are required to solve this exercise with a nested loop.
Last edited on
Topic archived. No new replies allowed.