C++ program to add N natural numbers using class

Given a number, we have to add N natural numbers using the class and object approach.
Submitted by Shubh Pachori, on August 04, 2022

Example:

Input: 
Enter Number: 5

Output:
Sum of first 5 Natural Number is 15

C++ Code to add n natural numbers using class and object approach

#include <iostream>
using namespace std;

// create a class
class SumNaturalNumber {
  // private data members
 private:
  int number;

  // public function with a int type parameter
 public:
  void sumnatural(int n) {
    // copying value of parameter in data member
    number = n;

    // two int type variable for indexing and sum
    int index, sum = 0;

    // for loop to get sum of n Natural Numbers
    for (index = 1; index <= number; index++) {
      // index is getting added in sum one by one
      sum += index;
    }

    // printing sum of n Natural numbers
    cout << "Sum of first " << number << " Natural Number is " << sum << endl;
  }
};

int main() {
  // create a object
  SumNaturalNumber S;

  // a int type variable to store number
  int n;

  cout << "Enter Number: ";
  cin >> n;

  // calling function using object
  S.sumnatural(n);

  return 0;
}

Output

RUN 1:
Enter Number: 5
Sum of first 5 Natural Number is 15

RUN 2:
Enter Number: 25
Sum of first 25 Natural Number is 325

RUN 3:
Enter Number: 3
Sum of first 3 Natural Number is 6

Explanation:

In the above code, we have created a class SumNaturalNumber, one int type data member number to store the number, and a public member function sumnatural() to add the given natural numbers.

In the main() function, we are creating an object S of class SumNaturalNumber, reading an integer number by the user, and finally calling the sumnatural() member function to add the given natural numbers. The sumnatural() function contains the logic to add the given natural 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.