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]|
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
usingnamespace 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?
#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 */
}
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.