w3resource

C++ Exercises: Display the n terms of even natural number and their sum

C++ For Loop: Exercise-21 with Solution

Write a program in C++ to display the n terms of even natural number and their sum.

Pictorial Presentation:

C++ Exercises: Display the n terms of even natural number and their sum

Sample Solution:-

C++ Code :

#include <iostream>
using namespace std;

int main()
{
    int i, n, sum = 0;

    cout << "\n\n Display n terms of even natural number and their sum:\n";
    cout << "---------------------------------------------------------\n";
    cout << " Input number of terms: ";
    cin >> n;
    cout << "\n The even numbers are: ";
    for (i = 1; i <= n; i++) 
    {
        cout << 2 * i << " ";
        sum += 2 * i ;
    }
    cout << "\n The Sum of even Natural Numbers upto " << n << " terms: " << sum << endl;
}

Sample Output:

Display n terms of even natural number and their sum:                 
---------------------------------------------------------              
 Input number of terms: 5                                              
 The even numbers are: 2 4 6 8 10                                        
 The Sum of even Natural Numbers upto 5 terms: 30  

Flowchart:

Flowchart: Display the n terms of even natural number and their sum

C++ Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a program in C++ to display the n terms of odd natural number and their sum.
Next: Write a program in C++ to display the n terms of harmonic series and their sum.

What is the difficulty level of this exercise?



Follow us on Facebook and Twitter for latest update.

C++ Programming: Tips of the Day

What is the usefulness of `enable_shared_from_this?

It enables you to get a valid shared_ptr instance to this, when all you have is this. Without it, you would have no way of getting a shared_ptr to this, unless you already had one as a member.

class Y: public enable_shared_from_this
{
public:

    shared_ptr f()
    {
        return shared_from_this();
    }
}

int main()
{
    shared_ptr p(new Y);
    shared_ptr q = p->f();
    assert(p == q);
    assert(!(p < q || q < p)); // p and q must share ownership
}

The method f() returns a valid shared_ptr, even though it had no member instance. Note that you cannot simply do this:

class Y: public enable_shared_from_this
{
public:

    shared_ptr f()
    {
        return shared_ptr(this);
    }
}

The shared pointer that this returned will have a different reference count from the "proper" one, and one of them will end up losing and holding a dangling reference when the object is deleted.

Ref : https://bit.ly/3pwVzzz