C++ Online Compiler
Example: Sum of First N Even Numbers (Loop-based) in C++
C
C++
C#
Java
Python
PHP
main.cpp
STDIN
Run
// Sum of First N Even Numbers (Loop-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 (2+4+6+8+10) // Step 2: Initialize a variable to store the sum int sum = 0; // Step 3: Use a loop to iterate and add each even number cout << "Calculating sum of first " << N << " even numbers:" << endl; for (int i = 1; i <= N; ++i) { int evenNumber = 2 * i; // Calculate the current even number (2, 4, 6, ...) sum += evenNumber; // Add it to the total sum } // Step 4: Print the final sum cout << "The sum is: " << sum << endl; return 0; }
Output
Clear
ADVERTISEMENTS