C code snippet to generate Kaprekar’s magical constant 6174
#include < stdio.h >
#include < conio.h >
void asc(int *a) // to sort the array elements in ascending order
{
int i,j;
for(j=1;j < 4;j++)
{
for(i=0;i < (4-j);i++)
{
if(a[i] > a[i+1])
{
int temp=a[i+1];
a[i+1]=a[i];
a[i]=temp;
}
}
}
}
int* desc(int *a) //to sort the array elements in descinding order{
int b[4],i,j;
for(i=3,j=0; i > =0;i–,j++)
b[j]=a[i];
return b;
}
int magic(int *n) // Function to find out the magic number
{
int a[4],*d,i=0,anum=0,dnum=0,diff;
static int count=1,prev=0;
for(i=0; i < 4; i++) // To read each digit of the number into an array
{
a[i]=(*n)%10;
*n=(*n)/10;
}
asc(a);
d=desc(a);
for(i=0;i < 4;i++) // Loop to get the number fron array elements
{
anum=anum*10+a[i];
dnum=dnum*10+d[i];
}
diff=dnum-anum;
if(diff==prev)
{
printf("%d",diff);
return count;
}
prev=diff;
count++; // To find out number of iterations
magic(&diff);
}
void main()
{
int num,cnt;
printf(“Enter any 4 digit number: “);
scanf(“%d”,&num);
cnt=magic(&num);
printf(“\n%d”,cnt);
}
More details on http://code-maniac.blogspot.com
To find more code snippets in C, C++, Java, HTML, PHP, MySQL, PL/SQL and forms of Free Online Programming Tutorials Click Here
Related posts:
- How to generate the magical Kaprekar’s number 6174
- C-code snippet to print a file by removing comments
- A handy C-code snippet for all the programmers…
- Useful JavaScript code snippet to save your website content from being copy-pasted!
- C# code snippet for demonstration of data casting!
Filed Under: Archive Categories
