#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2012
    Posts
    8
    Rep Power
    0

    How is this code works ?


    #include<stdio.h>

    int main()
    { int numbers[10]={1,0,0,0,0,0,0,0,0,0};
    int j,i;

    for(j=0;j<10;j++)
    for (i=0;i<j;i++)
    numbers[j]+=numbers[i];

    for (j=0;j<10;j++)
    printf("%i ",numbers[j]);

    printf ("\n");
    return 0;
    }

    here is the output 1 1 2 4 8 16 32 64 128 256

    could someone please explain to me how this works ? I really dont understand if the initial value of j is zero and the initial value of i is zero and in the second for loop the condition that i<j but what I understand is 0 is not less than 0 so should the program skip this line (numbers[j]+=numbers[i]; ) I'm really confused.
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Aug 2012
    Posts
    156
    Rep Power
    33
    add braces and print the variables

    Code:
    for (j = 0; j < 10; j++)
    {
        for (i = 0; i < j; i++)
        {
            numbers[j] += numbers[i];
            printf("i: %d; j: %d (array elements: %d %d)\n",
                        i, j, numbers[j], numbers[i]);
        }
    }
  4. #3
  5. Contributing User
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Aug 2011
    Posts
    4,711
    Rep Power
    480

    I can triple the length of any program!


    Code:
    #include<stdio.h>
    #include<string.h>
    
    #define DIM(A) (sizeof(A)/sizeof(*(A)))
    #define MIN(A,B) ((A)<(B)?(A):(B))
    
    void display(char*s,int*a,int n) {
      int i;
      for (i = 0; i < n; ++i)
        printf("%d ",a[i]);
      puts(s);
    }
    
    int cumulative_sum(int*a,int n) {
      int i,sum = 0;
      for (i = 0; i < n; ++i)
        sum += a[i];
      return sum;
    }
    
    int main() {
      int i, numbers[10];
      memset(numbers,0,sizeof(numbers));
      display("reset",numbers,DIM(numbers));
      numbers[0] = 1;
      display("start",numbers,DIM(numbers));
      for(i = 1; i < DIM(numbers); i++) {
        display("\tprior to cumulative sum",numbers,MIN(i+1,DIM(numbers)));
        numbers[i] = cumulative_sum(numbers,i);
      }
      display("final",numbers,DIM(numbers));
      return 0;
    }
    [code]Code tags[/code] are essential for python code and Makefiles!
  6. #4
  7. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2012
    Posts
    8
    Rep Power
    0
    thank you

IMN logo majestic logo threadwatch logo seochat tools logo