Friday, September 2, 2011

Sum of Natural Numbers up to 'n'

Adding consecutive natural numbers up to a number specified by user at run time is as easy as adding numbers to a known number. Here is the code to show you how its done:

Problem: Find sum of numbers up to 'n'. Where 'n' is entered by the user.

1. Prompt for the number (say n).
2. Write a for loop in which set first condition to 0 and second to n.
3. Add n to another variable (say j) which was initially set to 0.
4. Print the sum(which is j) when out of for loop.

Source Code:
using namespace::std;
int main (void)
int n;
int j;
cout<<"Enter the number: ";
for(int i=1; i<=n; i++)
cout<<"Sum of natural numbers from 0 to "<<n<<" is: "<<j<<endl;
return 0;

You can modify the program according to your need; product of natural numbers, sum of squares of natural numbers etc.

0 response(s):

Respond to this Post

Your participation is appriciated...