That is great! We have a formula for the number of stars for the i th line. If we keep doing these calculations, we will see that the formula for the number of stars in the i th line, 2i-1 is correct for any line. Therefore, the number of stars in the third line should be 2*i-1=2*3-1=5. Therefore, we print three stars in the second line. Therefore, the number of stars in the second line should be 2*i-1=2*2-1=3. Therefore, we print one star in the first line. Therefore, the number of stars in the first line should be 2*i-1=2*1-1=1. Let us check, if the hypothesis is correct for our running example. That is, if we are in the i th line, the number of stars to be printed is 2*i-1. Notice that the number of stars to be printed = 2*the line number we are currently in minus 1. The question we are trying to frame here is, when we are in the i th row, how many stars will we print? The formula for the number of stars in a line Let us iterate over the number of stars in the lines again. Let us try to find a connection between the line number and how many stars to print in that line. Finding the relationship between a line and how many stars to printįor such a pattern-printing problem, it becomes beneficial if we can come up with a relationship between a line number i and how many stars we should print on that line. That is, “ i” will vary from 1 to 5 for the above example-pyramid contains five lines of stars. In my code, I will use a variable named i, to go over every line of stars. Our target is to use a loop to go over each line and print the stars. The pattern is such that the number of stars increases in consecutive lines. And finally, there are 9 stars in the fifth line.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |