#include // From secondary school, you are aware that // // n(n + 1) // 0 + 1 + 2 + ... + (n - 1) + n = ---------- // 2 // // You may have also seen the formulas: // // 2 2 2 2 2 // 0 + 1 + 2 + ... + (n - 1) + n // // n(n + 1)(2n + 1) // = ------------------ // 6 // // and // // 3 3 3 3 // 1 + 2 + ... + (n - 1) + n // // 2 2 // n (n + 1) // = ------------ // 4 // // For example, // // 0 + 1 + 8 + 27 + 64 + 125 + 216 // + 343 + 512 + 729 + 1000 = 3025 // // and // // 2 2 // 10 11 12100 // -------- = ------- = 3025. // 4 4 // // If you are not yet familiar with sigma notation, // such sums are represented as // // n // ------- 2 2 // \ 3 n (n + 1) // ) k = ------------ // / 4 // ------- // k = 1 // // Now consider the sum // // 0*1 + 1*2 + 2*3 + 3*4 + 4*5. // // More generally, the formula in sigma notation is // // n // ------- // \ n(n + 1)(n + 2) // ) k(k + 1) = ----------------- // / 3 // ------- // k = 1 // // Verify this formula as follows: // // 1. Ask the user for an integer 'N'. // 2. For each n = 0, ..., N: // a. explicitly calculate the sum, // b. calculate the value given by the formula, // c. print 'n', a tab, the sum, a tab, and // the value given by the formula. // // If N < 0, return 0. // // ////////////////////////////////////////////////// // Interesting exercise: // // Can you find a pattern in these formulas? If so, // can you predict the next formula and modify your // code to test your prediction? // // n // ------- // \ n // ) 1 = --- // / 1 // ------- // k = 1 // // n // ------- // \ n(n + 1) // ) k = ---------- // / 2 // ------- // k = 1 // // n // ------- // \ n(n + 1)(n + 2) // ) k(k + 1) = ----------------- // / 3 // ------- // k = 1 // // What do you think should come next? // ////////////////////////////////////////////////// // Function declarations int main(); // Function definitions int main() { return 0; } // Hint: // // You will need two loops: // // 1. The outer loop has 'n' go from 0 to 'N'. // 2. The inner loop explicitly calculates the // sum for k from 1 to 'n'. // // What happens to the inner loop when n == 0? // Your outer loop should look like: // // for ( int n{ 0 }; n <= N; ++n ) { // // Calculate the sum. // // Calculate the formula. // // Print the results. // } // Here is one solution: /* int main() { int N{}; std::cout << "Enter a non-negative integer: "; std::cin >> N; if ( N < 0 ) { return 0; } for ( int n{ 0 }; n <= N; ++n ) { int sum{ 0 }; for ( int k{ 1 }; k <= n; ++k ) { sum += k*(k + 1); } int formula{ (n*(n + 1)*(n + 2))/3 }; std::cout << n << "\t" << sum << "\t" << formula << std::endl; } return 0; } */