-7
using namespace std;
#include <iostream>
#include <conio.h>
#include <cmath>

int main()

{

    int sum = 0;
    for (int i = 1; i < 11; i++)
        cout << 2 * pow(i, 2) + 5 * (i) - 3 << "\n";


    return 0;


}

Code outputs 4 15 30 49 72 99 130 165 204 247 but I need also calculate the sum of this numbers. How can I do this

Fred Larson
  • 60,987
  • 18
  • 112
  • 174
arcend
  • 1
  • 2
  • 2
    Replace `pow(i,2)` with `(i * i)`. Multiplication is faster than calling the `pow` function. Also, the `pow` function is floating point and you may get wrong results to conversion between integers and floating point (and vice-versa). – Thomas Matthews Sep 29 '21 at 21:37
  • 1
    Don't use `pow` to do a simple integer calculation. Just multiply. As a matter of fact, your program is susceptible to errors, depending on the version and make of compiler. [See this](https://stackoverflow.com/questions/25678481/why-does-pown-2-return-24-when-n-5-with-my-compiler-and-os) – PaulMcKenzie Sep 29 '21 at 21:37
  • For calculating the sum, you should be able to just do `sum += i`. You don't need to use pow() at all. – jkb Sep 29 '21 at 21:43
  • Sorry, I just saw that you said "these" numbers rather than "the numbers". You should probably ignore my previous comment. – jkb Sep 29 '21 at 22:02

1 Answers1

3

Here's another shot at the loop:

int sum = 0;
for (int i = 0; i < 11; ++i)
{
    const int temp = 2 * (i * i) + 5 * (i) - 3;
    cout << temp << "\n";
    sum += temp;
}
cout << "Sum: " << sum << "\n";

This version calculates (evaluates) the polynomial once, assigning the result to a temporary variable. The temporary variable is then printed and also added to the sum.

Thomas Matthews
  • 56,849
  • 17
  • 98
  • 154