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!!!