# pattern program for square

Discussion in 'C' started by cexpert, Nov 30, 2010.

1. ### cexpertNew Member

Joined:
Nov 30, 2010
Messages:
1
0
Trophy Points:
0

Q : Ypu are given an odd number as input and you have to write a function to draw alternative squares of 1s and 0s.

Sample : input number : 7

Output : 1 1 1 1 1 1 1
1 0 0 0 0 0 1
1 0 1 1 1 0 1
1 0 1 0 1 0 1
1 0 1 1 1 0 1
1 0 0 0 0 0 1
1 1 1 1 1 1 1

Prototype for the function : void drawsquare(int input);

Please provide generic code for any odd number entered.

2. ### virxenNew Member

Joined:
Nov 24, 2009
Messages:
387
90
Trophy Points:
0
something like this maybe

Code:
```#include <stdio.h>
#include <string.h>
#include <stdlib.h>

void drawsquare(int input);

int reverse(char *);
char before="";
char after="";

int main(){
int squares;

printf("\n number of squares=");
scanf("%d",&squares);getchar();
drawsquare(squares);
getchar();
return 0;
}

void drawsquare(int squares){
int i,j;
for (i=1;i<=squares;i++){
if (i>=squares/2+2){
int length1=strlen(before);
if (length1-1>=0){
before[strlen(before)-1]='\0';
strcpy(after,before);
reverse(after);
}
}
printf("\n%s",before);
for (j=0;j<squares-strlen(before)*2;j++){
printf("%d",i%2);
}
printf("%s",after);
if (i<squares/2+2){
char temp;
itoa(i%2,temp,10);
strcat(before,temp);
strcpy(after,before);
reverse(after);
}
}
}

int reverse(char * after1) {
char temp;
int i;
for (i=0;i<strlen(after1);i++)
temp[i]=after1[strlen(after1)-i-1];
temp[strlen(after1)]='\0';
strcpy(after1,temp);
return 0;
}

```

Last edited: Dec 1, 2010
cexpert and shabbir like this.
3. ### xpi0t0sMentor

Joined:
Aug 6, 2004
Messages:
3,009
203
Trophy Points:
63
Occupation:
Senior Support Engineer
Location:
England
Nice one. Here's another solution. BTW OP, you should also work on your own ideas, not just hand this stuff in. Plagiarism is a serious offence in academic circles (and tutors can spot it a mile off).
Code:
```void drawsquare(int input)
{
int maxN=(input-1)/2;
printf("input=%d; maxN=%d\n",input,maxN);
for (int y=-maxN; y<=maxN; y++)
{
for (int x=-maxN; x<=maxN; x++)
{
int px=(x<0) ? -x : x;
int py=(y<0) ? -y : y;
char digit='0';
for (int M=1; M<=maxN; M+=2)
{
if ((px==M && py<=M)) || (py==M && px<=M))
digit='1';
}
putchar(digit);
}
putchar('\n');
}
putchar('\n');
}
```

cexpert likes this.