Answer to Question #174174 in C++ for Harini.M

Question #174174

mplement a C++ program to overload the function named as sum, to perform sum of digits of integer and perform sum of digits of float number respectively


1
Expert's answer
2021-03-24T13:22:17-0400

#include <iostream>

#include <cmath>

 

using namespace std;

 

// function with int type parameter

int sum(int n) {

   int res= 0;

 // Handle negative number

  if (n < 0)

      n = -n;

      

   while (n != 0)  {

       res = res + n%10;

       n = n/10;

   }

   return res;

}

// function with double type parameter

int sum(double n) {

    int res = 0;

   // Handle negative number

    if (n < 0)

       n = -n;

 

    while (n != trunc(n)) {

       n *= 10;

 }

 

   while (int(n) != 0) {

       res = res + int(n)%10;

       n = int(n)/10;

   }

   return res;

}

int main()

{

   int intN = 1234;

   double doubleN = 12.34;

 

   cout << intN <<": sum of digits "<< sum(intN) <<endl;

   cout << doubleN << ": sum of digits " << sum(doubleN )<<endl;

   return 0;

}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS