Sample Fragments using nested for loops


Nested FOR loops are often used to produce DESIGNS:
 

// The Isosceles Right Triangle (made with capital letters)
char outer, inner;
for (outer = 'F' ; outer >= 'A' ; outer--)

     for (inner = 'A' ; inner <= outer; inner++)
     { 
          cout <<inner; 
     } 

     cout<< "\n";
}
ABCDEF
ABCDE
ABCD
ABC
AB
A


 

// Rectangle comprised of x's
for (rows = 0; rows < 4; rows++) 

     for (col = 0; col < 12; col++) 
     { 
          cout << 'x' ; 
     }

     cout<< "\n";
}
xxxxxxxxxxxx
xxxxxxxxxxxx
xxxxxxxxxxxx
xxxxxxxxxxxx


 

// Isosceles triangle of x's centered on column 15 
for(i =0; i<=3;i++)
{
     gotoxy(15-i, 5+i);
     for(int j=1; j<=2*i+1; j++)
          cout<<"x";              //print the x's
     cout<<endl;
}
       x
     xxx
   xxxxx
 xxxxxxx

 

 

 Return to Topic Menu | Computer Science Main Page | MathBits.com | Terms of Use