C++ Online Compiler
Example: Sum of Natural Numbers using for loop in C++
C
C++
C#
Java
Python
PHP
main.cpp
STDIN
Run
// Sum of Natural Numbers using for loop #include <iostream> // Required for input/output operations int main() { // Step 1: Declare variables to store the input number and the sum int n; int sum = 0; // Initialize sum to 0 before accumulation // Step 2: Prompt the user to enter a positive integer std::cout << "Enter a positive integer: "; std::cin >> n; // Read the user's input into variable 'n' // Step 3: Use a for loop to iterate from 1 to n // The loop variable 'i' will take values 1, 2, 3, ..., n for (int i = 1; i <= n; ++i) { sum += i; // Add the current number 'i' to the 'sum' } // Step 4: Display the calculated sum std::cout << "The sum of natural numbers up to " << n << " is: " << sum << std::endl; return 0; // Indicate successful program execution }
Output
Clear
ADVERTISEMENTS