Skip to main content

Codewars — Sum of the first nth term of Series

Your task is to write a function which returns the sum of following series upto nth term(parameter).
Series: 1 + 1/4 + 1/7 + 1/10 + 1/13 + 1/16 +...

Rules:

  • You need to round the answer to 2 decimal places and return it as String.
  • If the given value is 0 then it should return 0.00
  • You will only be given Natural Numbers as arguments.

Examples:

SeriesSum(1) => 1 = "1.00"
SeriesSum(2) => 1 + 1/4 = "1.25"
SeriesSum(5) => 1 + 1/4 + 1/7 + 1/10 + 1/13 = "1.57"
 
 My Solution
 
 
#include <iostream>
#include <iomanip> 

using namespace std;


class ta
{

   
   float ar[50];
   int j,f,k,q;
   float sum=0.00;
public:
   void taa(int k)
   {
      f = k;
   }
   
   
  void paa()

  { 
         
         for(j=0; j<f; j++)
         {

            ar[j] = 1.00/(1 + j * 3);
         }


   }
   void baa()
   {
      for(q=0; q<f; q++)
      {
         sum = sum+ar[q];
      }
      cout <<setprecision(3)<< sum;

   }
      
   

};
int main()
{
   ta a;
   a.taa(5);
   a.paa();
   a.baa();
   
}