Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Program to find sum of first n natural numbers in C++
In this tutorial, we will be discussing a program to find sum of first n natural numbers.
For this we will be provided with an integer n. Our task is to add up, find the sum of the first n natural numbers and print it out.
Example
#include<iostream>
using namespace std;
//returning sum of first n natural numbers
int findSum(int n) {
int sum = 0;
for (int x=1; x<=n; x++)
sum = sum + x;
return sum;
}
int main() {
int n = 5;
cout << findSum(n);
return 0;
}
Output
15
Advertisements
