Amit Singh Tomar - 5 months ago 38

C Question

This question has been asked here on SO before with below code

`find3missing(int* array)`

{

int newarray[100] = {0};

For i = 0 to 99

++newarray[array[i]] ;

For i = 0 to 99

If newarray[i] != 1

Cout << “the missing number is ” << i+1 << endl ;

}

But when I checked this code, it doesn't seem to work. Suppose I have an array of {1,2,6}. The output should be 3,4,5 but with the code above I get 1,4,5,6 instead. Below is my implementation of pseudo code with array size 6.

`main()`

{

int a[6]={1,2,6};

int tmp[6]={0},i;

for(i=0;i<6;i++)

{

++tmp[a[i]];

}

for(i=0;i<6;i++)

{

if(tmp[i]!=1)

{

printf("%d",i+1);

}

}

}

Is this the right code?

Answer

This `++newarray[array[i]]`

should be `++newarray[array[i] - 1]`

. This because you are interested in a sequence of 1-100 numbers, so no 0, but C arrays are 0 based. If you then look at the `cout`

: `the missing number is ” << i+1`

here you "unshift" the number by adding 1.

There is another problem: you should pass the number of elements of the `array`

, something like:

```
find3missing(int* array, int length) {
int newarray[100] = {0};
for (int i = 0; i < length; i++) {
++newarray[array[i] - 1] ;
}
```