### LANGUAGE: C++

### CHALLENGE:

You are given two int variables j and k, an int array zipcodeList that has been declared and initialized, an int variable nZips that contains the number of elements in zipcodeList, and a bool variable duplicates. Write some code that assigns true to duplicates if any two elements in the array have the same value, and that assigns false to duplicates otherwise. Use only j, k, zipcodeList, nZips, and duplicates.

### SOLUTION:

duplicates = false; for (k =0; k < nZips; k++){ for(j=k+1 ;j<nZips;j++){ if (zipcodeList[k] == zipcodeList[j]){ duplicates = true; break; } } }

Won’t this code always result in duplicates = true? Since the first element that’s being compared is

zipcodeList[0] == zipcodeList[0]

codelabs accepts the answer, but I’m not understanding it. Thanks for all your help posting these answers btw!

Yes, duplicates is set to false at the beginning of each iteration. In the event a duplicate is found duplicates is set to true. So true will only returned if a duplicate exists. Hope this helps, Happy Coding.

duplicates is set to false only once and not at each iteration.

You cant use j =0… you have to use j = k+1, otherwise j =1 and k =1 will match up and be equal when really its comparing the exact same line to itself.

This is what I used that finally worked.

duplicates = false;

for (k =0; k < nZips; k++)

{

for(j=k+1 ;j<nZips;j++)

{

if (zipcodeList[k] == zipcodeList[j])

{

duplicates = true;

break;

}

}

}

Correct Answer:

duplicates = false;

for(k = 0; k < zipcodeList.length; k++) {

for(j = k+1; j < zipcodeList.length; j++) {

if(zipcodeList[j] == zipcodeList[k]) {

duplicates = true;

break;

}

}

}

Correct Answer for Java:

duplicates = false;

for(k = 0; k < zipcodeList.length; k++) {

for(j = k+1; j < zipcodeList.length; j++) {

if(zipcodeList[j] == zipcodeList[k]) {

duplicates = true;

break;

}

}

}

duplicates=false;

for (k = 0; k < zipcodeList.length; k++)

for (j = 0; j < k; j++)

{

if ( zipcodeList[j] == zipcodeList[k])

{

duplicates=true;

break;

}

}