Search This Blog

#Day52 #100DaysChallenge- Matlab Loops|Sum of Natural Numbers using for and while loop

#Day51-Sum of Natural Numbers using for and while loop

Task:

Write a code to find sum of Natural Number using both for and while loop


Note: This code can be done using the in-built command. But for the challenge, I am trying to avoid those.
Matlab code

function sumn=sumofnaturalnumbers(x)
sumn=0;
for i=1:1:x
    sumn=sumn+i;
end
end


function sumn2=sumofnnatrualnum(x)
sumn2=0;
while x>0
    sumn2=sumn2+x;
    x=x-1;
end
end

Sample Input and Output

>> sumofnaturalnumbers(6)

ans =

    21

>> sumofnnatrualnum(6)

ans =

    21

Click here for Video description




Live Support: t.me/matlabirawen






No comments

MATLAB