Categorized | Programming

C code snippet to generate Kaprekar’s magical constant 6174

Posted on 21 September 2008

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);
}


1 Star2 Stars3 Stars4 Stars5 Stars (7 votes, average: 4.43 out of 5)
Loading ... Loading ...

This post was authored by:

om - who has written 106 posts on Tech Pedia.

Om is a freelance writer cum software engineer! Works for a reputed IT company & provides freelancing writing & web-services to several clients in US, Europe, Asia and all over the world! Owns a website,blog &runs a private franchise business whose clients are in fortune 100 listing! For relevant work contact him to om.thoke86@gmail.com

Contact the author

Leave a Reply

Site Sponsors

  • programming freak: And by the way thanks for those useful codes, i am surprised a site like this has C codes? and...
  • programming freak: Keep posting some codes man, i would be glad to find some c/c++/java/html/unix codes, sql queries...
  • programming freak: Hey thanks, good one!
  • Nathaniel Baker: its all good information.. but you forgot one very very important thing…. FAT32 can not...
  • om: Yeah sure it is.. :)

Older Posts

Ads

  • Advertise Here

Topics