Faustino Dilipa
Faustino Dilipa

Reputation: 13

Printing out characters in a target table pattern

I have to do a code in c, which is printing out target table pattern.

So input for example:

3
1
2
3


and the output:

*

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

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

I have done several tries, but its not working, cant do the mid-zones.
I've done this code, and for 1-2 its working, but i cant do for 2+.

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <math.h>

int main()
{
    int n,i,k;
    int p=0;
    int j=0,l=0;
    int d=0;
    scanf("%d",&n);
    for(i=0; i<n; i++)
    {
        scanf("%d",&k);
        d=((4*k)-3)*((4*k)-3);
            p=((4*k)-3);
        for(j=0; j<p; j++)
        {
            if(j==0 || j==p-1)
            {
                for(l=0; l<p; l++)
                    printf("*");
                        printf("\n");
            }

            if(j==p/2+1)
            {
                    for(l=0; l<p; l++)
                        {
                        if(l%2==0) 
                            printf("*");
                        else printf(" ");
                        }
                    printf("\n");
            }
            if(j>0 && j<p/2)
            {
                    for(l=0; l<p; l++)
                    {   
                        if(l==0 || l==p-1)
                            printf("*");
                        else printf(" ");
                    }
                    printf("\n");
                        }
                        if(j>p/2 && j<p-1)
            {
                    for(l=0; l<p; l++)
                    {   
                        if(l==0 || l==p-1)
                            printf("*");
                        else printf(" ");
                    }
                    printf("\n");
                        }

        }
    }
    return 0;
}

Upvotes: 0

Views: 47

Answers (1)

BLUEPIXY
BLUEPIXY

Reputation: 40155

#include <stdio.h>
#include <stdbool.h>

bool online(int size, int r, int c){
    if(size < 1)
        return false;
    int last = size-1;
    if((r == 0 || r == last) && (0 <= c && c <= last))
        return true;
    if((c == 0 || c == last) && (0 <= r && r <= last))
        return true;
    return online(size-4, r-2, c-2);
}

int main(void){
    int t, n, size;
    scanf("%d", &t);
    while(t--){
        scanf("%d", &n);
        size = 4*n-3;//1 + 4*(size-1);
        for(int r = 0; r < size; ++r){
            for(int c = 0; c < size; ++c){
                if(online(size, r, c))
                    putchar('*');
                else
                    putchar(' ');
            }
            putchar('\n');
        }
        putchar('\n');
    }
}

Upvotes: 1

Related Questions