Write a C++ program to calculate the sum of first n natural number, where n is entered by user.
Program Code:
#include <iostream>
using namespace std;
int main()
{
int i;
int number, sum = 0;
cout << "Enter a positive integer to calculate the sum is : ";
cin >> number;
for (i = 1; i <= number; i++)
{
sum = sum + i;
}
cout << " Sum of first n natural number = " ;
cout<< sum;
return 0;
}
The program output is tested on www.jdoodle.com
Output:
Enter a positive integer to calculate the sum is : 7
Sum of first n natural number = 28
Thanks
Mukesh Rajput
Program Code:
#include <iostream>
using namespace std;
int main()
{
int i;
int number, sum = 0;
cout << "Enter a positive integer to calculate the sum is : ";
cin >> number;
for (i = 1; i <= number; i++)
{
sum = sum + i;
}
cout << " Sum of first n natural number = " ;
cout<< sum;
return 0;
}
The program output is tested on www.jdoodle.com
Output:
Enter a positive integer to calculate the sum is : 7
Sum of first n natural number = 28
Thanks
Mukesh Rajput
Post A Comment:
0 comments: