As someone that has published a programming book I can offer some insight.
First, the concept you are demonstrating trump "clean" code. You use the code that most clearly represents what you want to demonstrate, not necessarily the code that is the best. This is one of my big complaints about JavaScript: The Good Parts... it's an excellent book, but the author was trying to be overly cleaver with his example applications, which makes it a heck of a lot harder to figure out the basic concepts he is trying to demonstrate.
Second, writing code for the printed page is vastly different then writing code on a 1080p monitor! This has a huge impact on the types of samples you can create. When you have to keep code length in mind, namespaces for example, become the first victim.
Third, you often need to create a template that further examples build off of. Generally you want your source samples to be in a single code unit ( AKA, a .c, .java or .cs file ) or it gets much harder to understand and document. Thus you often develop some boilerplate code so you dont have to repeat it over and over. This often means making a number of global(ish) variables.
So, a number of factors go in to writing sample code in books that arent a factor for day to day programming. What you do not do however, is make global loop counters!