- 1
sum in range
Hi, can I please get some help here? You need to create a function that takes two parameters and returns the sum of all numbers between the two parameters inclusive. The given code takes two numbers from input and passes them to a function called rangeSum().
5 Respuestas
+ 3
Use a for loop. The first number being the staring point and the next the condition (e.g. for(int x = starting point; x <= next number; x++)
Then add the numbers together: int sum += x;
+ 5
input <- readLines('stdin')
x <- as.integer(input[1])
y <- as.integer(input[2])
# function definition
result<-0
rangeSum <- function(x,y){
for(a in x:y){
result<-result+a
}
print(sum(result))
}
rangeSum (x, y)
+ 2
Thank you both!
0
Rok Mazej
Where is your attempts?
Already explanation is given, create a function with 2 parameters and use that parameters in for loop where 1st parameter is a start point and 2nd parameter is end point.
You can do like this:
total = 0
for (x in startPoint : endPoint) {
total = total + x
}
print(total)
Or you can use range function also which is inbuilt function.
0
You‘re welcome