Thursday , September 21 2017
Home / C / C program for Magic number

C program for Magic number

This is a C program for Magic number.

A Magic number is a number whose sum of digits eventually leads to 1.
Example#1:  19 ;  1+9 =10 ; 1+0 = 1.  Hence a magic number.
Example#2:  224; 2+2+4=10; 1+0 =1.  Hence a magic number.
Example#3:  874; 8+7+4=19; 1+9=10; 1+0=1.  Hence a magic number.

Also Check: Java program to check for a magic number

#include <stdio.h>
int singledigit(int x)       // Recursive function that will return the sum of every single digit
{
    if(x/10==0)
        return x;
    else
        return singledigit(x%10)+singledigit(x/10);     // It will calculate the sum of the digits of the number.
}
int main()
{
    int n;
    printf("ENTER NUMBER\n");    // To input a number
    scanf("%d",&n);
    while(n/10!=0)
    {
        n=singledigit(n);     // Calculate the sum of the digits until you get a single digit i.e from 0 to 9 and then check if it is 1
    }
    if(n==1)       // After you get a single digit then check if the sum of the digits is eventually 1 then it is magical else not
        printf("Number is magic");
    else
        printf("numebr is not magic");
}

OUTPUT:

C program for magic number
C program for magic number

Check Also

How to Solve Linear Equation in One Variable In C Programming?

C Program to Solve any Linear Equation in One Variable Find complete C program to ...

One comment

  1. THE PROGRAMMEE IS NICE BUT IF IT IS TO BE DIFFICULT TO UNDERSTAND

Leave a Reply

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