C Program for Magic Number

programming

Problem: Write a C program to check whether a number is Magic Number or not.

A magic number is that number whose sum of the digits is when multiplied by the reverse of the same sum results back the original number.

Example: 1729

Magic number in C

Steps to Check Magic Number in C

  1. Input a number.
  2. Calculate the sum of its digits.
  3. Multiply the computed sum with its reverse.
  4. check if the product is equal to the input number.
  5. If Yes, then the given number is Magic number else not.

Here is the implementation of same in C.


#include <stdio.h>
#include <stdlib.h>
 
int main()
{
    int num, temp, rev=0, digit, sumOfDigits=0;
 
    printf("Enter a Number \n");
    scanf("%d",&num);
    
    
    temp = num;
 
    //Calculating Sum of digits
    while(temp > 0){
        //Extract digit and add them
        sumOfDigits += temp % 10;  
        temp = temp / 10;      
    }

 
   temp = sumOfDigits;

    //Compute reverse of Sum of Digits

    while( temp > 0){
        rev = rev*10 + temp % 10; 
        temp = temp / 10;
    }
 
    if(rev*sumOfDigits == num)
        printf("Magic Number \n");
    else
        printf("Not a Magic Number \n");
 
    return 0;
}

Output

C Program for magic Number

In this tutorial, we learned to check magic number in C.

Leave a Reply

Your email address will not be published. Required fields are marked *