-4

Could anyone tell me how to modify my code.

I want to print a diamond pattern using only two loops. If I enter 5, the diamond should be like this:

  *  
 *** 
*****
 *** 
  *  

I am half way done.

here is what I got so far.

  5
  *  
 *** 
*****
 ****
  ***

Below is my code:

#include <iostream>
using namespace std;
// print diamond. Instead of finding * pattern, just find "  " 's pattern.
int main()
{
    int size;
    cin >> size;
    int m = size / 2;

    for (int row = 0; row < size; row++) {
        for (int col = 0; col < size; col++) { //   Before || is the left part. After || is right part
            if ((row < m && (col < m - row || col > m + row)) || (row > m && col < row - m))
                cout << " ";

            else
                cout << "*";
        }
        cout << endl;
    }
    return 0;
}
Community
  • 1
  • 1
Shawn99
  • 15
  • 4

2 Answers2

1

https://github.com/Erendile/DiamondShape/blob/main/diamondShape.c

    #include <stdio.h>
    #include <stdlib.h>
    #include <math.h>
    #define SIZE 17

    int main()
    {
        for(int i = 0, k = 0, l = SIZE / 2; i < SIZE; k++)
        {
            if(k == abs((SIZE / 2) - i))
            {
                for(int j = 0; j < 2 * abs(abs(l) - (SIZE / 2)) + 1; j++) // 2x + 1 -> 1, 3, 5, 7, 9...
                    printf("*");

                printf("\n"), i++, k = -1, l--;
                continue;
            }
            printf(" ");
        }
        return 0;
    }
0

@Shawn use my code for printing. If you want to use your code only write separate for loop for printing downside of diamond.

#include <iostream>
using namespace std;
int main()
{//code
    int n, c, k, space = 1;
    cout<<"\n\nEnter number of rows: ";
    cin>>n;
    space = n - 1;
    for (k = 1; k<=n; k++)
    {
        for (c = 1; c<=space; c++)
            cout<<" ";
        space--;
        for (c = 1; c<= 2*k-1; c++)
            cout<<"*";
        cout<<"\n";
    }
    space = 1;
    for (k = 1; k<= n - 1; k++)
    {
        for (c = 1; c<= space; c++)
            cout<<" ";
        space++;

        for (c = 1 ; c<= 2*(n-k)-1; c++)
            cout<<"*";

        cout<<"\n";
    }
    return 0;
}
Community
  • 1
  • 1
yadav22ji
  • 1
  • 2
  • I just want to know how to print it using only two loops. – Shawn99 Jan 15 '17 at 19:00
  • best you can do is to reverse the code. for example if you are able to make half diamond then use "\n" that many times and reverse the loops and make the other half or diamond. – yadav22ji Feb 21 '17 at 17:58