I have written a program to print out all the numbers, whose binary pattern is symmetrical(for example:1001001 , 1010101) between 1 to 1993. I had made a mistake and I found it out. However, there is some detail I can not understand yet.
The correct code:
#include <stdio.h>
main() {
int binary[11] = {0};
int i, n, j, k;
for(i = 1; i <= 1993; i++) {
n = i; k = 0;
while(n != 0) {
binary[k++] = n%2 ;
n = n/2;
}
for(j = 0; j < k; j++) {
if(binary[j] != binary[k-j-1])
break;
}
if(j == k) {
printf("%d ", i);
for(j = 0; j < k; j++)
printf("%d", binary[j]);
printf("\n");
}
}
}
The wrong code:
#include <stdio.h>
main() {
int binary[11] = {0};
int i, n, j, k = 0; /* I have found a mistake here, k=0 should inside the for loop */
for(i = 1; i <= 1993; i++) {
n = i;
while(n != 0) {
binary[k++] = n%2 ;
n = n/2;
}
for(j = 0; j < k; j++) {
if(binary[j] != binary[k-j-1])
break;
}
if(j == k) {
printf("%d ", i);
for(j = 0; j < k; j++)
printf("%d", binary[j]);
printf("\n");
}
}
}
I just can’t understand why the variable “i” can not increase to 6 when “k=0” outside the for loop, and the loop will repeat again and again.
In the “wrong code”, the k variable will not reset to 0 between iterations. It will however increase with every iteration of the while loop. At some point it will break the upper bound of the binary[11] array, and then the “binary[k++] = n%2 ;” statement will start to overwrite other variables on the stack, including the variable “i”. In this situation, unpredictable things will happen.
If you step through the “wrong code” I beleive you are able to verify that this happens when i=6.