- 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().

14th Feb 2022, 11:33 AM
Rok Mazej
5 odpowiedzi
+ 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;
14th Feb 2022, 12:22 PM
The_Fox
The_Fox - avatar
+ 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)
20th Jul 2022, 10:36 PM
Reza Zeraat Kar
Reza Zeraat Kar - avatar
+ 2
Thank you both!
14th Feb 2022, 4:34 PM
Rok Mazej
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.
14th Feb 2022, 2:19 PM
A͢J
A͢J - avatar
0
You‘re welcome
14th Feb 2022, 5:11 PM
The_Fox
The_Fox - avatar