Here we look for repetitions. A repetition in a pattern is a strong indication that the programmer needs to use a loop.
Consider the following poem:
Mary had a little lamb, Little lamb, Little lamb, Little lamb, Mary had a little lamb, Little lamb, Little lamb, Little lamb,Problem: Write a program to print out the poem above using each statement below just once.
printf("Mary had a little lamb,\n"); printf("Little lamb,\n");
Problem Analysis: There are two large repetitions. Each large repetition contains three small repetitions nested inside it. Thus it is likely we can solve this problem with nested loops.
Let's get a piece of the problem done. We need 3 reps of Little Lamb, in each big rep. So put it into a loop. We need the \n so each new Little Lamb, comes out on its own line.
int i=0; while (i<3) { printf("Little lamb,\n"); i++; }Now if we add a statement to print the stuff about Mary we get:
printf("Mary had a little lamb,\n"); int i=0; while (i<3) { printf("Little lamb,\n"); i++; }This will print one of the big reps. But we want two reps not 1! To get two reps. Let's take the code above and put it into the body of an outside loop that runs for two reps. That is:
int j=0; while (j<2) { put it here j++; }So putting it in:
int j=0; while (j<2) { printf("Mary had a little lamb,\n"); int i=0; while (i<3) { printf("Little lamb,\n"); i++; } j++; }