English Deutsch Français Italiano Español Português 繁體中文 Bahasa Indonesia Tiếng Việt ภาษาไทย
All categories

Im new to C++ and wonder if anybody can help me out.
I need to center this pyramid this is what ive done
#include
using name space std
int main ()
{
int j,i
for (i=1; i<=5; i++)
{
for (j=1; j cout << "*";
cout << endl;
}
having this result
*
**
***
****
*****
I need to center it so it can look like a PYRAMID with asterics.

2007-02-28 03:23:14 · 4 answers · asked by Anonymous in Computers & Internet Programming & Design

4 answers

#include
using namespace std;

void print_pyramid(int height);

int main()
{

print_pyramid(10);

return 0;
}
void print_pyramid(int height)
{
int line;
int const MARGIN = 10;

cout << "\n\n";

for (line = 1 ; line <= height ; line++)
{
int count;
int total_no_of_spaces = MARGIN + height - line;

for (count = 1 ; count <= total_no_of_spaces ; count++)
cout << ' ';

for (count = 1 ; count <= line * 2 ; count++)
cout << '*';

cout << '\n';
}

cout << "\n\n";
}

2007-02-28 03:42:08 · answer #1 · answered by Xtrax 4 · 0 0

You're going to have an issue with "centering" it... just think of the first two lines:
*
**
How do you center one asterisk over two of them? The only way is to put 1/2 space in front of the one asterisks. But you can't print a 1/2 space. And if this is a console application, odds are you're using a fixed font so changing the font for the spaces isn't going to help.

You can get close by adding a "spacing loop" between the two loops that goes from 1 to (5-i)/2 and prints a space each time through.

2007-02-28 03:38:01 · answer #2 · answered by BigRez 6 · 0 0

Here you go:

// NOTE: I'm using dashes "-----" below just to leave space.
// Don't use them in your actual program.

// n = the pyramid's number of rows (levels)

// The following for-loop does some work to each level of the
// pyramid
for (int i = 0; i < n; i++)
{
------ // The following for-loop prints the appropriate number of
------ // spaces
------ for (int j = i; j < n - 1; j++)
------ {
------------ cout << " ";
------ }
------ // The following for-loop prints the appropriate number of
------ // asterics
------ for (int k = 0; k < ((i * 2) + 1); k++)
------ {
------------ cout << "*";
------ }
------ cout << endl;
}

2007-02-28 04:33:43 · answer #3 · answered by Silver_Sword 3 · 0 0

int max max = 10; // 10 can chg to different extensive type for (i = a million ,i<=max,i++) { for (j = i , j<(2*i), j++) { printf (tp.c.d,j); //command to print j } printf ("n"); // substitute line }

2016-11-26 20:23:25 · answer #4 · answered by ? 4 · 0 0

fedest.com, questions and answers