There are 2 errors.
1. for (int j = 0; j < 4 - i; j++) //for the spaces.
You have initialised (lack of initialisation rather) the number of rows to 5 in the first for() loop.
So, you should be checking for j<5-i in the second for loop too.
2.
for (int p = 0; p < i+1 ; p++) //printing the stars.
The condition is wrong here especially for the last row, since you have to print twice the number of rows + 1.
The condition should be for (int p = 0; p < (i*2+1) ; p++)
The reformatted code should something like this:
#include <iostream>
using namespace std;
int main()
{
int n = 5; // Initialise the number of rows at the start or get it as an user input.
for (int i=0; i < n; i++) //0,1,2,3,4
{
for (int j = 0; j < (n-i); j++) //for the spaces.
{
cout <<" ";
}
if (i == 0 || i == (n-1))
{
for (int p = 0; p < (i*2+1) ; p++) //Print Stars: Condition corrected.
cout << "*" ;
}
else
{
for (int m = 0; m < 2; m++) //inner stars
{
cout << "*";
for (int k = 0; k < (2*i) - 1 ;k++ ) //inner spaces
{
cout << " ";
}
}
}
cout << endl;
}
return 0;
}
This will yield output: (since n = 5)