Programs

C++ Program to Calculate Sum of Natural Numbers

C++ Program to Calculate Sum of Natural Numbers

Here’s a Turbo C++ program to calculate the sum of natural numbers up to a given number:

#include <iostream.h>
#include <conio.h>

void main() {
    clrscr();  // Clear the screen (specific to Turbo C++)

    int n, sum = 0;

    cout << "Enter a natural number: ";
    cin >> n;

    // Check if the number is a natural number
    if (n <= 0) {
        cout << "Please enter a natural number." << endl;
    } else {
        // Calculate the sum
        for (int i = 1; i <= n; ++i) {
            sum += i;
        }
        cout << "The sum of the first " << n << " natural numbers is: " << sum << endl;
    }

    getch();  // Wait for user input (specific to Turbo C++)
}

To compile and run this program in Turbo C++:

  1. Open Turbo C++.
  2. Create a new file and copy-paste the above code into it.
  3. Save the file.
  4. Compile the code (usually by pressing Alt + F9).
  5. Run the program (usually by pressing Ctrl + F9).

The program will prompt you to enter a natural number and then it will display the sum of all natural numbers up to that number. If the entered number is not a natural number, it will prompt you to enter a natural number.