C code snippet to generate Kaprekar’s magical constant 6174

A handy C code snippet to generate the 4 digit Kaprekar’s 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:

  1. How to generate the magical Kaprekar’s number 6174
  2. C-code snippet to print a file by removing comments
  3. A handy C-code snippet for all the programmers…
  4. Useful JavaScript code snippet to save your website content from being copy-pasted!
  5. C# code snippet for demonstration of data casting!

Filed Under: Archive Categories

About the Author

Om is a dynamic entrepreneur, renowned author, and founder of Webfosys Networks Pvt Ltd that provides IT, content creation, SEO & Website Design services to several clients across the globe. He has written over 12,000 articles, and loves to write Tech Reviews and Auto Reviews Reach him 24/7 - om.thoke86@gmail.com

Leave a Reply




If you want a picture to show with your comment, go get a Gravatar.