-2

For the famous problem.

There are 100 people standing in a circle numbered from 1 to 100. The first person is having a sword and kills the the person standing next to him clockwise i.e 1 kills 2 and so on. Which is the last number to remain alive? Which is the last number standing?

In the following C code for this problem.

void main(){
    int i=0, j; //i has the sword, j gets killed.
    int a[N]={0}; //0=not killed
    while(1){
        if(i != N-1) j = i + 1;
        else j = 0;
        while(a[j])
            if((j + 1) == N) j = 0; //loop back to 0
            else j++; //skip over the killed people
        if(i==j){ //if i is the only one left, stop
            printf("\n\n\n%d is left!", i+1);
            return;
        }
        a[j] = 1; //kill j
        printf(" %d kills %d.", i+1, j+1);
        if(j != N-1) i = j + 1;
        else i=0;
        while(a[i])
            if((i + 1) == N) i = 0;
            else i++;
    }
}

Please tell me meaning of int a[N]={0};//0=not killed in line no. 6 Thanks.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261

3 Answers3

2

In your code,

 int a[N]={0};

is initializing all the members of the array a to 0.

As per the C11 standard, chapter ยง6.7.9, initalization, (emphasis mine)

If there are fewer initializers in a brace-enclosed list than there are elements or members of an aggregate, or fewer characters in a string literal used to initialize an array of known size than there are elements in the array, the remainder of the aggregate shall be initialized implicitly the same as objects that have static storage duration.

and, for intializer value of static storage type int, which is arithmetic type,

[...] if it has arithmetic type, it is initialized to (positive or unsigned) zero;

and a is an array of type int, so it will have all it's members initialized 0 as the values. a[0] will be explicitly initialized to 0 (supplied), and the rest will get the implicit initialization.

FWIW, the N has to be a compile-time constant value, like

#define N 50 //or any value

for this to work.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
1

It basically tells the compiler that this will be an array of size N and will all be zero-initialized. So when you try to show the output of this array you'll see N zeroes.

SenselessCoder
  • 1,139
  • 12
  • 27
0

It is somewhat similar to :

memset(a, 0, N * sizeof(int))
Naman
  • 27,789
  • 26
  • 218
  • 353