Can any one help me to optimize this code. Or possible to alter and make it more simple
The out put i need to get is

1
 212
32123
.......

this is the code

main()
{
      int i,j,k,n=4,val,flag=0;
      for(i=0;i<n;i++)
      {
                      for(j=1;j<n-i;j++)
                         putchar(' ');
                      val=i+1;
                      flag=0;
                      for(k=0;k<2*i+1;k++)
                      {
                          
                          printf("%d",val);
                          if(val == 1)
                            flag = 1;
                           if(flag)
                             val++;
                            else
                            val--;  
                       } 
                       putchar('\n');
       }
                       getch();
}

Thanks

Optimise how?

Make it faster - not likely, since it's I/O bound to begin with with all those output statements.
Make it shorter - probably, but sooner or later it becomes excessively harder to read / write / debug.

I can optimise the readability like so.

main()
{
    int i, j, k, n = 4, val, flag = 0;
    for (i = 0; i < n; i++) {
        for (j = 1; j < n - i; j++)
            putchar(' ');
        val = i + 1;
        flag = 0;
        for (k = 0; k < 2 * i + 1; k++) {
            printf("%d", val);
            if (val == 1)
                flag = 1;
            if (flag)
                val++;
            else
                val--;
        }
        putchar('\n');
    }
    getch();
}

this will be considerably faster if only because it uses just one "printf" statement to display the pyramid.

#include <stdio.h>

void geometric(int number, int *result)
{
    if (number)
    {
        *result += number--;
        geometric(number, result);
    }
}


int main()
{
    char stringNum[3], *pyramid, *pyr_p;
    int numLines, arraysize, i, printNum;

    // request size of "pyramid"
    printf("enter number: ");
    gets(stringNum);
    numLines = atol(stringNum);
    if (numLines<0) return 0;

    // dynamically allocate pyramid array
    arraysize = numLines * numLines + 1;
    geometric((numLines+1), &arraysize);
    pyramid = malloc (arraysize * sizeof(char));
    memset(pyramid,32,arraysize);
    pyr_p = pyramid;

    //develop pyramid pattern
    for (i=1; i<=numLines; i++)
    {
        pyr_p += (numLines-i);
        printNum = i;
        while (printNum)
            *pyr_p++ = 48 + (printNum-- % 10);
        while (++printNum < i)
            *pyr_p++ = 48 + ((printNum+1) % 10);
        *pyr_p++ = '\n';
    }
    *pyr_p = 0;

    //print pyramid pattern to term
    printf("\n%s\n",pyramid);
    free(pyramid);
    return 0;
}

>this will be considerably faster if only because it uses just one "printf" statement
Somehow I doubt that you'll notice much difference, especially since in saving calls to printf, you added calls to malloc, free, gets, atol, memset, and a statistically significant number of mathematical operations. Not to mention that it's highly unlikely the pattern will be large enough to warrant any kind of performance optimization.

au contraire, mon frere

try running mine with a line size of 40, and then try running his with the same (change n=40)

mine is about 2x as fast.

and i'm certain the gain will continue to increase as line size increases

>mine is about 2x as fast.
That reminds me of a weasel marketing ploy. Claim your software is twice as fast because your competition does some non-user related task in 1 second and yours does it in half a second. The user won't ever notice any difference, but you can sell more units by making big claims about trivial things.

>and i'm certain the gain will continue to increase as line size increases
Just how big are you expecting n to be? We're not talking about a generic sorting library here, we're talking about a school project to print a pyramid of numbers. I think you've lost track of the goal.

my goodness, did someone pee in your cornflakes?

he ASKED for an optimization, on his otherwise already-working code.

so i PROVIDED one.

you don't like it? fine, go roll your own.


at any rate, i think my example has instructive purposes, even if it's overkill for the project at hand.

>so i PROVIDED one.
You assumed he meant performance optimization. I'll note that he never did say what he meant by "optimize". He could have wanted something simpler, in which case you did the exact opposite.

>you don't like it? fine, go roll your own.
Wow, I can just imagine the stink you'll raise when I get around to actually reviewing your code. Don't get all huffy just because you think I'm attacking you.

>i think my example has instructive purposes
On that we agree, but I'm sure you think those purposes teach good things and I think otherwise.

>even if it's overkill for the project at hand
Actually, I'm inclined to think that it's so far above the OP's head, he won't even bother to read it thoroughly.

I can just imagine the stink you'll raise when I get around to actually reviewing your code

please do. i'm ready for a lesson. but stick to the "optimized" code please. the rest of the stuff was just so it would compile and work out of the box.

pyr_p = pyramid;

    //develop pyramid pattern
    for (i=1; i<=numLines; i++)
    {
        pyr_p += (numLines-i);
        printNum = i;
        while (printNum)
            *pyr_p++ = 48 + (printNum-- % 10);
        while (++printNum < i)
            *pyr_p++ = 48 + ((printNum+1) % 10);
        *pyr_p++ = '\n';
    }
    *pyr_p = 0;

    //print pyramid pattern to term
    printf("\n%s\n",pyramid);

You assumed he meant performance optimization.

Actually, I'm inclined to think that it's so far above the OP's head

i did assume speed optimization, so i assumed he would be interested in using pointers.

so i may have been wrong. meh. c`est la vie

*pyr_p++ = 48 + (printNum-- % 10); Isn't that undefined behavior?

no, but i think i see why you think so.... pyramid was already defined as an array, and pyr_p is a pointer to that array

for simplicity's sake:

char pyramid[10000], *pyr_p;

pyr_p = pyramid;

>but stick to the "optimized" code please. the rest of the
>stuff was just so it would compile and work out of the box.
Nice. Please review my latest awesome program that I'm going to give to newbies without any disclaimers:

void main ( void )
{
  int size = 1;
  int *p = malloc ( size );
  int i;

  // Initialize the string
  strcpy ( p, "I'm a little teapot" );
  
  // Print all characters in the string
  for ( i = 0; i < 1000; i++ );
    printf ( "%f", *p++ );
}

But stick to the part that I wanted them to see, please. The rest of the stuff was just so it would compile and work out of the box:

int size = 1;

:icon_rolleyes:

#include<stdio.h>
void main()
{
int i,j,cnt=0,k,sp;

for(i = 1;i<=7;i++,printf("\n"))
  {
     k = i;
     for(sp = 7;sp>=i;sp--)
          printf("  ");
    for(j = 1;i>1?j<=(i+cnt):j<=i;j++)
        {
             printf("%d ",k);
             if(j<i)
             k-=1;
             else
             k+=1;
        }
        cnt++;
    }
 }

Edited 3 Years Ago by Nick Evan: Fixed formatting

This article has been dead for over six months. Start a new discussion instead.