Is Armstrong Number--2 test cases fail

#include<bits/stdc++.h>
using namespace std;
int main()

{
int n;
cin>>n;

int r,ans=0,count=0;

while(n>0)
{
r=n%10;
count++;
n=n/10;
}
while(n>0)
{
r=n%10;
ans=ans+ pow(r,count);
n=n/10;
}
if(ans==n)
cout<<“true”<<endl;
else
cout<<“false”<<endl;
return 0;

}

Hello @Ankur-Ankur-937479863269311,

Always share your code using online Coding Blocks IDE.
The way you have shared it may cause syntax errors.
STEPS:

  1. Paste your code on https://ide.codingblocks.com.
  2. Save your code there.
  3. Share the URL generated.

Now coming back to your code:
Problem:
After first while loop, the value of n will reduce to 0.
So, second while loop will never execute.Thus, ans will remain 0.
Hence, your code will always return true.
Solution:
Use another variable and assign it the value of n.

Modified Code:

Hope, this would help.
Give a like if you are satisfied.

1 Like