Debugging: My Unexpected Result of n1=75

  • Thread starter Thread starter hokhani
  • Start date Start date
  • Tags Tags
    Debugging
Click For Summary
The program results in n1=75 due to the inner loop summing the values of m from 1 to 5, which totals 15, and this occurs 5 times in the outer loop. To achieve the expected result of n1=25, the code should be modified to increment n1 by 1 instead of m. This change will ensure that n1 is incremented only once per iteration of the outer loop. The current logic leads to an accumulation of values rather than a simple count. Adjusting the increment will correct the output as intended.
hokhani
Messages
579
Reaction score
20
The program below gives the result n1=75 wheras I expect to get n1=25. What is my mistake?

[C O D E]
clc
clear all
n1=0;
for n=1:5
for m=1:5
n1=n1+m;
end
end
n1
[/C O D E]
 
Physics news on Phys.org
Code:
clc
clear all
n1=0;
for n=1:5
    for m=1:5
        n1=n1+m;
    end
end
n1

The inner loop (for m=1:5) adds 15 to the value of n1. The outer loop (for n=1:5) tells it to do that 5 times. Therefore you get 75.
 
  • Like
Likes hokhani
If you want 25 you should do n1=n1+1 instead.
 
  • Like
Likes hokhani

Similar threads

  • · Replies 4 ·
Replies
4
Views
24K
  • · Replies 10 ·
Replies
10
Views
4K
Replies
12
Views
2K
  • · Replies 2 ·
Replies
2
Views
5K
  • · Replies 3 ·
Replies
3
Views
2K
Replies
3
Views
2K
  • · Replies 1 ·
Replies
1
Views
2K
  • · Replies 7 ·
Replies
7
Views
7K
  • · Replies 1 ·
Replies
1
Views
3K
  • · Replies 2 ·
Replies
2
Views
2K