Nazeem Nazeem - 1 month ago 5
C Question

Optimize hollow diamond pattern printing in c with minimum loops

Am trying to print hollow diamond pattern with * outline with minimum loops. I optimized with 2 loops.

My output using 2 loops

Enter no of rows: 5
***********
***** *****
**** ****
*** ***
** **
* *
** **
*** ***
**** ****
***** *****
***********


Is there any other way to still optimize this code?

void main()
{
int row,col,n,k;

printf("Enter no of rows: ");
scanf("%d",&n);

for(row=0, k=1; row<=2*n; row>n?k++:k, printf("\n"), row++)
for(col=-n; col<=n; col++)
(col>0?col:-col) < (row<=n?row:(row-2*k)) ? printf(" ") : printf("*");
}


'

Answer

you can save a lot of time by figuring out that (row<=n?row:(row-2*k)) doesn't depend on the inner loop variable

So writing that:

int row,col,n,k;

printf("Enter no of rows: ");
scanf("%d",&n);

for(row=0, k=1; row<=2*n; row>n?k++:k, putchar('\n'), row++)
{
    int z=(row<=n?row:(row-2*k));
    for(col=-n; col<=n; col++)
        putchar((col>0?col:-col) < z ? ' ' : '*');
}

is equivalent, but you have a lot less tests (note the better way to use ternary expression inside printf rather than 2 printfs).

(also replaced bloated printf by putchar which is fine here, and probably faster)