Printing Output on Screen in Julia
Julia provides many methods of printing output on the screen. The Julia program starts with an interactive REPL (Read/ Evaluate /Print / Loop) as default.
- R: Reads what was typed;
- E: Evaluates the typed expression;
- P: Prints the return value;
- L: Loops back and repeats it ;
It helps in outputting the result of the expression on the screen immediately.
Print output using REPL
Using REPL, Julia provides the facility to evaluate the expression at the time of reading it, and further print the output of the expression.
Example:
If you don’t want the output to be printed you can use a semicolon(;) at the end.
Example:
Julia
4 + 4 ;
"hello" * "world" ;
|
To recall the last expression that was typed on the console we use ans command. The ans stores the last expression that was typed in the console.
Example:
Print output using print() and println() function
The most common function to print the output of the program in the console of Julia is print() and println(). To execute this command we just need to press Enter on the keyboard. The main difference is that the println() function adds a new line to the end of the output.
Example:
Julia
x = "The quick brown fox jumps over the lazy dog" ;
print (x)
x = "The quick brown fox jumps over the lazy dog" ;
println(x)
|
Print output using show() function
The show(io:: IO, x) function is also used to print output on the screen where the first argument is a stream. The REPL returns the output of show() function as a string.
Example:
Print output using printstyled() function
printstyled() function helps in printing out message in different colors.
Example:
Julia
for color in [:red, :cyan, :blue, :magenta]
printstyled( "Hello World $(color)\n" ; color = color)
end
|
Print output using printf() function
Julia also supports printf() function which is used in C language to print output on the console. Julia macro (which is used by prefacing it with the @ sign) provides the Printf package which needs to be imported in order to use. printf() is also used as a formatting tool. Here %f is used for conversion.
Example:
Julia
using Printf
@printf ( "pi = %0.20f" , float (pi))
|
Print output using sprintf() function
And we can use @sprintf() function in order to create another string
Example:
Julia
using Printf
@sprintf ( "pi = %0.20f" , float (pi))
|
Print output using write() function
write() function is used to write the output to a file and it prints the no. of characters present in the string on the console.
Example:
Julia
open ( "geek.txt" , "w" ) do io
write(io, "The quick brown fox jumps over the lazy dog" );
end
readline( "geek.txt" )
|
Last Updated :
28 Jul, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...