How to list posts for every category in WordPress

If you are building a news site or a directory based theme, you might like to print all categories and then output 10 recent posts in every category, through the use of the loop. Here is the snippet of the wordpress code, that does that. Basically its a double loop, first loops through all categories, then second loop through all the posts within a category. Just copy and paste the code wherever you want.

$cats = get_categories();

                // loop through the categries
                foreach ($cats as $cat) {
                    // setup the cateogory ID
                    $cat_id= $cat->term_id;
                    // Mate a header for the category
                    ?>
                    <div class="post">
                    <?php
                    echo "<h2>".$cat->name."</h2>";
                    // create a custom wordpress query
                    query_posts("cat=$cat_id&posts_per_page=10");
                    // start the wordpress loop!
                    if (have_posts()) : while (have_posts()) : the_post(); ?>

                        <?php // create our link now that the post is setup ?>
                       <p> <a href="<?php the_permalink();?>"><?php the_title(); ?></a><p>

                    <?php endwhile; endif; // done our wordpress loop. Will start again for each category ?>
                    </div>
                <?php } // done the foreach statement ?>