Sum of natural numbers up to a value given by the user. – CSKC
Sign In

Search

Solved Problem #CPP#2005    siteicon   siteicon  

Problem Statement - Sum of natural numbers up to a value given by the user.

Write a c++ program to collect a positive integer value from the user and print the list of all natural numbers up to that number. Also print the sum of the natural number printed.

Solution

TC++ #2005

 

×

Ask AI About This Code

Default Prompt that is passed along with the code is given below, You can write your own prompt if you so desire.



×

Test CPP

int n;
The positive integer to be collected by user is declared here.

long sum=0;
Here we declare sum as a long integer as adding many integers can generate a really long value. In fact even long may not be sufficient, but we assume that user enters a reasonable input value which not to big.

cout<<“Give a positive integer :”; cin>>n;
Here we collect the user input.

for(int i=1;i<=n;i++) { cout<<i<<” “; sum=sum+i;}
This loop starts from 1 as natural numbers begin with 1 and it ends at the value of n given by the user. the cout line prints the number with a space following it as given by the ” ” (space) string literal. Then it keeps adding the number to previously calculated sum.

cout<<endl<<“Sum of above numbers = “<<sum<<endl;
Here we print the final sum after all the numbers have been added into the variable sum.

Notes

  • The input value of the user has to be assumed to be of reasonable size, else even the long declaration for sum would be small. The long long type declaration may have to be used. Also such program may take a very long time to run when large value inputs are given. Computer speed may also be a consideration for running such programs with large input values.


Share

Created: 29-Dec-2017 00:06 | Updated: 13-Dec-2018 23:41|