简体   繁体   中英

Add the digits of each element in an multidimensional array

I have a 2 dimensional array. I'm trying to add the digits of each element in the array and find the sum.

For example :

consider my array is: a[2][2] = { {15,11}, {13,21} } .

Now for the element 15 i need to add 1+5 and the result 6 placed in the same position. and for element 11 1+1 and place the result 2 in the same position. And the same for all other elements.

Following is my code.

int main ()
{

   int a[3][2] = { {19,11}, {13,21}, {12,14}};
   int i, j;
   int digit1,digit2,sum1=0,sum2=0,rem1,rem2;

   for ( i = 0; i < 3; i++ )
   {

      for ( j = 0; j < 2; j++ )
      {
         digit1 = a[i];
         rem1 = digit1%10;
         sum1 = sum1 + rem1;
         digit1 = digit1/10;

         digit2 = a[j];
         rem2 = digit2%10;
         sum2 = sum2 + rem2;
         digit2 = digit2/10;

         printf("\nthe sum of i: ", sum1);
        printf("\nthe sum of j: ", sum2);

      }


   }
   return 0;
}

But from above code I'm not getting the sum.

I am kinda new to this and got stuck here. Here's the code in EDITOR .

Define a function to compute the sum of the digits of an integer.

int getSumOfDigits(int n)
{
   int ret = 0;
   while ( n > 0 )
   {
      ret += (n%10);
      n /= 10;
   }
   return ret;
}

Use the function in the for loop.

for ( i = 0; i < 3; i++ )
{
   for ( j = 0; j < 2; j++ )
   {
      a[i][j] = getSumOfDigits(a[i][j]);
   }
}

Its simple. Do the following -

//Assuming the array is a[3][2]

for(int i=0;i<3;i++)
for(int j=0;j<2;j++)
{
  int sum = 0;
  while(a[i][j])
  {
   sum+=a[i][j]%10;
   a[i][j]/=10;
  }
   a[i][j]=sum;
}

Inside for loop put this code instead of your code it will work

 for ( j = 0; j < 2; j++ )
  {
     sum1=0;
     while(a[i][j]){
     sum1=sum1+(a[i][j]%10);
     a[i][j]=a[i][j]/10;
     }
     a[i][j]=sum1;

     printf("\nthe sum of [%d][%d]: %d", i,j,sum1);
}

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