Search code examples
c#algebra

Calculate the algebraic expression in C#


Calculate the algebraic expression Z, for which n is inputted by user. Use 2 for loops to solve the problem.

enter image description here

My code so far:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {

            int n, k = 1;
            double z;
            float sum, p;
            n = Console.Read();

            for (int i = 0; i < n; i+=2)
            {
                sum += p;

                for (int j = 0; j < n; j++)
                {
                    p *= (3 * k + 2);
                }

            }

        }
    }
}

I'm totally stack in the for loops... any help is appreciated.


Solution

    • p has to be initialized to 1 as 0 * X == 0
    • Also i and j (why not k) have to be initialized to 1 as it is required by your formula
    • You have to sum up the products after the products where calculated as you would add 1 to the correct result otherwise and you would not add the last calculated product

    So the code below should give the correct result:

            float sum = 0;
    
            int n = Console.Read();
    
            for (int i = 1; i <= n; i++)
            {
    
              float p = 1;
              for (int k = 1; k <= i+2; k++)
              {
                p *= (3 * k + 2);
              }              
    
              sum += p;
            }