Sum of Natural Numbers in C++
Program Description- In this program, a class Sum is declared. Which has two public variables n and i and a public function sum_of_n() which takes an integer argument( user should provide a natural number) and returns sum of natural numbers. Moreover, in main() function an object s1 of type Sum is declared which access the function sum_of_n() and gives the result.
#include<iostream>
using namespace std;
class Sum
{
public:
int n;
int i;
public:
int sum_of_n(int);
};
int Sum:: sum_of_n(int n)
{
int sum=0;
for(i=1; i<=n; i++)
{
sum= sum + i;
}
return sum;
}
int main()
{
Sum s1;
int sumval1, n;
cout<< “Enter the value of nt”;
cin>>n;
sumval1= s1.sum_of_n(n);
cout<< sumval1;
return 0;
}
____________________
For output see the video