Step 1 of 5 · Reading · ~1 min
Learn
Numerical Basics
GNU Octave was started in 1988 to teach undergrad numerical methods. Today it's a full open-source MATLAB alternative — with the same syntax, mostly compatible toolboxes, and a thriving community.
disp("Hello, Octave!")
disp(x)writes x followed by a newlineprintf("format", args)for C-style formatted output- Comments use
%or#(both work) - Statements end with newline; suppress output (when assigning) with trailing
; - Double-quoted strings interpret escapes (
"a\nb"is two lines); single-quoted ones do not ('a\nb'keeps a literal backslash and n). Format strings therefore want double quotes.
Reading stdin: input("") reads a value from stdin. With second arg "s" it reads as a string:
n = input("") % reads as a number
line = input("", "s") % reads as a string
disp is not printf
Both write to stdout, but they are not interchangeable. disp formats a value the way the interactive prompt would, and for a number that means leading whitespace. printf writes exactly the characters your format string asks for and nothing else.
disp("hi") % hi
disp(7) % 7 <- note the leading space
printf("%d\n", 7) % 7
Use disp for text you are printing literally, and printf whenever a number has to land in an exact position. Graded output is compared character by character, so a stray leading space is a wrong answer.
One more habit to build now: a statement with no trailing semicolon echoes its result, variable name and all.
x = 5 % prints "x = 5" (yes, two spaces - it is the prompt format)
x = 5; % prints nothing
That echo goes to stdout like any other output, so a forgotten semicolon in an exercise shows up as extra lines the grader never asked for.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…