Skip to content
Lesson 3 of 7

Step 1 of 5 · Reading · ~1 min

Learn

Control 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.

Printing a number from a branch

A branch that has to print a number is where this lesson trips people. disp renders a number the way the interactive prompt does, which puts whitespace in front of it:

n = 7;
disp(n)              %  7      <- leading space, three characters
printf("%d\n", n)    % 7       <- exactly what you asked for

Text is safe either way — disp("Fizz") writes Fizz and nothing more. So a branch printing a fixed word can use disp, while a branch printing a number wants printf with an explicit format.

Up nextFunctionsControl Flow and Functions

Discussion

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

Sign in to post a comment or reply.

Loading…