It is possible to use Markdown to do that, but it is not in my experience, the best option. Reason for this is that what you should really do is incorporate the code from from real programs that can be tested using some (unit-)test harness.
That way there is far less chance that the code you include in your book contains some error that would go unnoticed because it was never run.
markdown is however kept very simple and does not support inclusions of code from somewhere else.
- There are ways around that limitation using
pandoc, as it allows merging of files as it allows merging of files, but for including code snippets of a few lines at a time that is a bit too course to my liking, and you loose the overview in your markdown text where goes what.
- There are other add-ons for markdown to assemble that keep the include information within the file. You would need to somehow generate the snippets of code to include in your text in separate files and include them.
If you have anything more than a few snippets you should look at the reStructuredText format, and especially its use within sphinx. It was particularly written to document source code. Originally for Python but also supporting other programming languages. It has native support for the including/assembling.
Sphinx has build in support for epub and pdf generation, the latter without having to go through LaTeX. With
pandoc, you would have to use LaTeX which is not always trivial to set up, depending on your OS.