Get startedGet started for free

Using variables 1

What is the sum of the first \(n\) positive integers?

We can use the formula \( n(n+1)/2 \) to quickly compute this quantity.

This exercise is part of the course

Data Science R Basics

View Course

Exercise instructions

  • Define n<-100
  • Then use R to compute the sum of 1 through 100 using the formula \( n(n+1)/2\). What is the sum?
  • Make sure you do not erase or change the sample code on DataCamp exercises.

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

# Here is how you compute the sum for the first 20 integers
20*(20+1)/2 

# However, we can define a variable to use the formula for other values of n
n <- 20
n*(n+1)/2

n <- 25
n*(n+1)/2

# Below, write code to calculate the sum of the first 100 integers
Edit and Run Code