0

I am trying to print a hollow diamond pattern. When I printed a solid diamond it goes perfectly. But when I tried to code for a hollow diamond, I stucked. The code is running for infinity. I know another approaches for this problem but I want to know about the flaws in my approach.

I am trying to print a hollow diamond in c++. First I print a solid diamond easily. But when I tried to print a hollow diamond, it runs for infinity. I am unable to understand why.

cin>>n;

    for(i=1; i<=n; i++){
        for(j=n; j>i; j--){
            cout<<"  ";
        }
        for(j=i; j>=1; j--){
            cout<<"* ";
        }
        for(j=1; j<i; j++){
            cout<<"* ";
        }
        cout<<endl;
    }

This is my code for solid diamond (upper half). It is running perfectly.

Below is the code for hollow diamond:

cin>>n;

    for(i=1; i<=n; i++){
        for(j=n; j>=1; j--){
            (j=i)?cout<<"* ":cout<<"  ";
        }
        for(j=1; j<i; j++){
            cout<<"* ";
        }
        cout<<endl;
    }

When I run this code for upper half of the hollow diamond, it runs for infinity. I am unable to understand why. I think, the problem lies in the nested for loop. According to me when I run from j=n to j=1 and applies the conditional statement that it should print "*" only when j=i. It should work fine. But instead, it runs for infinity. PLEASE HELP!!!

Evg
  • 25,259
  • 5
  • 41
  • 83
Harshit
  • 21
  • 2
  • 2
    [What is a debugger and how can it help me diagnose problems?](https://stackoverflow.com/questions/25385173/what-is-a-debugger-and-how-can-it-help-me-diagnose-problems) Also note that your code doesn't compile: `:1:1: error: 'cin' does not name a type` – Evg May 29 '23 at 15:21

1 Answers1

0

You are assigning the value of i to j in your ternary expression. Use == for equality testing.

(j=i)?cout<<"* ":cout<<"  ";

Also, you'd do better with an if statement: ternaries aren't the best habit to get into (though they have their place). Stylistically, your code will mesh better with other C/C++ if you get into the habit of using zero based loops (and, indeed, for arrays, you will have to anyway) rather than 1 based as here.

Pontus Gagge
  • 17,166
  • 1
  • 38
  • 51