w3resource

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

C++ For Loop: Exercise-3 with Solution

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

Visual Presentation:

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

Sample Solution :-

C++ Code :

#include <iostream> // Preprocessor directive to include the input/output stream header file

using namespace std; // Using the standard namespace to avoid writing std::

int main() // Start of the main function
{
    int n, i, sum = 0; // Declare integer variables 'n', 'i', and 'sum' and initialize 'sum' to 0

    cout << "\n\n Display n terms of natural number and their sum:\n"; // Display a message indicating the purpose
    cout << "---------------------------------------\n"; // Display a separator line
	cout << " Input a number of terms: "; // Prompt the user to input the number of terms
	cin >> n; // Read the user input for the number of terms		
    cout << " The natural numbers up to the " << n << "th term are: \n"; // Display a message indicating the list of natural numbers up to 'n'

    // Loop to print the natural numbers up to 'n' and calculate their sum
    for (i = 1; i <= n; i++) 
    {
        cout << i << " "; // Output each natural number followed by a space
		sum = sum + i; // Calculate the sum by adding the current number 'i' to 'sum'
    }

    cout << "\n The sum of the natural numbers is: " << sum << endl; // Display the sum of the natural numbers
}

Sample Output:

 Display n terms of natural number and their sum:                      
---------------------------------------                                
 Input a number of terms: 7                                            
 The natural numbers upto 7th terms are:                               
1 2 3 4 5 6 7                                                          
 The sum of the natural numbers is: 28

Flowchart:

Flowchart: Display n terms of natural number and their sum

C++ Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a program in C++ to find the sum of first 10 natural numbers.
Next: Write a program in C++ to find the perfect numbers between 1 and 500.

What is the difficulty level of this exercise?



Become a Patron!

Follow us on Facebook and Twitter for latest update.

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://www.w3resource.com/cpp-exercises/for-loop/cpp-for-loop-exercise-3.php