iwanttoprogram
iwanttoprogram

Reputation: 541

Structured solution without using a jump statement

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

  1. Also, what would be another way to eliminate the goto?- Could I not use a flag and just compliment the condition.

Thanks ...

Upvotes: 1

Views: 209

Answers (5)

Todd Gardner
Todd Gardner

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

rlbond
rlbond

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

klew
klew

Reputation: 14967

You need to add condition:

if (!done) cout << "* ";

Upvotes: 0

Vladimir Obrizan
Vladimir Obrizan

Reputation: 2593

Throw an exception.

Upvotes: -3

Sean Bright
Sean Bright

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

Related Questions