Nested Loops For Shapes
Nested Loops For Shapes
• #include <iostream>
• using namespace std;
• int main() {
• int rows;
• cout << "Enter number of rows: ";
•
*
cin >> rows;
• for(int i = 1; i <= rows; ++i) { **
• for(int j = 1; j <= i; ++j) { ***
• cout << "* ";
•
****
}
• cout << "\n"; *****
• }
• return 0;
• }
Program to Print a Half-Pyramid Using Numbers
#include <iostream>
using namespace std;
int main() {
int rows;
cout << "Enter number of rows: ";
cin >> rows; 1
for(int i = 1; i <= rows; ++i) { 12
for(int j = 1; j <= i; ++j) {
cout << j << " ";
123
} 1234
cout << "\n"; 12345
}
return 0;
}
Program to Print Half-Pyramid Using Alphabets
int main() {
char input, alphabet = 'A';
cout << "Enter the uppercase character you want to print in the last row: ";
cin >> input;
// convert input character to uppercase
input = toupper(input); A
for(int i = 1; i <= (input-'A'+1); ++i)
{
B B
for(int j = 1; j <= i; ++j) CCC
cout << alphabet << " "; DDDD
++alphabet;
cout << endl;
E E E E E
}
return 0;
}
Inverted Half-Pyramid Using *
#include <iostream>
using namespace std;
int main() {
int rows;
cout << "Enter number of rows: ";
cin >> rows; *****
for(int i = rows; i >= 1; --i) { ****
for(int j = 1; j <= i; ++j) { ***
cout << "* "; **
} *
cout << endl;
}
return 0;
}
Inverted Half-Pyramid Using Numbers
#include <iostream>
using namespace std;
int main() {
int rows;
cout << "Enter number of rows: ";
cin >> rows; 12345
for(int i = rows; i >= 1; --i)
{ 1234
for(int j = 1; j <= i; ++j) 123
{ 12
cout << j << " ";
} 1
cout << endl;
}
return 0;
}
Programs to Display Pyramids and Inverted Pyramids Using *
int main() {
int space, rows;
cout <<"Enter number of rows: ";
cin >> rows;
for(int i = 1, k = 0; i <= rows; ++i, k = 0) {
for(space = 1; space <= rows-i; ++space) { *
cout <<" "; ***
} *****
while(k != 2*i-1) { *******
cout << "* "; *********
++k;
}
cout << endl;
}
return 0;
}
Inverted Full Pyramid Using *
int main() {
int rows;
cout << "Enter number of rows: ";
cin >> rows;
for(int i = rows; i >= 1; --i) { *********
for(int space = 0; space < rows-i; ++space) *******
cout << " "; *****
for(int j = i; j <= 2*i-1; ++j) ***
cout << "* "; *
for(int j = 0; j < i-1; ++j)
cout << "* ";
cout << endl;
}
return 0;
}
To print a diamond shape with 2n rows
int main(){
int n;
cout<<" Enter Number of lines";
cin>>n;
int space = n - 1;
for (int i = 0; i < n; i++) { // run loop (parent loop) till number of rows
for (int j = 0;j < space; j++) // loop for initially space, before star printing
cout << " ";
for (int j = 0; j <= i; j++) // Print i+1 stars
cout << "* ";
cout << endl;
space--;
} // end of outer loop
//main program is continue
Continued
space = 0; // Repeat again in reverse order
for (int i = n; i > 0; i--) // run loop (parent loop) till number of rows
{
for (int j = 0; j < space; j++) // loop for initially space, before star printing
cout << " ";
for (int j = 0;j < i;j++) // Print i stars
cout << "* "; Final Output
cout << endl;
space++;
}
return 0;
}// end of main