Search code examples
for-loopnested-loops

Nested For Loop astrix pattern


I'm having a hard time trying to understand this loop. I understand it printing the 15 rows as it prints one then moves onto the next line and prints another but I don't understand it printing 30 columns/astrix (*). I seem to have hit a brick wall trying to understand it. Can anybody explain it clearly or visually so that I can understand.

int main() 
{  
int a, b; 


for (a=0; a < 15; a++)  
{
for (b=0; b < 30; b++)   
{
cout << "*";     // Print * (asterisk)   
} 
cout << endl;  
} 

cout << endl; 

system("PAUSE"); 
return 0; 
} 

Solution

  • You only print the asterisk in the body of the inner loop and don't start a new line, so it will print 30 asterisks next to each other i.e. one asterisk every time it executes. The outer loop then proceeds its execution by starting a new line and the process is repeated.