Reputation: 541
From Schaums C++ text
Removal of goto- says use a flag
code segment:
const int N2 = 5;
int i, j, k;
for (i = 0; i < N2; i++)
{ for (j = 0; j < N2; j++)
{ for (k = 0; k < N2; k++)
if (i + j + k > N2)
goto esc;
else
cout << i + j + k << " ";
cout << "* ";
}
esc: cout << "." << endl;
}
The solution:
const int 5;
int i, j, k;
bool done = false;
for (i = 0; i < N2; i++)
{ for (j = 0; j < N2 && !done; j++)
{ for (k = 0; k < N2 && !done; k++)
if (i + j + k > N2)
done true;
else
cout << i + j + k << " ";
cout << "* ";
}
cout << "." << endl;
done = false;
}
The output of the structured solution does not produce the same result...as the goto one... I can't see the problem
Thanks ...
Upvotes: 1
Views: 209
Reputation: 13521
A great way to code this kind of loop escape functionality is a return; statement. Take:
const int N2 = 5;
void inner_loop(const int i) {
for (int j = 0; j < N2; ++j)
{
for (int k = 0; k < N2; ++k)
{
if (i + j + k > N2)
return;
cout << i + j + k << " ";
}
cout << "* ";
}
}
for (int i = 0; i < N2; ++i)
{
inner_loop(i);
cout << "." << endl;
}
Upvotes: 6
Reputation: 67809
First of all, your formatting is extremely difficult to read. This helps a lot:
const int N2 = 5;
int i, j, k;
for (i = 0; i < N2; i++)
{
for (j = 0; j < N2; j++)
{
for (k = 0; k < N2; k++)
{
if (i + j + k > N2)
goto esc;
else
cout << i + j + k << " ";
}
cout << "* ";
}
esc: cout << "." << endl;
}
Now I don't know who this Schaum guy is, but he's wrong. goto is a prefectly legitimate statement to use in this case. It's about the only reason you should ever need one, though. Eliminating the goto gains you nothing. Now you have an extra variable, and each loop needs an additional branch and test.
I suggest you avoid his advice on this issue.
Upvotes: 1
Reputation: 120684
const int 5;
int i, j, k;
bool done = false;
for (i = 0; i < N2; i++)
{ for (j = 0; j < N2 && !done; j++)
{ for (k = 0; k < N2 && !done; k++)
if (i + j + k > N2)
done = true;
else
cout << i + j + k << " ";
if (!done) // <-- Add this line
cout << "* ";
}
cout << "." << endl;
done = false;
}
Upvotes: 3