Accessing one dimensional array elements using the pointer

Program 53) Write a program using pointers to compute the sum of all elements stored in an array.

This program shows illustrates how a pointer can be used to traverse an array element. Since incrementing an array pointer causes it to point to the next element, we need only to add one to p each time we go through the loop.

                                     PROGRAM

main ( )
 {
      int *p, sum, i ;
      int x[5] = {5, 9, 6, 3, 7} ;
      i = 0 ;
     p = x ;    /*    Initializing with base address of     */
     printf ("Element value address\n\n) ;
     while (i < 5)
     {
          printf (" x[%d] %d %u\n", i, *p, p) ;
          sum = sum + *p ;    /*  accessing array element   */
          i++, p++ ;                /*   incrementing pointer   */
     }
     printf ("\n   Sum   =   %d\n",  sum) ;
     printf ("\n   &x [10]   =   %u\n",  &x [10]) ;

     printf ("\n  p   =   %u\n",   p) ;
 }

Output:              Element               Value           Address
                          x [0]                      5                     166
                          x [1]                      9                     168
                          x [2]                      6                     170
                          x [3]                      3                     172
                          x [4]                      7                     174
                         Sum    =    55
                         &x [0]  =    166
                         p         =    176

No comments:

Post a Comment