12. Nested Loops
Exercises
- What will be written out by the following piece of code?
for (int j=0; j<20; j++) { j += j; cout << j << endl; }
To find that out, first execute this piece of code by hand and then verify your results by executing it by a computer. - Write a program that reads in one number (let us call it n) and then prints out all the natural numbers having squares smaller than n.
- Write a program that reads in 10 numbers, then writes out whether any two of them are equal.
- Write a program that reads in a natural number n. Suppose that there are n players in a chess game tournament. Each player is represented by a unique tournament number from 1 to n. They all have to play a single match against each other. For each match that will be played, the program should write out the tournament numbers of the two players playing the match. For example, if n is 3, then the result is: (1,2) (1,3) (2,3). If you need a hint, see the footnote[*].
A nested loop is obviously required. How could we get the first tournament number to always be smaller than the second one? An if
statement could do it. A better way: the inner for
loop does not need to start counting from 1; it can calculate its starting value using an expression.