Search code examples
c++for-loopnestednested-loops

C++ program, design using nested loop


I have to make a program for generating the following output:

Example:

 & & & & & & &
   & & & & &
     & & &    
       &

What I have done so far:

#include<iostream.h>
#include<conio.h>
void main()
{
    clrscr();
    int i,j,k,n;
    cout<<"How many rows?\n";
    cin>>n;
    for(i=n;i>0;i-=2)
    {
        cout<<"\n";

        for(k=(i+1)/2;k>0;--k)
        cout<<" ";

        for(j=1;j<=i;++j)
        cout<<"&";
    }
}

What the output comes:

    & & & & &
  & & &
&

Please correct me where I am making the mistake. Any help will be appreciated. Thanks.


Solution

  • Your first try seems a bit complicated. I'd do something like this:

    #include <iostream>
    
    int main()
    {
        int i,j,k,n;
        std::cout << "How many &'s in the start row?\n";
        std::cin >> n;
        std::cout << std::endl;
        for(i=0; i < n; i+=2)
        {
            for(k=0 ; k < i; k++ )
            {
                    std::cout << " ";
            }
            for(j=0; j<(n - i); ++j)
            {
                    std::cout<<" &";
            }
            std::cout << std::endl;
        }
        return (0);
    }