1 Replies - 984 Views - Last Post: 27 September 2014 - 12:09 PM Rate Topic: -----

#1 xSlapppz   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 27-September 14

Triangles with nested for loops need help

Posted 27 September 2014 - 12:01 PM

So in class our teacher assigned us a program where we have to use nested for loops to creates triangles. My friend in class helped me get this far, but im confused about something, and might seem stupid, but im having a bit of a brain fart. How does the 2nd for loop print more than 1 star? since the for loop will only run the cout 1 time until it gets to the escape sequence \n, how does it print more than 1 star on a line? this is what is confusing me. I feel like if i can grasp the understanding of that and what the for loops are doing i can finish the rest of this program with ease

#include<iostream>
using namespace std;

int main()
{
    int n;                                                             
        cout<<"enter any number of rows";                                
        cin>>n;                                                            
        for(int i=1;i<=n;i++)                                                
        {      for(int j=1;j<=i;j++)                                     
                   cout<<"*";                                            
               cout<<"\n";                                               
        }                                  
system("pause");
return 0;
}


Is This A Good Question/Topic? 0
  • +

Replies To: Triangles with nested for loops need help

#2 snoopy11   User is online

  • Engineering ● Software
  • member icon

Reputation: 1549
  • View blog
  • Posts: 4,929
  • Joined: 20-March 10

Re: Triangles with nested for loops need help

Posted 27 September 2014 - 12:09 PM

The way for loops work in C and C++

is that for(statement)
        {
           //do something here
        }


you can also write it as

for(statement)
//do something here
//next line will not loop.


and only the first line will loop the second line will execute after the loop is finished

so in your code

for(int j=1;j<=i;j++)                                    
       cout<<"*";  //this line will loop                                         

       cout<<"\n"; // this line will execute after the loop finsihes 


Regards

Snoopy.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1