Question

Using C++ write a function AllSame(a,n) that returns 1 if all components of the positive integer...

Using C++ write a function AllSame(a,n) that returns 1 if all components of the positive integer array a[0 .. n-1] have the same sums of digits; otherwise it returns 0. E.g. the array a [ ] = {17, 242, 62, 35, 431, 8} has the same sums of digits and AllSame(a, 5) returns 1.

0 0
Add a comment Improve this question Transcribed image text
Answer #1
#include <iostream>

using namespace std;

// sumDigits function takes n as input and returns the sum of digits in n
int sumDigits(int n){
   if(n > 0){
      return (n%10) + sumDigits(n/10);
   }
   else{
      return 0;
   }
}
 
// Function AllSame returns 1 if all components of the positive integer array a[0 .. n-1]
// returns 0 otherwise
int AllSame(int a[], int n){
   int sum = sumDigits(a[0]);
   for(int i=1;i<n;i++){
      if(sumDigits(a[i])!=sum){
         return 0;
      }
   }  
   return 1;
}

int main(){
   int a [ ] = {17, 242, 62, 35, 431, 8};
   cout<<AllSame(a, 5)<<endl;
   return 0;
}

1

Add a comment
Know the answer?
Add Answer to:
Using C++ write a function AllSame(a,n) that returns 1 if all components of the positive integer...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT