Create a function that calculates the result of the arithmetic series
$\sum_{k = 0}^n (a + kd)$
where $a$ and $d$ are real numbers and $n$ is a positive integer. You can find a formula that gives you this result at Wikipedia.
You should also be able to determine this sum by using the following rules:
$\sum_{k = 0}^n (a_k + b_k) =
\left( \sum_{k = 0}^n a_k \right) +
\left( \sum_{k = 0}^n b_k \right)$
$\sum_{k = 0}^n ab_k = a \sum_{k = 0}^n b_k$
$\sum_{k = 0}^n 1 = n + 1$
Compare your formula you found for calculating the arithmetic series with the formula $(n + 1)(nd/2 + a)$. Are these formulas the same?
Your function declaration will be:
double arithmetic_series( double initial_value, double difference, unsigned int n );
You should not use any loops in your code.
The following function explicitly calculates the series, as opposed to using a formula. When this formula gives a different answer from yours, which do you suspect is more correct?
double arithmetic_series_explicit( double initial_value, double difference, unsigned int n ); double arithmetic_series_explicit( double initial_value, double difference, unsigned int n ) { double sum{initial_value}; for ( unsigned int k{1}; k <= n; ++k ) { sum += initial_value + k*difference; } return sum; }
Here is a program you can run:
#include <iostream> double arithmetic_series_explicit( double initial_value, double difference, unsigned int n ); double arithmetic_series( double initial_value, double difference, unsigned int n ); int main(); double arithmetic_series_explicit( double initial_value, double difference, unsigned int n ) { double sum{initial_value}; for ( int k{1}; k <= n; ++k ) { sum += inial_value + k*difference; } return sum; } int main() { std::cout.precision( 16 ); double a, d; unsigned int n; while ( true ) { std::cout << "Enter the initial value 'a': "; std::cin >> a; std::cout << "Enter the difference 'd': "; std::cin >> d; std::cout << "Enter the upper limit 'n': "; std::cin >> n; std::cout << arithmetic_series( a, d, n ) << std::endl; std::cout << arithmetic_series_explicit( a, d, n ) << std::endl; } return 0; }