- #1
gfd43tg
Gold Member
- 950
- 50
Hello,
I am trying to decipher loop codes and I am having a lot of difficulty doing so
Here is an example code
So I thought the while function does something an infinite amount of times. This is what I think this code is doing
It starts with A = 0, (not sure what the while A < 1 is doing), then the for statement does this
A = 0 + (-1)^1 = -1
A = -1 + 1 = 0
for k = 1, then it must repeat this statement (k=2). The A = 0 in this line is not from the first line of code, it comes from the result for k=1,
A = 0 + (-1)^2 = 1
A = 1 + 2 = 3
well I guess somewhere here the A < 1 is violated, thus the code should stop? I run it and I get 4. I don't understand how this code is working.
I am trying to decipher loop codes and I am having a lot of difficulty doing so
Here is an example code
Code:
A = 0;
while A < 1
for k=1:5
A = A+(-1)^k;
end
A = A+k;
end
So I thought the while function does something an infinite amount of times. This is what I think this code is doing
It starts with A = 0, (not sure what the while A < 1 is doing), then the for statement does this
A = 0 + (-1)^1 = -1
A = -1 + 1 = 0
for k = 1, then it must repeat this statement (k=2). The A = 0 in this line is not from the first line of code, it comes from the result for k=1,
A = 0 + (-1)^2 = 1
A = 1 + 2 = 3
well I guess somewhere here the A < 1 is violated, thus the code should stop? I run it and I get 4. I don't understand how this code is working.