4

C++ Program to Find Sum of First 'N' Natural Numbers

 1 year ago
source link: https://www.geeksforgeeks.org/videos/c-program-to-find-sum-of-natural-numbers/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

C++ Program to Find Sum of First 'N' Natural Numbers

C++ Program to Find Sum of First 'N' Natural Numbers
  • 10 Views
  • 22/06/2022

In this video, we will see a C++ program for the sum of first n natural numbers.

Examples:

1. Input : n = 7 Output : 28

Explanation : Note that: 1 + 2 + 3 + 4 + 5 + 6 + 7= 28

2.Input : 8 Output : 36

Explanation : Note that: 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 = 36

In this video, we see two different approaches for the Sum of first n natural numbers in C++: 1. By using for loop 2. Using Mathematical formula: I.e [ Sum of first n natural numbers = (n*(n+1))/2]

Apart from that, we will see the Time and Space complexity of both the approaches as follows:

- Using For loop: Time Complexity O(n) Space complexity O(1)

- Using Mathematical formula: Time Complexity O(1) Space complexity O(1)

Find if the given number is the sum of the first n natural numbers: https://www.geeksforgeeks.org/find-given-number-sum-first-n-natural-numbers/ Program to find sum of first n natural numbers: https://www.geeksforgeeks.org/program-find-sum-first-n-natural-numbers/


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK