Can someone help me with this problem
I've been trying to do an else statement but it doesn't work
here is the code....

for(int c=0;c<student_max;c++){

if(search_id==id[c]){
location=binary_search(id,student_max,search_id);
cout<<"Student ID \tTotal \tGrade"<<endl;
cout<<"-----------------------------"<<endl;
cout<<search_id<<" \t\t"<<total[location]<<" \t"<<determine_grade(total[location])<<endl;
//break;
}


//}

else{
cout<<"Incorrect id entered"<<endl;
break;
}
}
}

What I can see looks correct. What is the error you're getting?

Also, please use code tags, it makes it easier to read.

Edited 3 Years Ago by happygeek: fixed formatting

for(int c=0;c<student_max;c++)
    {
    if(search_id==id[c])
        {
        location=binary_search(id,student_max,search_id);
        cout<<"Student ID \tTotal \tGrade"<<endl;
        cout<<"-----------------------------"<<endl;
        cout<<search_id<<" \t\t"<<total[location]<<" \t"<<determine_grade(total[location])<<endl;
        }
    else
        {
        cout<<"Incorrect id entered"<<endl;
        }    
    }

As far as I'm able to see, the code is fine?

The blocking and logic structure of the snippet you are showing are correct.

Unfortunately, you aren't being very clear on what exactly isn't working.

Does it simply execute the first/true section every time? Is it ignoring the else section when the test is false?

Please provide more information. Based on what I see, it is likely that there is an issue outside your loop that is causing an error inside it.

Edited 7 Years Ago by Fbody: n/a

Just guessing here, but rethink your break statements. Maybe you want to reorganize to find the matching ID, then break out of the loop and finish the location lookup.

bool found = false;
for ( int c = 0; c < student_max ; ++c )
{
    if ( search_id == id[c] )
    {
        found = true;
        break;
    }
}
if ( found )
{
    location = // etc
}
else
{
    cout << "invalid id;
}

Another possibility: what is binary_search() doing? Isn't it going to return the same index you already discovered in c? Do you even need the for loop? Could you just validate that search_id is in range and then use binary_search to find the location?

if ( search_id >= 0 && search_id < student_max )
{
    location = binary_search(id, student_max, search_id);
    cout << ....
}
else
{
    cout << "invalid";
}

Or is that supposed to be std::binary_search? If it is, you're using it wrong; check your documentation.

Like other people have noted, you'll need to be clearer on what you think is wrong, and possibly include some more of the program leading up to this loop.

This article has been dead for over six months. Start a new discussion instead.