-2

I need to write sum of digits for all array elements using pointer arithmetic.

Program should print: 0 1 2 5 8 16 14

#include <stdio.h>
void sumDigit(int arr[], int n) {
  int *p = arr, m, sum;
  while (p < arr + n) {
      sum=0;
      m = (*p) % 10;
      sum += m;
      (*p) /= 10;
    p++;
     printf("%d ", sum);
  }
}
int main() {
  int arr[] = {0, 1, 2, 14, 35, 97, 68};
  int n = sizeof(arr) / sizeof(*arr);
  sumDigit(arr, n);
  return 0;
}

This code prints only last digits (0 1 2 4 5 7 8).

How to implement pointer arithmetic for this task?

  • 2
    [Include in your post](https://stackoverflow.com/posts/70992694/edit) a formatted text block that shows *exactly* what you are expecting, and *exactly* what you are getting that differs from that, for the provided example. It will *dramatically* improve the quality of your post. – WhozCraig Feb 04 '22 at 20:54
  • I have written what I need. –  Feb 04 '22 at 20:55
  • 2
    @devec Review this block `while (q < arr + n) { ... }`. Explain what `q` does. – chux - Reinstate Monica Feb 04 '22 at 20:56
  • @chux-ReinstateMonica it's double loop using pointer arithmetic –  Feb 04 '22 at 21:01
  • Yes but why are you looping over the array in the inner loop? You are supposed to check the digits of the current entry in the array in that inner loop (that is, loop over the digits not the array). The outer loop is already looping over the whole array. – kaylum Feb 04 '22 at 21:02
  • What do you think the **inner** `while (q < arr + n)` is accomplishing ? – WhozCraig Feb 04 '22 at 21:02
  • We didn't say you don't need an inner loop. Just that the loop was iterating over the wrong thing. You still need it to loop over the digits of the current number. You should probably sit down and work thru the steps on a piece of paper before proceeding to code. – kaylum Feb 04 '22 at 21:07
  • 3
    Write a function that, given *a* (singular) `int` value, produces the sum-of-digits of that value as the result. No pointers, just an input `int`, and an output `int`. Should be simple enough. Then, consider where in your current code you would use that. then ask yourself again, what is the purpose of that **inner loop** `while (q < arr + n)`. – WhozCraig Feb 04 '22 at 21:09
  • @WhozCraig How could that function accept int value of pointer? –  Feb 04 '22 at 21:30
  • The purpose of this exercise is to see if you can enumerate an array *without* using subscripting. E.g. Don't use `arr[i]`, use `*p`. The rules of this game aren't that you can't dereference addresses to get to data; they just don't want you using subscripting to do it. To answer your question, given a pointer-to-int `p` holding a valid address to some memory containing an `int` value, you would provide "that function" the integer residing at the address that pointer contains *exactly* how you think you would. : `callme(*p);`. – WhozCraig Feb 04 '22 at 21:46
  • You're zapping `sum` on each iteration of the loop. Move `sum = 0;` _above_ the loop. – Craig Estey Feb 04 '22 at 22:00
  • @CraigEstey it would print 0 1 3 7 12 19 27 –  Feb 04 '22 at 22:03
  • You're mixing `p` and `q`. You only need one. – Craig Estey Feb 04 '22 at 22:07
  • I have spent so much time in this, I'm confused, could someone post an answer that works? –  Feb 04 '22 at 22:12
  • Exchanges like these make me very angry. You have my sympathies for your frustrations, @devec, but working though this sort of thing is *how you learn*. Now that someone has written it for you, you've missed that. Yes, you can see how the provided solution works, but you've learned nothing about how to analyze a problem and come up with a solution like this (like these) for yourself. – Steve Summit Feb 04 '22 at 22:29
  • @devec Please read https://ericlippert.com/2014/03/21/find-a-simpler-problem/ . That's the approach WhozCraig was trying to get you to take in his comment an hour ago beginning with "Write a function that, given a (singular) `int` value". Breaking a problem up into smaller, separate subproblems isn't just a good technique to use when you're learning — it's a good technique for anyone to use. – Steve Summit Feb 04 '22 at 22:31
  • Code like the `sumDigit` function you started with — which is trying to iterate over the array *and* iterate over the digits of each element in the array at the same time — is *impossible*. You can't write it, we can't read it, you can't debug it, we can't figure it out — and it doesn't work, to boot. – Steve Summit Feb 04 '22 at 22:33
  • If you had first written code to sum the digits of one `int` (ignoring all the other parts of the problem), then used that code to sum the digits of the several ints in an array (ignoring the part of the problem that said you couldn't use array subscripts), then finally rejiggered it to get rid of the verboten array subscripts, I believe you could have solved this yourself. – Steve Summit Feb 04 '22 at 22:38

2 Answers2

0

Probably gone on long enough in general-chat. You're completely misunderstanding the purpose of the assignment. The purpose is to accomplish the task without using subscripting. E.g. you can't do this:

for (int i=0; i<n; ++i)
{
    // do something with arr[i]
}

Instead, they want you to do something like this:

int *p = arr;
while (p != arr+n)
{
    // do something with *p, then....

    ++p;
}

That's it. There are at least a dozen ways to do this for the task at hand; I can think of five right off the top of my head. One way is shown below:

#include <stdio.h>

void sumDigit(const int arr[], size_t n)
{
    const int *stop = arr + n;
    for (; arr != stop; ++arr)
    {
        int sum = 0;
        int value = *arr;
        while (value != 0)
        {
            sum += value % 10;
            value /= 10;
        }
        printf("%d ", sum);
    }
    fputc('\n', stdout);
}

int main()
{
    int arr[] = {0, 1, 2, 14, 35, 97, 68};
    size_t n = sizeof arr / sizeof *arr;
    sumDigit(arr, n);
    return 0;
}

Output

0 1 2 5 8 16 14 

Here's another way:

void sumDigit(const int arr[], size_t n)
{
    const int *p = arr;
    while (p != arr+n)
    {
        int sum = 0;
        int value = *p;
        while (value != 0)
        {
            sum += value % 10;
            value /= 10;
        }
        printf("%d ", sum);
        ++p;
    }
    fputc('\n', stdout);
}

And another...

void sumDigit(const int arr[], size_t n)
{
    for (const int *p = arr; p != arr+n; ++p)
    {
        int sum = 0;
        int value = *p;
        while (value != 0)
        {
            sum += value % 10;
            value /= 10;
        }
        printf("%d ", sum);
    }
    fputc('\n', stdout);
}

Here's one that, as I described in general-comment, uses a purpose-driven function to compute the sum-of-digits of a provided int value, thereby making the actual sumDigit much easier to understand:

int sum_of_digits(int value)
{
    int sum = 0;
    while (value != 0)
    {
        sum += value % 10;
        value /= 10;
    }
    return sum;
}

void sumDigit(const int arr[], size_t n)
{
    for (const int *p = arr; p != arr+n; ++p)
        printf("%d ", sum_of_digits(*p));
    fputc('\n', stdout);
}

All of these produce the same output, because they all ultimately do the same thing.

WhozCraig
  • 65,258
  • 11
  • 75
  • 141
0

The only pointer arithmetic you need is arr++. Variable val is needed to do not destroy the content of the original array. It makes no sense to return int as sum of digits cannot be negative. Also use the correct type for the sizes (size_t)

unsigned sumDigit(int arr[], size_t n) 
{
    int val;
    unsigned sum = 0, psum;
    while (n--) 
    {
        val = *arr++;
        psum = 0;
        do
        {
            psum += abs(val % 10);
            val /= 10;
        }
        while(val);
        sum += psum;
        printf("%u ", psum);
    }
    printf("\n");
    return sum;
}

int main(void)
{
    int arr[5] = {68876, -434554, 3456, 99999, -3435543};

    printf("Sum of digits of all numbers in the array = %u\n", sumDigit(arr, 5));
}

0___________
  • 60,014
  • 4
  • 34
  • 74