title: Summing infinite series 1/n
body: <p>I just started taking my first steps in learning coding and general (starting with c#)and I'm learning from a book currently. The book leaves questions at the end of every chapter. I'm currently unsure on how to proceed with this specific question. The question is as follows:</p>
  
  <p><strong>Question: Write a program that calculates the sum (with precision of 0.001) of the following sequence: 1 + 1/2 - 1/3 + 1/4 - 1/5 + … 1/n</strong></p>
  
  <p>The book has given the following guidelines for this problem:</p>
  
  <p><strong>Guide Lines: Accumulate the sum of the sequence in a variable inside a while-loop (see the chapter "Loops"). At each step compare the old sum with the new sum. If the difference between the two sums Math.Abs(current_sum – old_sum) is less than the required precision (0.001), the calculation should finish because the difference is constantly decreasing and the precision is constantly increasing at each step of the loop. The expected result is 1.307</strong></p>
  
  <p>I have an idea on how to implement this but I do not know how or where to initiate and break the loop when the sum has reached the required precision. I currently use user input to enter n. I would like to know how to automate this process. </p>
  
  <p>Here is my code so far. I know its a cop out to use the format {N:2} but i am not sure how to proceed. Would very much appreciate the help! Thanks!</p>
  
  <pre><code>using System;
  using System.Collections.Generic;
  using System.Linq;
  using System.Threading.Tasks;
  
  namespace Demo
  {
      class Program
  {
      static void Main()
      {
  
          Console.Write("Please enter n: ");
          double counter = double.Parse(Console.ReadLine());
          double sum = 1 + AddSum(counter); // calculate infinite sum 
          Console.WriteLine("Sum = {0:N3}", sum);
  
  
  
      }
  
  
      static double AddSum(double n)
      {
          double a = 0;
  
          for (double i = 1; i &lt; n; i++)
          {
              if(i % 2 == 0)
              {
                  a -= 1 / (i +1); // calculates negative fractions
              }
  
              else
              {
                  a += 1 / (i +1); // calculates positive fractions
              }
          }
  
          return a;
      }
  
  }
  </code></pre>