Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Unreasonable loop

  1. Feb 15, 2015 #1
    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]
     
  2. jcsd
  3. Feb 15, 2015 #2

    Borg

    User Avatar
    Gold Member

    Code (Text):

    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.
     
  4. Feb 15, 2015 #3

    Dale

    Staff: Mentor

    If you want 25 you should do n1=n1+1 instead.
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook




Similar Discussions: Unreasonable loop
  1. Fsolve and FOR loops (Replies: 1)

  2. For loop problem (Replies: 3)

  3. For loop in matlab (Replies: 3)

  4. Mathematica looping (Replies: 3)

Loading...