Kaprekar's constant in C
Kaprekar's constant, or 6174, is a constant that arises when we take a 4-digit integer, form the largest and smallest number from its digits, and then subtract these two numbers. Continuing with this process of forming the largest and smallest numbers from the result digits and subtracting again, will always arrive at the number 6174.
//
// https://www.programiz.com/c-programming/online-compiler/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
void biggest(char dptr[]) {
// 1000 - 1 = 999
bool done = false;
char tmp;
while (!done) {
done = true;
for (int i=0; i < 3; i++) {
if (dptr[i] < dptr[i+1]) {
tmp = dptr[i];
dptr[i] = dptr[i+1];
dptr[i+1] = tmp;
done = false;
}
}
}
}
void smallest(char dptr[]) {
char t1,t2;
t1 = dptr[2];
t2 = dptr[3];
dptr[3] = dptr[0];
dptr[2] = dptr[1];
dptr[1] = t1;
dptr[0] = t2;
}
int main() {
char s[6];
char d[4], tmp;
int n,m,r=0;
printf("Kaprekar's constant (6174)\nnumber between 1 and 9998: ");
fgets(s,6,stdin);
int length=strlen(s);
while (length < 5) {
s[length-1] = '0';
length++;
}
s[4]='\0';
while (r != 6174) {
biggest(s);
n = atoi(s);
smallest(s);
m = atoi(s);
r= n-m;
printf("%d - %d = %d\n", n,m,r);
sprintf(s,"%d", r);
if (strlen(s) == 3)
sprintf(s, "0%d", r);
}
return 0;
}