Write a function file that gets a positive integer as input

Write a function file that gets a positive integer as input. Add up all the numbers from 1 to that number using a for loop. Return the calculated sum as the output from the function.

Solution

function sum_ = _sum_(n)
sum_ = 0;
for i = 1:n
sum_ = sum_+i;
end
end

Save above code in _sum_.m

Above code gets a input as a parameter and returns the total sum calculated.

Now, for executing use below

_sum_(9)

this will return

ans = 45

Write a function file that gets a positive integer as input. Add up all the numbers from 1 to that number using a for loop. Return the calculated sum as the out

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site