Monday, May 24, 2010

Can anyone help me write this program in C?

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 an int variable duplicates .





Write some code that assigns 1 to duplicates if any two elements in the array have the same value, and that assigns 0 to duplicates otherwise.


Use only j , k , zipcodeList , nZips , and duplicates .

Can anyone help me write this program in C?
Here you go:








duplicates = 0;





for(int j = 0; j %26lt; nZips; j++)


{





for(int k = j + 1; k %26lt; nZips; k++)


{


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


{


duplicates = 1;


break;


}


}





if(duplicates == 1)


break;


}


}
Reply:you need to create a loop that will go from 0 to nZips-1(the reason is that stacks start with 0). For this loop use varable i.


Then make another loop inside it(nested loop) similar to the first one. For this second loop use variable j. Then use the following if statement:


if(zipcodeList[i] == zipcodeList[j]){duplicates = 1;}





That should do it.


No comments:

Post a Comment