- 1

Using a for loop, write a C++ program to produce the output shown below:

******** ******* ****** ***** **** *** ** * Here is the code that accomplishes the above task. However, can anyone explain to me how does the for loop in the program actually work? include <iostream> using namespace std; int main(){ string star = "*"; for (int x=1; x <= 8; x++){ for (int i = 8; i >=x; i--){ cout << star; } cout << endl; } return 0; }

4th Feb 2017, 6:50 AM
Hirnesh Singh
Hirnesh Singh - avatar
3 Antworten
+ 2
The first for loop handles the lines. Each call runs the second for loop - which writes 'i-x' stars - and then makes a new line. On round 2 of the first for loop, it calls the second with x=2. This writes one less star. And so on. The purpose of the nested for loops is for one to count out how many lines to write, and the other to count out how many stars each line should get.
4th Feb 2017, 7:30 AM
Alan Tenore
Alan Tenore - avatar
+ 2
string star = "*"; // First loop which will run 8 times. // it begins at number 1 (x=1) and runs until x is less than or equals to 8 // x++ increases value of x by 1 each time the first loop runs. for (int x=1; x <= 8; x++){ // second loop which begins at 8 and runs while // the value of 'i' is higher than or equals to the value of x // and it decreases value of 'i' by 1 each time it runs. // when this loop runs for the first time it prints 1 "*" // and it does the same on current line until i = 0 for (int i = 8; i >=x; i--){ cout << star; } // after i = 0, it is adding a linebreak and first loop runs for a second time. cout << endl; } // SHORT SUMMARY: // First loop runs once, and second loop runs as many times as value of 'i' // after that it does the same process untill value of x == 8 // and when value of x is 8, second loop will stop because it runs while value of 'i' is >= 'x'
4th Feb 2017, 11:13 AM
Nedim Kanat
Nedim Kanat - avatar
0
Alright thank you for the detailed responses, finally got it. :D
4th Feb 2017, 6:54 PM
Hirnesh Singh
Hirnesh Singh - avatar