简体   繁体   中英

Sum of digits of each elements inside an array of integers

I want to calculate the sum of digits in each elements in array. The problem is with this code it only calculates the the sum of odd indexes (1,3,5...) in array. And in console it shows some random numbers for even indexes (0,2,4...)

Can anybody tell me what is the problem?

And yes I need to use it as array

Here are output values:

Enter how many numbers you want to calculate sum of digits: 5
Enter those numbers: 12
Enter those numbers: 33
Enter those numbers: 44
Enter those numbers: 22
Enter those numbers: 33
Sum of 0 number is: 4
Sum of 1 number is: 6
Sum of 2 number is: 40
Sum of 3 number is: 4
Sum of 4 number is: 11730950
#include <iostream>


int main(int argc, char** argv) 
{
    int n;
    int temp;
    int pom;

    cout << "Enter how many numbers you want to calculate sum of digits: ";
    cin >> n;

    int numbers[n];
    int sum[n];

    for (int i = 0; i < n; i++)
    {
        cout << "Enter those numbers: ";
        cin >> numbers[i];
    }

    for (int i = 0; i < n; i++)
    {
        while (numbers[i] > 0)
        {
        temp = numbers[i] % 10;
        sum[i]+= temp;
        numbers[i] = numbers[i]/10; 
        }

    }



    for (int i = 0; i < n; i++)
    {
        cout << "Sum of " << i << " number is: " << sum[i] << endl;
    }

    return 0;
}

You need to initialize the sum array, like this:

int sum[n] {};

otherwise, the first time you read from an element of sum you have undefined behaviour.

Also, variable length arrays are not part of standard c++. If you don't know the size of the array at compile time, just use a std::vector .

If you absolutely must use an array, then you will need to dynamically allocate it, like this:

int * arr = new int[n]{};
#include <iostream>
using namespace std;
int main() {
    int a,temp,sum=0;
    cin>>a;
    int arr[a];
    for(int i=0;i<a;i++)
    {
        cin>>arr[i];
    }
    for(int i=0;i<a;i++)
    {
        sum=0;
        while(arr[i]>0)
        {
            temp=arr[i]%10;
            sum+=temp;
            arr[i]=arr[i]/10;
        }
        cout<<sum<<" ";
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM