title: How to break out of a while loop with a boolean?
body: <p>I am trying to break out of several nested while loops and I am having trouble. I want this program to break out into the outer loop, which will run only a certain amount of times. I tried doing it with a boolean but my program terminates too early. It is an N-Queens problem where I am solving for 1x1, 2x2, 3x3,...nxn queens.</p>
  
  <p>Here is my code:</p>
  
  <pre><code>bool ok(int *q, int col)
  {
     for(int i=0; i&lt;col; i++)
        if(q[col]==q[i] || (col-i)==abs(q[col]-q[i])) return false;
  
  return true;
  };
  
  void print(int q[], int n, int cnt)
  {
      //static int count =0;
      cout&lt;&lt;"There are "&lt;&lt;cnt&lt;&lt;" solutions for "&lt;&lt;n&lt;&lt;" queens." &lt;&lt;endl;   
  };
  
  int main()
  {
      int n;
      int *q;
      cout&lt;&lt;"Please enter the size of the board:"&lt;&lt;endl;
      cin&gt;&gt;n;
  
      int static count = 0;
  
      int c = 1;
      int a = 1;
      bool from_backtrack=false;
  
      while(a!=n){
  
          q= new int[a];
          q[0]=0;
          bool foundSolution=true;
          while(foundSolution)
          {
              if (c==a){
                  a++;
              }
              while(c&lt;a)
              {
                  if(!from_backtrack)
                      q[c] = -1; //Start at the top
                  from_backtrack=false;
                  while(q[c]&lt;a)
                  {
                      q[c]++;
                      if  (q[c]==a)
                      {
                          c--;
                          if(c==-1) {
                              print(q, n, count);
                              foundSolution=false;
                              //system("PAUSE"); exit(1);
                          }
                          continue;
                      }
                      if( ok(q,c) ) break; //get out of the closest while loop
                  }
                  c++;
              }
              count++;
              c--;
              if(c==-1) {
                  print(q, n, count);
                  foundSolution=false;
                  //system("PAUSE"); exit(1);
              }
              from_backtrack=true;
          }
          delete[a] q;
          a++;
      }
      system("PAUSE");
  }
  </code></pre>