A farmer who wants to follow the companion planting method for crops, it would better when they are implementing in gardening and agriculture is the planting of different crops in proximity for pest control, pollination, providing habitat for beneficial creatures, maximizing use of space, and to otherwise increase crop productivity. Companion planting is a form of polyculture.
In the Companion planting method, the crops are planted in the following pattern.
For n = 5, the pattern should be as follows,
XXXXXXXXX
XX - XXX -XX
X - X - X -X -X
XX -XXX - XX
XXXXXXXXX
XX - XXX- XX
X- X- X - X - X
XX - XXX -XX
XXXXXXXXX

Hint: Number of rows = 2*n - 1

Write a program to print the pattern for the given ‘n’ value.


Input format:
Input is an integer which corresponds to the n.

Output format:
Refer the sample output.

Sample Intput 1:
5
Sample Output 1:
XXXXXXXXX
XX - XXX -XX
X - X - X -X -X
XX -XXX - XX
XXXXXXXXX
XX - XXX- XX
X- X- X - X - X
XX - XXX -XX
XXXXXXXXX

Sample Input 2:
9
Sample Output 2:
XXXXXXXXXXXXXXXXX
XX-----XXX-----XX
X-X---X-X-X---X-X
X--X-X--X--X-X--X
X---X---X---X---X
X--X-X--X--X-X--X
X-X---X-X-X---X-X
XX-----XXX-----XX
XXXXXXXXXXXXXXXXX
XX-----XXX-----XX
X-X---X-X-X---X-X
X--X-X--X--X-X--X
X---X---X---X---X
X--X-X--X--X-X--X
X-X---X-X-X---X-X
XX-----XXX-----XX
XXXXXXXXXXXXXXXXX

Solution Code :

#include<stdio.h>
int main()
{
    int n;
    int r;
    scanf("%d",&n);
    r=2*n-1;
    int a[r][r],l=r-1;
    printf("\n");
    int q=r/2-1,p=r/2+1,e=1,d=l-1;
    for(int i=1;i<r;i++)
    {
        if(i<r/2)
        {
            a[i][q]='X';
            q--;
            a[i][p]='X';
            p++;
        }
        if(i>r/2)
        {
            a[i][e]='X';
            e++;
            a[i][d]='X';
            d--;
        }
        
        
    }
    
    for(int i=0;i<r;i++)
    {
      for(int j=0;j<r;j++)
      {
          if(i==j||j==l||j==r-1||j==0||i==0||i==r-1||j==r/2||i==r/2)
          a[i][j]='X';
          else if(a[i][j]=='X')
          {
          printf("%c",a[i][j]);
          continue;
          }
          else
          a[i][j]='-';
          printf("%c",a[i][j]);
      }
      l--;
      printf("\n");
    }
}

Recommended

Post a Comment