C++ Online Compiler
Example: Sum of First n Odd Numbers (For Loop) in C++
C
C++
C#
Java
Python
PHP
main.cpp
STDIN
Run
// Sum of First n Odd Numbers (For Loop) #include <iostream> using namespace std; int main() { // Step 1: Declare variables for number of terms and sum int n_terms; long long sum = 0; // Use long long for sum to avoid overflow with large 'n' // Step 2: Prompt user for input cout << "Enter the number of odd terms to sum: "; cin >> n_terms; // Step 3: Input validation if (n_terms <= 0) { cout << "Number of terms must be positive." << endl; return 1; // Indicate an error } // Step 4: Iterate and sum the odd numbers cout << "Series: "; for (int i = 1; i <= n_terms; ++i) { int current_odd = 2 * i - 1; // Formula to get the i-th odd number sum += current_odd; cout << current_odd; if (i < n_terms) { cout << " + "; } } cout << endl; // Step 5: Display the result cout << "Sum of the first " << n_terms << " odd numbers is: " << sum << endl; return 0; }
Output
Clear
ADVERTISEMENTS