Read the book copyright statement and license. Some books have separate license for examples.
However, if you copy an example from a book into a code, then very often it's fair use, but if you copy the same example from a book into your own book, then very often it's a copyright infringement, unless explicitly allowed by the book license.
If I learn programming from a book that is copyrighted and use a small snippet (for example, how to do a particular kind of sort) from it in my own program, am I violating a copyright?