Create a script file to find the sum of the first N integers
Create a script file to find the sum of the first N integers starting with 1. Prompt the user to enter the integer, N, they want to sum up to. Use a for loop to determine the Sum. Print the output to the command window with a statement that includes the value for N and the value of the Sum. Check your results using the following formula. Paste the Script file below and paste two sample outputs: for N = 3 and N = 30.
Solution
Here we take n as the input to our function sum_of_n where we take a variable answer in which we store the sum of the integers. We use loop which iterates from 1 to n and at each step adds the value to the answer variable.
Finally we display the result using disp function.
Here is the code :
function sumOfNumbers = sum_of_n(n)
%function will calculate the sum of n numbers
%For Example
%1+2+3+4+5+6+......+n
%A variable to store the value of the sum
answer = 0;
for i = 1:n
answer = answer+i;
end
X = [\'The Sum of integer till n=\',n,\' is \',answer];
disp(X)
Sample input : n=3
Output:The Sum of integer till n=3 is 6
