I want to print a pyramid like this.....
*****
****
***
**
*
This is my code.....

#include<iostream>
#include<conio.h>
using namespace std;
int main()
{
    int i,j;
    int b;
    char* sp=" ";
    cin>>j;
    for(int a=j;a>=1;a--)
 {   for( b=a;b>=1;b--)
    cout<<"*";
    cout<<endl;
    for(int k=1;k<b;k++)
    cout<<sp;
    
    }
    
    getch();
    return 0;
}

But it does not print that pyramid.Please help.

Dani AI

Generated

A short, practical fix and explanation based on the thread: posted a descending-star pyramid attempt and correctly noted the solution can be much simpler. The usual errors to watch for are using extra loops that run after a counter has been decremented to zero, and relying on nonstandard headers like <conio.h> and getch() which are unnecessary and reduce portability.

A minimal, modern C++ approach uses the std::string constructor to repeat a character, eliminating manual inner loops:

#include <iostream>
#include <string>

int main() {
    int n;
    if (!(std::cin >> n)) return 0;
    for (int i = n; i >= 1; --i)
        std::cout << std::string(i, '*') << '\n';
}

Troubleshooting notes: if a loop variable is reused after the loop body (for example, relying on its value after a decrementing inner loop), the result will often be zero or an unexpected value. Avoid keeping an extra counter just to print spaces or stars — either compute the needed count fresh each iteration or build a small string with std::string(count, ch). Also remove conio.h/getch() unless building for a specific legacy Windows environment; standard input/output and return from main are sufficient.

If a centered pyramid or other alignment is desired instead of left-aligned descending stars, prepend a computed number of spaces before the stars (for example, std::string(max - i, ' ') + std::string(i, '*')). That keeps the logic clear and avoids off-by-one mistakes.

First of all, there is no need for 3 loops, second, think if so many integers are really necessary.

Yea I have solved it.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.