views:

68

answers:

4
Given: 
 an  int variable  k , 
 an  int array  currentMembers that has been declared and initialized, 
 an  int variable  memberID that has been initialized, and 
 an  boolean variable  isAMember ,

write code that assigns  true to  isAMember if the value of  memberID 
    can be found in  currentMembers , and that assigns  false to `isAMember` otherwise.
    Use only  k ,  currentMembers ,  memberID , and  isAMember .

Here's what I came up with:

for (k=0;k<currentMembers.length;k++){
    if (currentMembers[k]==memberID)
        isAMember=true;
    else
        isAMember=false;
    }

What am I doing wrong?

+3  A: 

You are only taking the result of the test against the last value in your array. You need to break if you find a match.
Take a look at this tutorial on the break statement.

akf
Yes looks like you're right. How do I fix this?
fprime
+2  A: 

You need to stop searching once you confirm that memberID is in currentMembers[k].

isAMember = false;

for (k=0;k<currentMembers.length;k++){
    if (currentMembers[k]==memberID) {
        isAMember=true;
        break;
    }
}

In your original code, isAMember will only be true if the last element in currentMembers happens to == memberID.

Charles Salvia
note this is homework.
akf
@akf, I think the OP has sufficiently demonstrated that he's tried to solve the problem
Charles Salvia
A: 
isAMember = false;
for (k=0;k<currentMembers.length;k++){
    if (currentMembers[k]==memberID) {
        isAMember=true;
        break;
    }
}
hvgotcodes
A: 
if (currentMembers[0]==memberID)
  isAMember=true;
else
  isAMember=false;

if (currentMembers[1]==memberID)
  isAMember=true;
else
  isAMember=false;

if (currentMembers[2]==memberID)
  isAMember=true;
else
  isAMember=false;

So, it doesn't really matter what currentMember[0] and currentMember[1] are, currentMembers[2] writes to isAMember anyway. Don't set it to false, if you didn't find it now. You may have found the member before.

Ishtar