Skip to content
Conditionals and Loops
step 1/5

Reading — step 1 of 5

Learn

~1 min readControl Flow and Functions

if/elseif/else/endif:

if n > 0
    disp("positive")
elseif n < 0
    disp("negative")
else
    disp("zero")
endif

Note endif closes the block (also end works). Same pattern for endfor, endwhile, endfunction, endswitch. The non-end versions read better but Octave accepts either.

for loops over a vector:

for i = 1:10
    printf("%d ", i)
endfor

while:

n = 1;
while n < 100
    n = n * 2;
endwhile

switch:

switch grade
    case "A"
        disp("excellent")
    case {"B", "C", "D"}
        disp("passing")
    otherwise
        disp("failed")
endswitch

Most tasks don't need explicit loops — vectorized operations are faster and clearer. Use loops for genuinely sequential algorithms.

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…