Search code examples
cwhile-looppi

Is there a simpler way to do this? How can I get rid of one of my while loops?


For my CS assignment we were asked to create a program to approximate pi using Viete's Formula. I have done that, however, I don't exactly like my code and was wondering if there was a way I could do it without using two while loops.

(My professor is asking us to use a while loop, so I want to keep at least one!)

#include <stdio.h>
#include <math.h>
#include <stdlib.h>

int main()
{
  double n, x, out, c, t, count, approx;
  printf("enter the number of iterations to approximate pi\n");
  scanf("%lf", &n);

  c = 1;
  out = 1;
  t = 0;
  count = 1;
  x = sqrt(2);

  while (count<=n)
  { 
      t=t+1;

      while (c<t)
      { 
          x=sqrt(2+x);
          c=c+1; 
      }

      out=out*(x/2);
      count=count+1; 
  }

  approx=2/out;
  printf("%lf is the approximation of pi\n", approx);
} 

I just feel like my code could somehow be simpler, but I'm not sure how to simplify it.


Solution

  • Consider how many times the inner loop runs in each iteration of the outer loop

    • on the first iteration, it does not run at all (c == t == 1)
    • on each subsequent iteration, it runs exactly once (as t has been incremented once since the last iteration of the outer loop).

    So you could replace this inner while with an if:

        if (count > 1) {
    

    once you do that, t and c are completely unnecessary and can be eliminated.

    If you change the initial value of x (before the loop), you could have the first iteration calculate it here, thus getting rid of the if too. That leaves a minimal loop:

    out = 1;
    count = 1;
    x = 0;
    while (count<=n) {
        x=sqrt(2+x);
        out=out*(x/2);
        count=count+1; 
    }