C++ Online Compiler
Example: Sum of First n Odd Numbers (Formula) in C++
C
C++
C#
Java
Python
PHP
main.cpp
STDIN
Run
// Sum of First n Odd Numbers (Formula) #include <iostream> #include <cmath> // Required for pow() function, though n*n is simpler using namespace std; int main() { // Step 1: Declare variables for number of terms and sum int n_terms; long long sum; // No need to initialize sum here, calculated directly // 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; } // Step 4: Calculate the sum using the formula sum = static_cast<long long>(n_terms) * n_terms; // Sum of first n odd numbers is n*n // Step 5: Display the result cout << "Sum of the first " << n_terms << " odd numbers is: " << sum << endl; return 0; }
Output
Clear
ADVERTISEMENTS