NESTED LOOP
EX 1
/* Nested Loop Ex1 - Create a C++ program that will input
size of equilateral triangle 2 to 50 is the valid
size. Prompt the user to input any key to try again
and X/x to exit
CRISTINA A. PASCUA
CS10-lL/A3
May 12, 2016
*/
#include <iostream>
#include <cctype>
using namespace std;
int main()
{ int size, row, col;
char tryagain;
do{
system("cls");
do{
cout<<"Input size of equilateral triangle (2-50) : ";
cin>>size;
if(size<2 || size>50)
cout<<size<<" is INVALID"<<endl;
}while(size<2 || size>50);
cout<<endl<<endl;
cout<<"Solution 1 - using while loop"<<endl<<endl;
row = 1;
while(row<=size) //outer loop
{
col=1;
while(col<=row) //inner loop
{
cout<<"*";
col++;
}
cout<<endl;
row++;
}
cout<<endl<<endl;
cout<<"Solution 2 - using for loop"<<endl<<endl;
for(row = 1; row<=size; row++) //outer loop
{
for(col=1; col<=row; col++) //inner loop
{
cout<<"*";
}
cout<<endl;
}
cout<<endl<<endl;
cout<<"Solution 3 - using do-while loop"<<endl<<endl;
row = 1;
do//outer loop
{
col=1;
do //inner loop
{
cout<<"*";
col++;
} while(col<=row);
cout<<endl;
row++;
} while(row<=size);
cout<<endl<<endl;
cout<<"Press any key to try again or [X/x] to exit";
cin>>tryagain;
tryagain = toupper(tryagain);
}while(tryagain != 'X');
system("pause");
return 0;
}
EX 2 OUTLINE TRIANGLE
/* Nested Loop Ex1 - Create a C++ program that will input
size of equilateral triangle 2 to 50 is the valid
size. Prompt the user to input any key to try again
and X/x to exit
CRISTINA A. PASCUA
CS10-lL/A3
May 12, 2016
*/
#include <iostream>
#include <cctype>
using namespace std;
int main()
{ int size, row, col;
char tryagain;
do{
system("cls");
do{
cout<<"Input size of equilateral triangle (2-50) : ";
cin>>size;
if(size<2 || size>50)
cout<<size<<" is INVALID"<<endl;
}while(size<2 || size>50);
cout<<endl<<endl;
cout<<"Solution 1 - using while loop"<<endl<<endl;
row = 1;
while(row<=size) //outer loop
{
col=1;
while(col<=row) //inner loop
{ if (col==1 || row==size || row==col)
cout<<"*";
else
cout<<" ";
col++;
}
cout<<endl;
row++;
}
cout<<endl<<endl;
cout<<"Solution 2 - using for loop"<<endl<<endl;
for(row = 1; row<=size; row++) //outer loop
{
for(col=1; col<=row; col++) //inner loop
{ if (col==1 || row==size || row==col)
cout<<"*";
else
cout<<" ";
}
cout<<endl;
}
cout<<endl<<endl;
cout<<"Solution 3 - using do-while loop"<<endl<<endl;
row = 1;
do//outer loop
{
col=1;
do //inner loop
{ if (col==1 || row==size || row==col)
cout<<"*";
else
cout<<" ";
col++;
} while(col<=row);
cout<<endl;
row++;
} while(row<=size);
cout<<endl<<endl;
cout<<"Press any key to try again or [X/x] to exit";
cin>>tryagain;
tryagain = toupper(tryagain);
}while(tryagain != 'X');
system("pause");
return 0;
}