C++ Exercises: Display the n terms of even natural number and their sum
C++ For Loop: Exercise-21 with Solution
Write a C++ program that displays the sum of the n terms of even natural numbers.
Visual Presentation:
Sample Solution:-
C++ Code :
#include <iostream> // Including input-output stream header
using namespace std; // Using standard namespace to avoid writing std::
int main() // Start of the main function
{
int i, n, sum = 0; // Declaration of integer variables 'i' (loop counter), 'n' (user input for the number of terms), 'sum' (sum of even natural numbers)
cout << "\n\n Display n terms of even natural number and their sum:\n"; // Display message on the console
cout << "---------------------------------------------------------\n";
cout << " Input number of terms: "; // Prompt the user to input the number of terms
cin >> n; // Read the input value as the number of terms
cout << "\n The even numbers are: "; // Display message indicating the list of even numbers
for (i = 1; i <= n; i++) // Loop for 'n' terms
{
cout << 2 * i << " "; // Print the even numbers by formula 2 * 'i'
sum += 2 * i; // Add the even number to the sum variable
}
cout << "\n The Sum of even Natural Numbers up to " << n << " terms: " << sum << endl; // Display the sum of even numbers up to 'n' terms
}
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:
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?
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/cpp-exercises/for-loop/cpp-for-loop-exercise-21.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics