Search code examples
arrayscglobal-variablesequalityfunction-definition

finding out if all the digits of a number are equal


So I want to start by saying that I already solved the problem, but there is something that is bugging me,

Here is the code first:

#include <stdio.h>

int flag = 1;

int controlNumber(int);

int main() {    
    int array[10] = { 233, 45, 777, 81, 999999, 36, 90, 88, 11, 61 };   
    int i;  
    int c;  

    for (i = 0; i < 10; i++) {
        printf("%d >>  ", array[i]);
        c = controlNumber(array[i]);
        if (c == 1) {           
            printf("all digits are equal\n");
        } else {
            printf("not all digits are equal\n");
        }
    }
    return 0;
}

int controlNumber(int a) {
    int q = a;
    int r = a % 10;
    int temp;
    
    while (q != 0) {
        temp = q % 10;
        if (temp == r) {
            q = q / 10;
        } else {
            flag = 0;
            return flag;
        }
    }
    return flag;
}

The code works only if the global variable flag is made local inside the scope of the function controlNumber with a value of 1, and I can't really figure out why that is the case since the logic should still be the same.

Also, I'm still a beginner to some extend so I apologize for any indentation errors.


Solution

  • Global variables retain their value. In your case, if flag is global, once set to 0 (within controlNumber) it will keep that value. There is no other place in the code to make it 1 again.

    Making it a local variable to the function will cause it to initialize to 1 every time the function is called.

    Edit: if you want to have it as global, you could set it to 1 every time controlNumber returns 0, i.e., before or after printf("not all digits are equal\n");.