C++ program to find the sum of digits of numbers between numbers using class

Given numbers, we have to find the sum of digits of numbers between numbers using the class and object approach.
Submitted by Shubh Pachori, on September 01, 2022

Example:

Input:
Enter Numbers: 22 25

Output:
Sum of Digits:22
(2+2+2+3+2+4+2+5 = 22)

C++ code to find the sum of digits of numbers between numbers using the class and object approach

#include <iostream>
using namespace std;

// create a class
class SumDigit {
  // declare private data members
 private:
  int start, end;

  // public functions
 public:
  // getNumbers() function to insert numbers
  void getNumbers() {
    cout << "Enter Numbers:";
    cin >> start >> end;
  }

  // sumDigit() function to add digits of
  // numbers in between the numbers
  int sumDigit() {
    // initializing int type variables to
    // performing operations
    int index, temp, sum = 0;

    // for loop to add every digit one by one
    // between the numbers
    for (index = start; index <= end; index++) {
      // copying number in the temporary variable
      temp = index;

      // while loop to gain digits one by one
      while (temp > 0) {
        // adding digits in sum
        sum = sum + temp % 10;

        // dividing temp by 10 at every iteration
        temp = temp / 10;
      }
    }

    // returning sum
    return sum;
  }
};

int main() {
  // create an object
  SumDigit S;

  // int type variable to store the sum
  int sum;

  // calling getNumbers() function to insert numbers
  S.getNumbers();

  // sumDigit() function to add digits of
  // numbers between in numbers
  sum = S.sumDigit();

  cout << "Sum of Digits : " << sum;

  return 0;
}

Output:

RUN 1:
Enter Numbers:19 25
Sum of Digits : 37

RUN 2:
Enter Numbers:1 100
Sum of Digits : 901

Explanation:

In the above code, we have created a class SumDigit, two int type data members start and end to store the start and end of the numbers, and public member functions getNumbers() and sumDigit() to store and to add digits of numbers in between that given numbers.

In the main() function, we are creating an object S of class SumDigit, reading a numbers by the user using getNumbers() function, and finally calling the sumDigit() member function to add digits of numbers in the given numbers. The sumDigit() function contains the logic to add digits of numbers in the given numbers and printing the result.

C++ Class and Object Programs (Set 2) »




Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.