w3resource

Sum of Cubes calculation with For loop in R

R Programming: Control Structure Exercise-9 with Solution

Write a R program function to compute the sum of cubes of numbers from 1 to n using a for loop.

Sample Solution :

R Programming Code :

# Define a function to compute the sum of cubes of numbers from 1 to n using a for loop
sum_of_cubes <- function(n) {
    # Initialize a variable to store the sum
    sum <- 0
    
    # Iterate through numbers from 1 to n
    for (i in 1:n) {
        # Calculate the cube of the current number
        cube <- i^3
        
        # Add the cube to the sum
        sum <- sum + cube
    }
    
    # Return the total sum of cubes
    return(sum)
}

# Test the function with an example input
n <- 5  # Example value of n
result <- sum_of_cubes(n)

# Print the result
cat("The sum of cubes of numbers from 1 to", n, "is:", result, "\n")

Output:

The sum of cubes of numbers from 1 to 5 is: 225               

Explatnaion:

In the exercise above,

  • The "sum_of_cubes()" function calculates the sum of cubes of numbers from 1 to 'n'.
  • It initializes a variable 'sum' to store the sum and sets it to 0.
  • Using a for loop, it iterates through numbers from 1 to 'n'.
  • Within each iteration, it calculates the cube of the current number (i) and adds it to the 'sum'.
  • After iterating through all numbers from 1 to 'n', it returns the total sum of cubes.

R Programming Code Editor:



Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Factorial calculation with Recursion in R.
Next: Check Armstrong number with While loop in R.

Test your Programming skills with w3resource's quiz.

What is the difficulty level of this exercise?



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/r-programming-exercises/control-structure/r-programming-control-structure-exercise-9.php