PDA

View Full Version : How do I terminate a FOR Loop?



JYoung
11-12-2001, 11:18 AM
In the below FOR Loop, I only want VALUE FOUND or VALUE NOT FOUND
printed once. Right now depending on what array[index] the value is in
(ie. if it's in the third index) it will print VALUE NOT FOUND twice, then
VALUE FOUND.

How do I modify to print either statement 1x? Partial Code follows...
-----------------------------------------------------------------------------------------------------

cin >> choice;
for (int count = 0; count < 5; count++)
{
if (numbers[count] == choice)
cout << "VALUE FOUND: " << choice << endl;
else
cout << "VALUE NOT FOUND:" << endl;
}
-----------------------------------------------------------------------------------------------------
Thanks for any assistance. I'm a beginner by the way. :)

-JY

C++Newbie
11-12-2001, 11:26 AM
That loop should stop once it gets to 4.
Hope that helps i'm new to this also. See ya.:)

WayTooHigh
11-12-2001, 12:34 PM
i'm not sure this is what you want. but try break;.
for (int count = 0; count < 5; count++)
{
if (numbers[count] == choice)
{
cout << "VALUE FOUND: " << choice << endl;
break;
}
else
{
cout << "VALUE NOT FOUND:" << endl;
break;
}
}

Jeremy G
11-12-2001, 03:28 PM
cin >> choice;
int fail = 1; initialize as a fail.
for (int count = 0; count < 5; count++)
{
if (numbers[count] == choice)
fail = 0; // found the choice
}
if(fail == 1);
cout << "sorry choice not found";
else // optional
cout << "Your choice:" << choice << endl;

Magos
11-13-2001, 07:21 AM
cin >> choice;
int fail = 1;
for (int count = 0; count < 5; count++)
{
if (numbers[count] == choice)
fail = 0;
}
if(fail == 1); <-- Sorry, no ; here :)
cout << "sorry choice not found";
else
cout << "Your choice:" << choice << endl;

Jeremy G
11-13-2001, 03:20 PM
a simple typo, not like hed never beable to figure out why it doesnt work when he compiles..

sean
11-13-2001, 05:44 PM
I think what you're looking for was what the guy way up there ^ mentioned. break;. You may want to use an if statement like this:

while (loop_needs_to_be_run == true)
{
// Yada, yada, yada
if (loop_needs_to_exit == true)
break;
}

novacain
11-14-2001, 03:37 AM
Or if you just want to skip to the next value

continue;