user5398801
user5398801

Reputation:

Converting for() loop to do{}while in C with nested loops

I am trying to write a program that will find all acute triangle solutions after the user enters a min and max value (dmin and dmax). Right now I think I have the program working using only for() loops, but I need to change the first for() loop to a do{}while loop, which is confusing me. I'm not able to figure out how to write the do{}while loop so that is also includes these nested for() loops and the if statements. Everything I've tried either tells me b and c aren't being used or it just runs and provides no output. Here is my code with the for() loops.

double a = 0, b = 0, c = 0;
printf("Here are the acute triangle solutions the program found:\n");
  for (c = dmin; c <= dmax, c++)
  {
      for (b = dmin; b <= dmax; b++)
      {
          for (a = dmin; a <= dmax; a++)
          {
              if (a * a + b * b - c == c * c ){ //
                  if (((a + b) > c) && ((b + c) > a) && ((b + a) > b))
                  {printf("(%lf %lf %lf)\n", a, b, c);}  
                  //sum of two sides must be greater than the third
                  //and angle across from c must be <90 degrees
              }
          }
      }
  }

Upvotes: 1

Views: 608

Answers (2)

MiltoxBeyond
MiltoxBeyond

Reputation: 2731

In a do while, you simply do an initialization before and the check after. It is really somewhat similar to what the system does for a for loop.

The following code:

  for (c = dmin; c <= dmax, c++)
  {
      for (b = dmin; b <= dmax; b++)
      {
          for (a = dmin; a <= dmax; a++)
          {
              if (a * a + b * b - c == c * c ){ //
                  if (((a + b) > c) && ((b + c) > a) && ((c + a) > c))
                  {printf("(%lf %lf %lf)\n", a, b, c);}  
                  //sum of two sides must be greater than the third
                  //and angle across from c must be <90 degrees
              }
          }
      }
  }

Becomes:

  c = dmin;
  if(c < dmax) { //Make sure not to run once if c is greater
    do
    {
      for (b = dmin; b <= dmax; b++)
      {
          for (a = dmin; a <= dmax; a++)
          {
              if (a * a + b * b - c == c * c ){ //
                  if (((a + b) > c) && ((b + c) > a) && ((c + a) > b))
                  {printf("(%lf %lf %lf)\n", a, b, c);}  
                  //sum of two sides must be greater than the third
                  //and angle across from c must be <90 degrees
              }
          }
      }
    } while( ++c <= dmax );
  }

Upvotes: 1

Jean-Baptiste Yun&#232;s
Jean-Baptiste Yun&#232;s

Reputation: 36391

a for (e1;e2;e3) something loop can be transformed in:

e1;
while (e2) {
  something;
  e3;
}

or:

e1;
if (e2) {
  do {
    something;
    e3;
  } while (e2);
}

Upvotes: 2

Related Questions