I need help understanding these two questions. I have managed to do all of my assignments in Matlab without using/understanding these type of problems but they are on my midterm review. I have the answers but can't seem to grasp how to arrive at them. I understand how to use while and for loops in the codes that I have written, but can't figure out the answers to these questions. Help with either one would be greatly appreciated!
Question #1
The output of the following code is? Answer is sum=18
n=0;
sum=0;
while n<10
sum=sum+n;
n= n+3;
end
fprintf('sum= %d \n', sum)
Question #2
What is the final value for y in the code below? Answer is -49
Also, how many times will the 'for' loop run? Answer is 7
Here is the code:
y=0;
for x= 1:2:13
y=y-x;
end
Any help will be greatly appreciated. My textbook is pretty useless and I cannot figure these out.
So the n=n+3 means that n is always (0+3) within the range given for n? Shouldn't this command come before the sum command for the sum to be properly calculated? Either way, I still don't see how the sum would ever equal 18??? It seems that the sum portion of the equation would always be 0 so the highest value would be the highest value of n, which can't be 18.
Wow I'm stupid. I have #1 figured out for the most part. I wasn't following the loop the way I should have been, but now it makes perfect sense. Thanks for the chart captain! That got my mind heading in the right direction.
I do have one concern. How can you assume that the first value of n is 3 when calculating the first sum if the n=n+3 is AFTER the sum equation.
Any advice on tackling #2? Does the 1:2:13 mean to go from 1-13 in intervals of 2? If so, I understand it perfectly.