Articles

# In this chapter of C++ program tutorial out task is:

• Write a c++ program to check whether a number is magic number or not

### C++ program to check a number is Magic number or not

Below is the C++ program to check a number is magic or not.

``````/*  Program Name : To check whether a number is Magic or not
Program Author : Sayantan Bose
*/
#include <iostream>
using namespace std;

int magic(int n)
{
int s,r;
while(n>9)
{
s=0;
while(n!=0)
{
r=n%10;
s=s+r;
n=n/10;
}
n=s;
}

return s;
}

int main() {
int n,sum;
cout<<"Enter the number to be checked : ";
cin>>n;
if(n>9)
sum=magic(n);
else
sum=n;
if(sum==1)
cout<<n<<" is a Magic number";
else
cout<<n<<" is not a Magic number";
return 0;
}
``````

#### OUTPUT

Enter the number to check Magic number:

1234
1234 is a Magic number
Or

Enter the number to check Magic number:

53
53 is not an Magic number

EXPLANATION :

In the above c++ program to check if a number is Magic or not:

• A number is said to be Magic if and only if the recursive sum of its digits is equal to 1.
• For example: 1234 is a Magic number. Because the recursive sum i.e. 1+2+3+4=10, 1+0=1.
• In the method magic, we are calculating the sum of each digit of the inputed number also at the same time we are keeping in check that the loop is running untill we get a single digit sum. And then the sum is returned to the main method.
• In the main method the sum is then compared with 1.
• If both of them turn out to be equal the number is a Magic number else it isn't.

āYou can see the above code execution and output in codeblocks IDE:

CPP Programs

Would you like to see your article here on tutorialsinhand. Join Write4Us program by tutorialsinhand.com