Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I exit a loop in C++ without using break?

Tags:

c++

loops

break

I'm writing a code to swap integers in an array and I want to know how I can exit a loop without using a break statement and keeping my logic consistent. Here is my code below:

int swapped = 0;
if (arrays[0][first] % 2 == 0)
{
     cout << arrays[0][first] << " is odd " << endl;
     for (int i = 1; i < arraycount; ++i)
     {
         for (int j = 1; j < arrays[i][0] + 1; ++j)
         {
             if (arrays[i][j] % 2 != 0)
             {
                  int temp = arrays[i][j];
                  cout << "Array #" << 1 << " value " << arrays[0][first] << " swapped with "
                          << "Array #" << i << " value " << temp;

                  arrays[i][j] = arrays[0][first];
                  arrays[0][first] = temp;
                  swapped = 1;
                  break;
              }
          }
          if (swapped) {
                break;
          }
like image 823
John Smith Avatar asked Oct 03 '15 06:10

John Smith


1 Answers

Use goto [I'll be bashed because of this].

if (arrays[0][first] % 2 == 0)
{
     cout << arrays[0][first] << " is odd " << endl;
     for (int i = 1; i < arraycount; ++i)
     {
         for (int j = 1; j < arrays[i][0] + 1; ++j)
         {
             if (arrays[i][j] % 2 != 0)
             {
                  int temp = arrays[i][j];
                  cout << "Array #" << 1 << " value " 
                          << arrays[0][first] << " swapped with "
                          << "Array #" << i << " value " << temp;

                  arrays[i][j] = arrays[0][first];
                  arrays[0][first] = temp;
                  goto done;
              }
          }
done:
    something;
like image 122
Cem Kalyoncu Avatar answered Oct 06 '22 10:10

Cem Kalyoncu