Thread: Compute sum of the array elements using pointers

  1. #1
    Registered User
    Join Date
    May 2016
    Posts
    7

    Compute sum of the array elements using pointers

    The stated problem is "compute sum of the array elements using pointers."

    The website solution looks like this:

    Code:
    #include<stdio.h>
    #include<conio.h>
    
    void main(){
    
    int numArray[10];
    int i, sum = 0;
    int *ptr;
     
    printf("\nEnter 10 elements : ");
     
    for (i = 0;i < 10;i++)
    scanf("%d", &numArray[i]);
     
    ptr = numArray;/* a=&a[0] */
     
    for (i = 0;i < 10;i++){
    sum = sum + *ptr;
    ptr++;
    }
     
    printf("The sum of array elements : %d",sum);
    }
    So instead of
    sum += numArray[i]
    you have
    sum += *ptr;

    Ok I get this. Can this also be solved using arrays passed through a function? I.E.

    Code:
    #include <stdio.h>
    
    void arrayFunc(int myArray...etc); //prototype a function with array and any other variables needed in function
    
    int main() {
    
    int myArray[5]
    int sum = 0;
    int i;
    
    
    for (i = 0; i < 5; i++){
    printf("Please enter number %d: ", i+1);
    scanf("%d", &myArray[i]);
    }
    
    for (i = 0; i < 5; i++)
    arrayFunc(myArray[i],....)
    
    return 0;
    }
    
    void arrayFunc(int myArray, etc..) //other variables may be pointers? i.e. int *sum or something along those lines
    
    //somewhere in here do the sum += myArray[i] using pointers to fill-in-the-blank values

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,661
    > The website solution looks like this:
    Which website - not this website surely?

    Using conio.h and void main are big red flags to look elsewhere, because the author is stuck in the 1980's.

    > void arrayFunc(int myArray...etc); //prototype a function with array and any other variables needed in function
    Any standard text would have described how to pass an array to a function.
    Look at how you might use say strcat() - it receives arrays of chars.
    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 rstanley's Avatar
    Join Date
    Jun 2014
    Location
    New York, NY
    Posts
    1,111
    Instead of:
    Code:
    void arrayFunc(int myArray, etc..) //other variables may be pointers? i.e. int *sum or something along those lines
    You need to pass the array name as a pointer to an int, and the dimension of the array. You also should not use "Magic Numbers" in your code.

    The function should be defined as:
    Code:
    void arrayFunc(int *arrayPtr, int dim)
    {
        // ...
    }
    And call the function as:
    Code:
    #define DIM 5
    // ...
    arrayFunc(myArray, DIM);
    The name of the array is the address (Pointer) of the first element of the array.

    I leave the rest of the code to you. You have everything you need.

    If your instructor / book / YouTube video where you learned C did not provide you with this information, then you need a new teaching source!

  4. #4
    Registered User
    Join Date
    May 2016
    Posts
    7
    Quote Originally Posted by rstanley View Post
    Instead of:
    Code:
    void arrayFunc(int myArray, etc..) //other variables may be pointers? i.e. int *sum or something along those lines
    You need to pass the array name as a pointer to an int, and the dimension of the array. You also should not use "Magic Numbers" in your code.

    The function should be defined as:
    Code:
    void arrayFunc(int *arrayPtr, int dim)
    {
        // ...
    }
    And call the function as:
    Code:
    #define DIM 5
    // ...
    arrayFunc(myArray, DIM);
    The name of the array is the address (Pointer) of the first element of the array.

    I leave the rest of the code to you. You have everything you need.

    If your instructor / book / YouTube video where you learned C did not provide you with this information, then you need a new teaching source!
    Thanks for this.

    I came up with two versions, messing around with stuff.

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #define SIZE 5;
    
    void arrayFunc(int arr[], int *sum, int i);
    
    int main()
    {
       int myArray[SIZE];
       int sum = 0;
       int i;
    
    for (i = 0; i < SIZE; i++)
    {
       printf("Please enter #%d: ", i+1);
       scanf("%d'", &myArray[i]);
    }
    
    for (i = 0; i < SIZE; i++)
         arrayFunc(myArray, &sum, i);
    printf("%d", sum);
    
    return 0;
    }
    
    void arrayFunc(int arr[], int *sum, int i)
    {
       *sum += arr[i];
    }
    And keeping in mind your example of intializing as a pointer in the function..

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #define SIZE 5;
    
    void arrayFunc(int *arr, int *sum, int i);
    
    int main()
    {
       int myArray[SIZE];
       int sum = 0;
       int i;
    
    for (i = 0; i < SIZE; i++)
    {
       printf("Please enter #%d: ", i+1);
       scanf("%d'", &myArray[i]);
    }
    
    for (i = 0; i < SIZE; i++)
       arrayFunc(myArray, &sum, i);
    printf("%d", sum);
    
    return 0;
    }
    
    void arrayFunc(int *arr, int *sum, int i)
    { 
       *sum += *(arr+i);
    }
    I haven't tried putting the dimensions of the array in the actual function but I will try that too

  5. #5
    Registered User rstanley's Avatar
    Join Date
    Jun 2014
    Location
    New York, NY
    Posts
    1,111
    Code:
    void arrayFunc(int arr[], int *sum, int i)
    {
       *sum += arr[i];
    }
    Why do you call this function i number of times? Wouldn't it be more efficient to put the loop in this function, rather than in main()?

    Pass i as the NUMBER of the elements of the array, NOT as a single index of ONE element!

    I would also return the sum rather than pass a pointer to the sum.
    Code:
    int arrayFunc(int arr[], int i)
    { 
        int sum = 0;
        // ...
        return sum;
    }

  6. #6
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Incidentally, going back to the original formulation of the problem, the solution that you were presented boils down to:
    Code:
    ptr = numArray;
    for (i = 0; i < 10; i++) {
        sum = sum + *ptr;
        ptr++;
    }
    Here the loop index i functions purely as a counter to get the loop to loop as many times as there are elements in the array. This is fine, but then it would have been simpler to write:
    Code:
    for (i = 0; i < 10; i++) {
        sum = sum + numArray[i];
    }
    But of course this then fails the "using pointers" part of the challenge. Rather, I suggest that you make use of the pointers when iterating, e.g.,
    Code:
    for (ptr = numArray; ptr < numArray + 10; ptr++) {
        sum += *ptr;
    }
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  7. #7
    Registered User
    Join Date
    May 2016
    Posts
    7
    [QUOTE=rstanley;1255826]
    Code:
    void arrayFunc(int arr[], int *sum, int i)
    {
       *sum += arr[i];
    }
    Why do you call this function i number of times? Wouldn't it be more efficient to put the loop in this function, rather than in main()?

    Pass i as the NUMBER of the elements of the array, NOT as a single index of ONE element!


    You mean instead of:
    Code:
    for (i = 0; i < SIZE; i++)
    {
       printf("Please enter #%d: ", i+1);
       scanf("%d'", &myArray[i]);
    }
     
    for (i = 0; i < SIZE; i++)
       arrayFunc(myArray, &sum, i);
    printf("%d", sum);
     
    return 0;
    }
     
    void arrayFunc(int *arr, int *sum, int i)
    { 
       *sum += *(arr+i);
    }

    do something like this(treating the pointers as arbitrary and focusing the proper usage of i)...

    Code:
    for (i = 0; i < SIZE; i++)
    {
       printf("Please enter #%d: ", i+1);
       scanf("%d'", &myArray[i]);
    }
     
       arrayFunc(myArray, &sum);
       printf("%d", sum);
     
    return 0;
    }
     
    void arrayFunc(int *arr, int *sum)
    { 
       int i; 
       for (i = 0; i < SIZE; i++)
         *sum += *(arr+i);
    }
    ...?

    also, thanks laserlight for your post.
    Last edited by DustBin; 05-25-2016 at 12:58 PM.

  8. #8
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Maybe it would be helpful to see an example:
    Code:
    #include <stdio.h>
    
    void printNumbers(const int *numbers, int n);
    
    int main(void)
    {
        int xs[] = {1, 2, 3, 4, 5};
        int xs_n = 5;
    
        int ys[10] = {7, 8, 9};
        int ys_n = 3;
    
        printNumbers(xs, xs_n);
        printf("\n");
    
        printNumbers(ys, ys_n);
        printf("\n");
    
        return 0;
    }
    
    void printNumbers(const int *numbers, int n)
    {
        const int *p;
        for (p = numbers; p < numbers + n; p++)
        {
            printf("%d ", *p);
        }
    }
    In the above, I am printing numbers, not computing their sum, but the general principles remain. Notice that because I use the parameter n in the loop for printNumbers, printNumbers can be used for both xs and ys, even though they are of different sizes. Not only are they of different sizes, but not all the elements of ys are in use.

    Notice that the loop index, or in my case the pointer used to iterate over the array, is not a parameter: it doesn't need to be because it is implementation detail. The caller basically is saying "print these numbers" and passes a pointer to the first element of the array along with the number of elements to print.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  9. #9
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,612
    You mean instead of: ...
    do something like this(treating the pointers as arbitrary and focusing the proper usage of i)...
    No, I think he meant what he said, use i (or pick a better name than i) to mean the number of elements. He gave a partial implementation as an example in his post.

    Incidentally, I encourage playing around with things. Here's an alternate implementation that will let you add up any part of an array, or a whole one. It also uses pointers.
    Code:
    int SumOfSubArray(int *arr, size_t first, size_t last)
    {
       int sum = 0;
       int *it;
       int *end;
       /* sum [first .. last] inclusive */
       for (it = arr + first, end = arr + last + 1; it < end; it++) {
          sum += *it;
       }
       return sum;
    }
    
    int SumOfArray(int *arr, size_t n)
    {
       return SumOfSubArray(arr, 0, n - 1);
    }

  10. #10
    Registered User
    Join Date
    May 2016
    Posts
    7
    Quote Originally Posted by whiteflags View Post
    No, I think he meant what he said, use i (or pick a better name than i) to mean the number of elements. He gave a partial implementation as an example in his post.

    Incidentally, I encourage playing around with things. Here's an alternate implementation that will let you add up any part of an array, or a whole one. It also uses pointers.
    Code:
    int SumOfSubArray(int *arr, size_t first, size_t last)
    {
       int sum = 0;
       int *it;
       int *end;
       /* sum [first .. last] inclusive */
       for (it = arr + first, end = arr + last + 1; it < end; it++) {
          sum += *it;
       }
       return sum;
    }
    
    int SumOfArray(int *arr, size_t n)
    {
       return SumOfSubArray(arr, 0, n - 1);
    }
    ok great. Thank you and everyone else for the input =)

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 3
    Last Post: 04-19-2016, 01:24 AM
  2. Pointers and printing distinct elements in array
    By dave_the_bear10 in forum C Programming
    Replies: 2
    Last Post: 10-29-2011, 01:31 AM
  3. Accessing elements in an array of pointers to arrays
    By fxtdr79 in forum C Programming
    Replies: 5
    Last Post: 06-05-2010, 09:29 PM
  4. printing elements of an array using pointers
    By zeebo17 in forum C Programming
    Replies: 3
    Last Post: 05-22-2009, 09:30 PM
  5. Replies: 3
    Last Post: 10-14-2001, 01:13 PM

Tags for this Thread