Why isnt my Product of Digits program in c++ not working?

Hey there, I was about to use a function which would give me the product of digits in a program, it was not giving me the desired values. Please help me figure the problem out.
Thanks in advance!
Code:
#include<bits/stdc++.h>

using namespace std;

//Product Of Digits:

long long product(int num){

long long pl;

while(num != 0)

{

    pl = pl * (num % 10);

    num = num / 10;

}

return pl;

}

int main()

{

int n;

cin>>n;

cout<<product(n)<<endl;

return 0;

}

Please either format your code or (better!) link to your submission - the forum software has mangled it and it won’t compile! :slight_smile:

1 Like

The problem I see is you didn’t initialize pl so it’s having garbage value and you are using it in your calculations. Change this line to long long pl = 1;, now it should work.

write long long pl=1;
what happens is when you dont assign a value, it allot random value to your pl;

Just reading the compiler warnings would have revealed the issue immediately:

[simon@simon-laptop][08:09:31]
[~/devel/hackerrank/otherpeoples]>./compile-latest-cpp.sh 
Compiling anirbansaha010-blah.cpp
+ g++ -std=c++14 anirbansaha010-blah.cpp -O3 -g3 -Wall -Wextra -Wconversion -DONLINE_JUDGE -D_GLIBCXX_DEBUG -fsanitize=undefined -ftrapv -fno-sanitize-recover
anirbansaha010-blah.cpp: In function ‘long long int product(int)’:
anirbansaha010-blah.cpp:21:12: warning: ‘pl’ may be used uninitialized in this function [-Wmaybe-uninitialized]
     return pl;
            ^~
anirbansaha010-blah.cpp: In function ‘int main()’:
anirbansaha010-blah.cpp:15:12: warning: ‘pl’ may be used uninitialized in this function [-Wmaybe-uninitialized]
         pl = pl * (num % 10);
         ~~~^~~~~~~~~~~~~~~~~
anirbansaha010-blah.cpp:9:15: note: ‘pl’ was declared here
     long long pl;
               ^~
+ set +x
Successful
1 Like