Search code examples
octaveoctave-gui

summation series using octave of while loop


The summation

sun=0;
i=0;
while(i<=20)
while(j<=5)
y=i+2j
j=j+1;
end
j=0;
i=i+1
end

Failed with error

when I run it, it displays a lot of y=20+i


Solution

  • There are many problems with this code.
    Here is a cleaned-up version below (i.e. appropriate indentation, spacing, etc) with comments

    sun = 0;   % What's the `sun` doing here? Did you mean `y`?
    i   = 0;
               % Where's the initialisation of j in this list?
               %    You are using it below uninitialised!
    
    while i <= 20   % Octave/matlab does not need brackets in `while`, `for`,
                    %   `if` statements, etc.
    
        while j <= 5        % Proper indentation clarifies scope of 
                            %   outer 'while' block
    
            y = i + 2 * j   % Octave/matlab do not support '2j' syntax.
                            %   You need to multiply explicitly.
    
            j = j + 1;
    
        end
    
        j = 0;      % Why aren't you resetting this *before* the inner loop? 
                    % How do you think your sum will be affected if `j` is,
                    %   let's say `10`, at the start of this program?
    
        i = i + 1   % Are you leaving the `;` out intentionally here?
                    %   (and `y` above?). If you don't want these values
                    %   printed on the console each time, put a `;` at the end.
    end