Thread: fill array with odd numbers

  1. #1
    Registered User
    Join Date
    Nov 2021
    Posts
    6

    Question fill array with odd numbers

    how can I fill this array of 10 elements with odd numbers? Thank you

    Code:
    #include <stdio.h>
    
        main ()
    {
        int a[10];
        int b,i;
        a[0]=1;
    
        for (b=0;b<9;b++)
        {
            a[i] = a[i]+2;
    
        }
        for (b=0;b<10;b++)
        {
            printf ("%d\n", a[i]);
    
        }
    }

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,069
    > a[i] = a[i]+2;
    Perhaps you should use [b] as your array subscript.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Registered User
    Join Date
    Nov 2021
    Posts
    6
    Thank you. I tried using b as an array subscript, however, i got only 10 zeroes as output. I used this code.
    Code:
    #include <stdio.h>
    
        main ()
    {
        int a[10];
        int b,i;
        a[0]=1;
    
        for (b=0;b<9;b++)
        {
            a[b] = a[b]+2;
    
        }
        for (b=0;b<10;b++)
        {
            printf ("%d\n", a[i]);
    
        }
    }

  4. #4
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,069
    > printf ("%d\n", a[i]);
    Yah think this should be a different subscript as well?

    > for (b=0;b<9;b++)
    a[0] is already set, so perhaps this loop should start at 1.

    Also, think about what "this element is the previous element + 2" means.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  5. #5
    Registered User
    Join Date
    Nov 2021
    Posts
    6
    Thanks again. I am getting lost. I tried to change these things, but the out does not make sense. I got this
    Code:
    1
    2
    4199707
    2
    10
    2
    66
    2
    10752978
    0
    How can I just fill the array with odd numbers, i taught this strategy would work.

    Code:
    #include <stdio.h>
    
        main ()
    {
        int a[10];
        int b,i;
        a[0]=1;
    
        for (b=1;b<9;b++)
        {
            a[b] = a[b]+2;
    
        }
        for (b=0;b<10;b++)
        {
            printf ("%d\n", a[b]);
    
        }
    }

  6. #6
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,069
    > a[b] = a[b]+2;

    Compare with
    a[b] = a[b-1]+2;

    And you want to do <10 for both loops.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  7. #7
    Registered User
    Join Date
    Nov 2021
    Posts
    6
    Thank you so much! It works now and I finally understand what the problem was.

  8. #8
    Registered User
    Join Date
    Feb 2019
    Posts
    951
    Instead of copying the previous item of the array adding 2, this is, actually, faster:
    Code:
    void fillodd( int *p, size_t elems )
    {
      int q = 1;
      while ( elems-- )
        *p++ = 2*q++ + 1;
    }

  9. #9
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,069
    Any decent compiler will do that optimisation for you, without making the code obscure in the process.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  10. #10
    Registered User
    Join Date
    Feb 2019
    Posts
    951
    Let's see:
    Code:
    #include <stddef.h>
    
    // "unobscured" code.
    void fill( int *p, size_t elems )
    {
      int i;
    
      p[0] = 1;
      for ( i = 1; i < elems; i++ )
        p[i] = p[i-1] + 2;
    }
    
    // "obscured" code, using pointer and pos-increment.
    void fill2( int *p, size_t elems )
    {
      int q = 0;
    
      while ( elems-- )
        *p++ = 2 * q++ + 1;
    }
    This will give us, with -O2 (gcc):
    Code:
    fill:                     fill2:
      mov [rdi],1               test  rsi,rsi
      cmp rsi,1                 je  .exit
      jbe .exit                 mov eax,1
      lea rax,[rdi+4]           lea rdx,[rdi+rsi*4]
      lea rcx,[rdi+rsi*4-4]
      mov edx,1                 align 4
      jmp .first              .loop:
                                add rdi,4
      align 4                   mov [rdi-4],eax
    .loop:                      add eax,2
      add rax,4                 cmp rdi,rdx
    .first:                     jne .loop
      add edx,2               .exit:
      mov [rax],edx             ret
      cmp rax,rcx
      jne .loop
    .exit:
      ret
    Last edited by flp1969; 01-07-2022 at 02:27 PM.

  11. #11
    Registered User
    Join Date
    Dec 2017
    Posts
    1,312
    I doubt salem meant to compare those two functions. They will obviously generate very different code. Presumably he meant something more like this:
    Code:
    #include <stdio.h>
     
    void fill(int *a, size_t size) {
        for (size_t i = 0; i < size; ++i) a[i] = i * 2 + 1;
    }
     
    void fill2(int *a, size_t size) {
        int q = 0;
        while (size--) *a++ = 2 * q++ + 1;
    }
     
    void print(int *a, size_t size) {
        for (size_t i = 0; i < size; ++i) printf("%d ", a[i]);
        putchar('\n');
    }
     
    int main() {
        int a[10];
        fill(a, 10);
        print(a, 10);
        fill2(a, 10);
        print(a, 10);
        return 0;
    }
    Result with -O2:
    Code:
    fill:
    .LFB12:
        .cfi_startproc
        testq    %rsi, %rsi
        je    .L1
        leaq    (%rdi,%rsi,4), %rdx
        movl    $1, %eax
        .p2align 4,,10
        .p2align 3
    .L3:
        movl    %eax, (%rdi)
        addq    $4, %rdi
        addl    $2, %eax
        cmpq    %rdx, %rdi
        jne    .L3
    .L1:
        ret
    
    fill2:
    .LFB13:
        .cfi_startproc
        testq    %rsi, %rsi
        je    .L9
        leaq    (%rdi,%rsi,4), %rdx
        movl    $1, %eax
        .p2align 4,,10
        .p2align 3
    .L11:
        addq    $4, %rdi
        movl    %eax, -4(%rdi)
        addl    $2, %eax
        cmpq    %rdi, %rdx
        jne    .L11
    .L9:
        ret
    Sign at the Sichuan Tobacco Project Hope Primary School:
    "Work hard for society. Tobacco can help you become an achiever!"

  12. #12
    Registered User
    Join Date
    Feb 2019
    Posts
    951
    Ok... the first is the same as the second. But I fail to see why pointer arithmetic and indirection, plus pos-increment are "obfuscation". To me, obfuscation is this:
    Code:
    /* ball.c */
    /* Compile with: 'gcc -ansi -o ball ball.c -lm' */
    /* Works on linux */
    #include <stdio.h>
    #include <math.h>
    #include <unistd.h>
    #include <sys/ioctl.h>
     
                 main() {
             short a[4];ioctl
          (0,TIOCGWINSZ,&a);int
        b,c,d=*a,e=a[1];float f,g,
      h,i=d/2+d%2+1,j=d/5-1,k=0,l=e/
     2,m=d/4,n=.01*e,o=0,p=.1;while (
    printf("\x1b[H\x1B[?25l"),!usleep(
    79383)){for (b=c=0;h=2*(m-c)/i,f=-
    .3*(g=(l-b)/i)+.954*h,c<d;c+=(b=++
    b%e)==0)printf("\x1B[%dm ",g*g>1-h
    *h?c>d-j?b<d-c||d-c>e-b?40:100:b<j
    ||b>e-j?40:g*(g+.6)+.09+h*h<1?100:
     47:((int)(9-k+(.954*g+.3*h)/sqrt
      (1-f*f))+(int)(2+f*2))%2==0?107
        :101);k+=p,m+=o,o=m>d-2*j?
          -.04*d:o+.002*d;n=(l+=
             n)<i||l>e-i?p=-p
                 ,-n:n;}}
    My entire point previously: Instead of copying the previous array item adding 2, 2n+1 will give the odd values easily...
    Last edited by flp1969; 01-07-2022 at 06:28 PM.

  13. #13
    Registered User
    Join Date
    Dec 2017
    Posts
    1,312
    It's not obfuscating but fill2 is harder for a beginner to understand. :-)

    That ball program is pretty good. This flight simulator is pretty cool. The code and scenary files can be found here: banks

    Build: make banks
    Run: ./banks < river.sc
    Ailerons/Elevator: arrow keys
    Center controls: return
    Throttle: page-up, page-down
    Code:
    #include                                     <math.h>
    #include                                   <sys/time.h>
    #include                                   <X11/Xlib.h>
    #include                                  <X11/keysym.h>
                                              double L ,o ,P
                                             ,_=dt,T,Z,D=1,d,
                                             s[999],E,h= 8,I,
                                             J,K,w[999],M,m,O
                                            ,n[999],j=33e-3,i=
                                            1E3,r,t, u,v ,W,S=
                                            74.5,l=221,X=7.26,
                                            a,B,A=32.2,c, F,H;
                                            int N,q, C, y,p,U;
                                           Window z; char f[52]
                                        ; GC k; main(){ Display*e=
     XOpenDisplay( 0); z=RootWindow(e,0); for (XSetForeground(e,k=XCreateGC (e,z,0,0),BlackPixel(e,0))
    ; scanf("%lf%lf%lf",y +n,w+y, y+s)+1; y ++); XSelectInput(e,z= XCreateSimpleWindow(e,z,0,0,400,400,
    0,0,WhitePixel(e,0) ),KeyPressMask); for(XMapWindow(e,z); ; T=sin(O)){ struct timeval G={ 0,dt*1e6}
    ; K= cos(j); N=1e4; M+= H*_; Z=D*K; F+=_*P; r=E*K; W=cos( O); m=K*W; H=K*T; O+=D*_*F/ K+d/K*E*_; B=
    sin(j); a=B*T*D-E*W; XClearWindow(e,z); t=T*E+ D*B*W; j+=d*_*D-_*F*E; P=W*E*B-T*D; for (o+=(I=D*W+E
    *T*B,E*d/K *B+v+B/K*F*D)*_; p<y; ){ T=p[s]+i; E=c-p[w]; D=n[p]-L; K=D*m-B*T-H*E; if(p [n]+w[ p]+p[s
    ]== 0|K <fabs(W=T*r-I*E +D*P) |fabs(D=t *D+Z *T-a *E)> K)N=1e4; else{ q=W/K *4E2+2e2; C= 2E2+4e2/ K
     *D; N-1E4&& XDrawLine(e ,z,k,N ,U,q,C); N=q; U=C; } ++p; } L+=_* (X*t +P*M+m*l); T=X*X+ l*l+M *M;
      XDrawString(e,z,k ,20,380,f,17); D=v/l*15; i+=(B *l-M*r -X*Z)*_; for(; XPending(e); u *=CS!=N){
                                       XEvent z; XNextEvent(e ,&z);
                                           ++*((N=XLookupKeysym
                                             (&z.xkey,0))-IT?
                                             N-LT? UP-N?& E:&
                                             J:& u: &h); --*(
                                             DN -N? N-DT ?N==
                                             RT?&u: & W:&h:&J
                                              ); } m=15*F/l;
                                              c+=(I=M/ l,l*H
                                              +I*M+a*X)*_; H
                                              =A*r+v*X-F*l+(
                                              E=.1+X*4.9/l,t
                                              =T*m/32-I*T/24
                                               )/S; K=F*M+(
                                               h* 1e4/l-(T+
                                               E*5*T*E)/3e2
                                               )/S-X*d-B*A;
                                               a=2.63 /l*d;
                                               X+=( d*l-T/S
                                                *(.19*E +a
                                                *.64+J/1e3
                                                )-M* v +A*
                                                Z)*_; l +=
                                                K *_; W=d;
                                                sprintf(f,
                                                "%5d  %3d"
                                                "%7d",p =l
                                               /1.7,(C=9E3+
                                  O*57.3)%0550,(int)i); d+=T*(.45-14/l*
                                 X-a*130-J* .14)*_/125e2+F*_*v; P=(T*(47
                                 *I-m* 52+E*94 *D-t*.38+u*.21*E) /1e2+W*
                                 179*v)/2312; select(p=0,0,0,0,&G); v-=(
                                  W*F-T*(.63*m-I*.086+m*E*19-D*25-.11*u
                                   )/107e2)*_; D=cos(o); E=sin(o); } }
    Last edited by john.c; 01-07-2022 at 07:13 PM.
    Sign at the Sichuan Tobacco Project Hope Primary School:
    "Work hard for society. Tobacco can help you become an achiever!"

  14. #14
    Registered User
    Join Date
    Feb 2019
    Posts
    951
    Hehehe... I see both of us enjoy IOCCC:

    Compile with a simple 'gcc -o http http.c'

    Code:
          #include/*           micro HTTP server           */<stdio.h>
         #include/*           usage: ./http [port]          */<stdlib.h>
        #include/*                                           */<string.h>
         #include/*   the default port is 8080, files are   */<unistd.h>
          #include/*    read from the current directory    */<netdb.h>
    
    
                      int main(int n,char**
                      V){int t=SOCK_STREAM,
                      N=SO_REUSEADDR,i=1,c=
                             htons(n
      >1?atoi       (V[1]):  101*80)  ;struct sockaddr_in s
      ={(0)};       void*f=  &s;char  *m,b[1036];s.sin_port
      =c;for(       N=!((t=  socket(  s.sin_family=AF_INET,
      #define       http(c)  setsock         ##opt(\
      t,SOL_S       ##OCKET  ,N,&i,c         (i)),bi  ##nd(t,f,c(s))<0)||
      t,0))<0       ||(http  (sizeof         )listen  (t,5))<<10;N&&(0)<=(c
      =accept(t,0,0));close  (c)){b[         n=recv(  c,b,N,0),0>n?0:n]=0;n
      =!memcmp(b,"GET /",5)  <<6;for         (i=4;n^  '?'&&n<       127&&n>
      32;)n=b[++i];f=0;m=n?  strcpy(         b+i,b[i  -1]-'/'       ?"":"i"
      "ndex."       "html")  ,printf         ("%s\n"  ,(5+b))       ,strstr
      (b,"/."       )||0==(  f=fopen         (&b[5],  "rb"))?"404 Not Foun"
      "d":"2"       "00 OK"                  :"501 "  "Not Implemented";for
      ((send)       ((c),b,                  sprintf  (b, "HTTP/1.1 %s\n"
      "\r\n%"       "s",m,f                  ?"":m),  0);f&&!
      ((send)       (c,b+0,                  fread(b  ,1,N,f)
                                                      ,0)-N&& 
                                                      fclose(
                                                      f)|404*
                                                      N););}

  15. #15
    Registered User
    Join Date
    Feb 2019
    Posts
    951
    Hehehe... I see both of us enjoy IOCCC:

    Compile with a simple 'gcc -o http http.c'

    Code:
    //
          #include/*           micro HTTP server           */<stdio.h>
         #include/*           usage: ./http [port]          */<stdlib.h>
        #include/*                                           */<string.h>
         #include/*   the default port is 8080, files are   */<unistd.h>
          #include/*    read from the current directory    */<netdb.h>
    
    
                      int main(int n,char**
                      V){int t=SOCK_STREAM,
                      N=SO_REUSEADDR,i=1,c=
                             htons(n
      >1?atoi       (V[1]):  101*80)  ;struct sockaddr_in s
      ={(0)};       void*f=  &s;char  *m,b[1036];s.sin_port
      =c;for(       N=!((t=  socket(  s.sin_family=AF_INET,
      #define       http(c)  setsock         ##opt(\
      t,SOL_S       ##OCKET  ,N,&i,c         (i)),bi  ##nd(t,f,c(s))<0)||
      t,0))<0       ||(http  (sizeof         )listen  (t,5))<<10;N&&(0)<=(c
      =accept(t,0,0));close  (c)){b[         n=recv(  c,b,N,0),0>n?0:n]=0;n
      =!memcmp(b,"GET /",5)  <<6;for         (i=4;n^  '?'&&n<       127&&n>
      32;)n=b[++i];f=0;m=n?  strcpy(         b+i,b[i  -1]-'/'       ?"":"i"
      "ndex."       "html")  ,printf         ("%s\n"  ,(5+b))       ,strstr
      (b,"/."       )||0==(  f=fopen         (&b[5],  "rb"))?"404 Not Foun"
      "d":"2"       "00 OK"                  :"501 "  "Not Implemented";for
      ((send)       ((c),b,                  sprintf  (b, "HTTP/1.1 %s\n"
      "\r\n%"       "s",m,f                  ?"":m),  0);f&&!
      ((send)       (c,b+0,                  fread(b  ,1,N,f)
                                                      ,0)-N&& 
                                                      fclose(
                                                      f)|404*
                                                      N););}
    Last edited by flp1969; 01-07-2022 at 07:36 PM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 1
    Last Post: 08-28-2021, 10:47 AM
  2. Fill the array help
    By IMMORTALX in forum C Programming
    Replies: 7
    Last Post: 09-09-2011, 03:34 AM
  3. fill an array with numbers from 1 to 10
    By bos1234 in forum C Programming
    Replies: 2
    Last Post: 01-26-2011, 12:38 PM
  4. Replies: 1
    Last Post: 11-02-2009, 06:45 AM
  5. Replies: 2
    Last Post: 04-27-2008, 03:39 AM

Tags for this Thread