TutorialStudyMite

Program to display the cube of the number upto given integer in C++

Beginner friendly

Try it first

Sum of Squares Up to N

Give it a try before seeing the solution in this article.

Give it a try

Track completion, mastery, and revision.

Displaying Cubes Up to a Given Integer in C++

This article demonstrates how to write a C++ program that calculates and displays the cube of each number from 1 up to a user-specified integer. The program will prompt the user for a positive integer n, and then iterate from 1 to n, printing each number and its corresponding cube.

Example

If the user inputs 4 as the number of terms, the program will produce the following output:

Input the number of terms: 4
Number is: 1 and its cube is: 1
Number is: 2 and its cube is: 8
Number is: 3 and its cube is: 27
Number is: 4 and its cube is: 64

Algorithm

The core logic for this program is straightforward:

  1. Get Input: Prompt the user to enter the desired number of terms (let's call it n).
  2. Iterate: Use a loop that starts from i = 1 and continues as long as i is less than or equal to n.
  3. Calculate Cube: Inside the loop, for each value of i, calculate its cube by multiplying i by itself three times (i * i * i).
  4. Display Result: Print the current number (i) and its calculated cube.

C++ Implementation

Here's the C++ code that implements the algorithm described above:

#include <iostream> // Required for input/output operations
using namespace std; // Allows direct use of cout, cin, endl without std:: prefix

int main() {
  int i, n, cube; // Declare variables: i for loop counter, n for user input, cube for storing the result

  // Prompt the user for input
  cout << "Input the number of terms: ";
  cin >> n; // Read the user's integer into 'n'

  // Loop from 1 up to 'n' (inclusive)
  for (i = 1; i <= n; i++) {
    cube = i * i * i; // Calculate the cube of the current number 'i'
    cout << "Number is: " << i << " and its cube is: " << cube << endl; // Display the number and its cube
  }

  return 0; // Indicate successful program execution
}

Callout: This program uses a simple for loop to iterate through numbers from 1 up to the n provided by the user. Inside the loop, the cube is calculated by multiplying the number by itself three times.

Example Output

When the program is executed and 5 is entered as the number of terms, the output will be:

Input the number of terms: 5
Number is: 1 and its cube is: 1
Number is: 2 and its cube is: 8
Number is: 3 and its cube is: 27
Number is: 4 and its cube is: 64
Number is: 5 and its cube is: 125

Finished reading?

Was this helpful?

Your feedback shapes better tutorials for everyone.