w3resource

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

C++ For Loop: Exercise-20 with Solution

Write a C++ program that displays the sum of n odd natural numbers.

Visual Presentation:

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

Sample Solution:-

C++ Code :

#include <iostream> // Include 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 odd natural numbers)

    cout << "\n\n Display n terms of odd 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 << " The odd numbers are: "; // Display message indicating the list of odd numbers

    for (i = 1; i <= n; i++) // Loop for 'n' terms
    {
        cout << 2 * i - 1 << " "; // Print the odd numbers by formula 2 * 'i' - 1
        sum += 2 * i - 1; // Add the odd number to the sum variable
    }

    cout << "\n The Sum of odd Natural Numbers up to " << n << " terms: " << sum << endl; // Display the sum of odd numbers up to 'n' terms
}

Sample Output:

Display n terms of odd natural number and their sum:                  
---------------------------------------------------------              
 Input number of terms: 5                                              
 The odd numbers are: 1 3 5 7 9 

Flowchart:

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

C++ Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a program in C++ to display the multiplication table vertically from 1 to n.
Next: Write a program in C++ to display the n terms of even natural number and their sum.

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