Error in this code

i cant understand the error in this code. Pls help

this is the cb ide link

Hey @vector.9974

#include <iostream>
#include <cmath>

using namespace std;

int main()
{
    int n;
    cin>>n;
    int r, x;
    int sum = 0;
	int m=n; //added this
    int count = 0;
    while ( n > 0)
        {
            n/= 10;
            count++;
        }
	n=m;//added this otherwise n became 0 and next loop will nor wokr
    while ( n > 0)
    {
        r = n % 10;
        x = pow(r, count);
        sum+= x;
        n/=10;
    }
	n=m;//added this otherwise n became 0 and next condition will nor work

    (sum == n)?cout<<"true":cout<<"false"; //you have ti print true or false

    return 0;
}

Here did the required changes in your code :slight_smile:
If this resolves your query then please mark it as resolved:)

thank you for the solution sir. I want to ask that why the value of n which was initially taken from the user and had a local scope within the int main function

Due to this n becomes 0 that’s why we reinitialized it to original value

Same goes for this

Pls ignore the above message

thank you for the solution sir. I want to ask that why the value of n which was initially taken from the user and had a local scope within the int main function. That value of n shouldnt be changed by the application of a loop as the variable that goes inside a loop is destroyed when it comes out of it.

Bro n you are using in loop is the one that you initialized in main
you are not creating another n inside loop which will become local to it .

int n;
cin>>n;
while(...){
      n+=10;//this n belongs to n and have scope of main
}

while(...){
     int n=20;//this n is local to this loop and have scope till end of this loop
}

thanks a lot sir…

1 Like