C++ Online Compiler
Example: Cube Series up to N in C++
C
C++
C#
Java
Python
PHP
main.cpp
STDIN
Run
// Cube Series up to N #include <iostream> // Required for input/output operations int main() { int n; // Declare an integer variable 'n' to store the limit // Step 1: Prompt the user to enter a positive integer std::cout << "Enter a positive integer (n): "; std::cin >> n; // Read the user's input into 'n' // Step 2: Validate the input to ensure 'n' is positive if (n <= 0) { std::cout << "Please enter a positive integer." << std::endl; return 1; // Exit with an error code } // Step 3: Print a descriptive message std::cout << "The cube series up to " << n << " is: "; // Step 4: Use a for loop to iterate from 1 to 'n' for (int i = 1; i <= n; ++i) { // Calculate the cube of the current number 'i' long long cube = static_cast<long long>(i) * i * i; // Print the calculated cube, followed by a space std::cout << cube << " "; } std::cout << std::endl; // Print a newline character at the end for formatting return 0; // Indicate successful execution }
Output
Clear
ADVERTISEMENTS