******
******
******
******
******
The for loop has three stages: initialization (it's executed once, as the loop begins).
termination (expression evaluates to false, the loop then terminates).
increment (what is produced after each cycle through the loop).
There are five lines of *'s because we set k=1 and tell the loop to produce the output of *'s until the statement for (int k = 1; k <= 5; k++) is false. This happens to be 5 times since there are only 5 lines.
As for the number of *'s in a line, the for loop tells i to create the loop. Since we set i=1, the for loop says to print out an * until the statement for (int i = 1; i <=6; i++) is false. This happens when the i value reaches 7. Since on 7 it is false, it terminates and produce 6 *'s.
The way the for loop works is first the compiler will verify that the for loop for k is true for k=1, then it will go down and verify that the for loop for i is true for i=1. Because of the System.out.println() , it skips a line and goes on to the next line. It then goes back up to the for loop for k because of the k++ in the code. This means thats k = k+1. So now it produces the second line of stars because the loop is true. After this, it goes down to the for loop for i++ so it produces 2 stars on the lines. This loop continues until k reaches 6 and i reaches 7
Hi Ryan. Rewrite the appropriate loop that controls the number of *'s so that only 3 *'s are printed per line.
ReplyDeletefor (int i = 1; i <=3; i++)
ReplyDeletethis produces 3 *'s per line
Very good. 50 XPs awarded for this completion.
ReplyDelete