C++ Online Compiler
Example: Sum of First N Even Numbers (Formula-based) in C++
C
C++
C#
Java
Python
PHP
main.cpp
STDIN
Run
// Sum of First N Even Numbers (Formula-based) #include <iostream> using namespace std; int main() { // Step 1: Define the number of terms int N = 5; // Example: Sum of the first 5 even numbers // Step 2: Calculate the first and last terms int firstTerm = 2; int lastTerm = 2 * N; // Step 3: Apply the arithmetic series sum formula // Using long long for sum to handle potentially large results long long sum = (long long)N / 2 * (firstTerm + lastTerm); // Step 4: Print the final sum cout << "Calculating sum of first " << N << " even numbers using formula:" << endl; cout << "The sum is: " << sum << endl; return 0; }
Output
Clear
ADVERTISEMENTS