-1

Sigma Equation

I am currently attempting to write a program in which a user enters a number (Z) to be used to calculate the summation. I've been attempting to use nested for loops, to no avail.

This is a homework assignment, so rather an idea in the right direction than a full answer if possible.

Edit: In the example a Z of 10 is used to equate to 20790, which has been my method of checking if my code works

for(int x = 0; x<=z; x++)
{
    for(int y =0; y<=x+1; y++)
    {
        sum = (z/2)*((x^2)+y+1);
        total += sum;
    }
}

This was my last attempt, albeit a poor one.

Eendjie
  • 21
  • 1
  • 4

1 Answers1

4

First of all: did you initialize your total to 0?
Furthermore, the operator ^ does not raise to a power. It's a bitwise XOR. Simply use x*x.

Robert Kock
  • 5,795
  • 1
  • 12
  • 20
  • 1
    Thank you, we just moved over from python, so after seeing x**2 no longer worked I looked up the command, must've misread it. – Eendjie Jul 31 '18 at 17:06
  • 1
    Just for interests sake, what would happen if total was not initialised to zero, just created with "int total;" at the start? – Eendjie Jul 31 '18 at 17:09
  • `total` would have an arbitrary value. It would mess up the final result. – Robert Kock Jul 31 '18 at 17:11
  • 1
    I understand, thank you very much for taking the time to help with such a stupid mistake. – Eendjie Jul 31 '18 at 17:12
  • 1
    @Eendjie A slight correction: What happens if you do not initialize `total` depends on how and where you define `total`. If it is defined inside a function and not declared `static` (An Automatic or local variable) then what Robert says is correct. Its value will be undefined and likely whatever old value happened to be in the memory now used by `total`. As a static variable `total` would be zeroed for you. [Look up Storage Duration](https://en.cppreference.com/w/cpp/language/storage_duration) for more info. – user4581301 Jul 31 '18 at 18:32