Aquí, construiremos un programa en C++ para imprimir el patrón de forma de diamante de pirámide de estrella hueca que se puede lograr con dos enfoques, es decir
- Uso de bucle for
- Usando el ciclo while
Aporte:
n = 5
Producción:
* * * * * * * * * * * * * * * *
1. Usando el bucle for
C++
// C++ program to print hollow diamond pattern #include <iostream> using namespace std; int main() { int n = 5, rows, columns; // for loop is used to identify the number of rows and // it is used to print upper triangle for (rows = 1; rows <= n; rows++) { // used for printing the spaces for (columns = n; columns > rows; columns--) { cout << " "; } // print star cout << "*"; // again print the spaces for (columns = 1; columns < (rows - 1) * 2; columns++) { cout << " "; } if (rows == 1) { cout << "\n"; } else { cout << "*\n"; } } // for loop is used to identify the number of rows and // it is used to print lower triangle for (rows = n - 1; rows >= 1; rows--) { // used for printing the spaces for (columns = n; columns > rows; columns--) { cout << " "; } // print star cout << "*"; for (columns = 1; columns < (rows - 1) * 2; columns++) { cout << " "; } if (rows == 1) { cout << "\n"; } else { cout << "*\n"; } } return 0; }
Producción
* * * * * * * * * * * * * * * *
2. Usando el bucle while:
C++
// C++ program to print hollow diamond pattern #include <iostream> using namespace std; int main() { int n = 5, rows = 1, columns; // while loop is used to identify the number of rows and // it is used to print upper triangle while (rows <= n) { columns = n; // used for printing the spaces while (columns > rows) { cout << " "; columns--; } // print star cout << "*"; columns = 1; while (columns < (rows - 1) * 2) { cout << " "; columns++; } if (rows == 1) { cout << "\n"; } else { cout << "*\n"; } rows++; } // while loop is used to identify the number of rows and // it is used to print lower triangle rows = n - 1; while (rows >= 1) { columns = n; // used for printing the spaces while (columns > rows) { cout << " "; columns--; } // print star cout << "*"; columns = 1; while (columns < (rows - 1) * 2) { cout << " "; columns++; } if (rows == 1) { cout << "\n"; } else { cout << "*\n"; } rows--; } return 0; }
Producción
* * * * * * * * * * * * * * * *
Publicación traducida automáticamente
Artículo escrito por laxmigangarajula03 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA