Go4Expert (http://www.go4expert.com/)
-   C (http://www.go4expert.com/forums/c/)
-   -   pattern program for square (http://www.go4expert.com/forums/pattern-program-square-t24041/)

 cexpert 30Nov2010 18:56

pattern program for square

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.

 virxen 1Dec2010 05:55

Re: pattern program for square

something like this maybe

Code:

```#include <stdio.h> #include <string.h> #include <stdlib.h> void drawsquare(int input); int reverse(char *);     char before[100]="";     char after[100]="";     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[10];             itoa(i%2,temp,10);             strcat(before,temp);             strcpy(after,before);             reverse(after);          }      } } int reverse(char * after1) { char temp[100]; 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; }```

 xpi0t0s 1Dec2010 16:44

Re: pattern program for square

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'); }```

 All times are GMT +5.5. The time now is 08:54.