Using while loop to calculate 1+2+...+n | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Using while loop to calculate 1+2+...+n

I write programm but only show input Sum is 0

29th Oct 2020, 6:43 PM
Jo'shqinbek Bekniyozov
Jo'shqinbek Bekniyozov - avatar
2 Answers
+ 2
Jo'shqinbek Bekniyozov If u r looking for a program to add n natural numbers then here is the solution: #include <iostream> using namespace std; int main() { int n; int sum=0; cin>>n; //no of natural number while(n) {sum+=n; n--; } cout<<sum; return 0; } Sample input:5 Output:15
30th Oct 2020, 3:24 AM
~प्रिया
~प्रिया - avatar
0
int n = 5; int sum = 0; for(int i = 0; i < n; i++){ sum += i; } I think this is what you are looking for. It would be nice if you can show us your code so people can help you find your errors.
29th Oct 2020, 7:00 PM
Apollo-Roboto
Apollo-Roboto - avatar