Use a counter in the output generating loop. When the counter reaches the desired value, exit the loops.
See the break statement.