Friday, 4 December 2015

Magic number in C

Magic Number

Magic Number is a number whose sum of digits (until one digit remains) is 1.
There can be many ways to implement the Magic Number.This is one of the methods to do so.

Examples of Magic number:

235 is a magic number because 2 + 3 + 5 = 10  => 1 + 0 = 1
657 is not a magic number because 6 + 5 +7 = 18 => 1 + 8 = 9

Below is the code for magic number in C:

#include<stdio.h>
#include<conio.h>

int main()
{
int n,s1=0,s=0,r;
printf("enter a number\n");
scanf("%d",&n);
while(n!=0)
{
r=n%10;
s=s+r;
n=n/10;
}
while(s!=0)
{
s1=s1+(s%10);
s=s/10;
}
if(s1==10|| s1==1)
printf("Magic number");
else
printf("Not a magic number");
getch();
}

Below is the Output:

1st test case:







2nd test case:












No comments:

Post a Comment