Well at least with (i*i) you wont get function overheads, and its less work to type.

Printable View

- 01-04-2008mike_g
Well at least with (i*i) you wont get function overheads, and its less work to type.

- 01-04-2008alyeska
Hi all,

Thank you for all the helpful pointers. I couldn't get the sign=-sign idea to work, I guess, I have no idea how. Can somebody be more specific on how to do that?

Here's the code and the output though.. I still got warnings but it compiled anyway..

Code:`#include <iostream>`

#include <cmath>

using namespace std;

int main()

{

double i = 0;

int sum = 0, n = 0;

int elements = 0;

cout << "Enter a value for n where n >= 1: ";

cin >> n;

for (i = 1; i < n; ++i)

{

elements = (pow(-1.0,i-1))*(i * i);

sum += elements;

cout << elements << " + ";

}

elements = (pow(-1.0,i-1))*(i * i);

sum += elements;

cout << elements << " = " << sum << endl;

}

Code:`Enter a value for n where n >= 1: 4`

1 + -4 + 9 + -16 = -10

Press any key to continue...

- 01-04-2008tabstop
- 01-04-2008iMalc
- 01-04-2008iMalc
- 01-04-2008alyeska
Here is what I came up with. There is definitely a better way to write this but I will go for it this time. Thank you everyone, especially tabstop and iMalc.

Code:`#include <iostream>`

#include <cmath>

using namespace std;

int main()

{

double i = 0;

int sum = 0, n = 0;

int elements = 0;

cout << "Enter a value for n where n >= 1: ";

cin >> n;

for (i = 1; i < n; ++i)

{

elements = (pow(-1.0,i-1))*(i * i);

sum += elements;

if (elements % 2 != 0)

cout << " + " << elements << " ";

else

cout << elements;

}

elements = (pow(-1.0,i-1))*(i * i);

sum += elements;

if (elements % 2 != 0)

cout << " + " << elements << " = " << sum << endl;

else

cout << elements << " = " << sum << endl;

}

Code:`Enter a value for n where n >= 1: 4`

+ 1 -4 + 9 -16 = -10

Press any key to continue...