0

int main() { int n=100; cin >> n; int sum=0; for (int n=1; n<=100; n++){ sum+=n; } cout<<sum; }

Can someone debugg above code to add numbers. I.e number 5 output is 15 I.e 1+2+3+4+5=15

31st Dec 2022, 1:30 PM
Alex Boso Nzaphila
Alex Boso Nzaphila - avatar
8 Respostas
+ 2
For an AP - Arithmetic Progression, the sum of the first N items is: n × (n + 1)/2 eg) (5 × 6) / 2 = 15. This is a SHORTCUT FORMULA for Arithmetic Progression.
2nd Jan 2023, 12:46 PM
Sanjay Kamath
Sanjay Kamath - avatar
+ 1
The best way is you save the code on Sololearns playground and link here with your question. Otherwise the people here have to manual enter this in the editor.
31st Dec 2022, 1:39 PM
JaScript
JaScript - avatar
+ 1
You declared n and assigned 100. Again taking input into n so now n value input. Next in loop, int n = 1; which hides n=>input value. So loop finds sum of 1 to 100., which wastages input value. Instead do take, input into a different variable say limit. Like int limit; cin >> limit; Now use this in condition as n<=limit;
31st Dec 2022, 2:13 PM
Jayakrishna 🇮🇳
0
If u add from 1 to 100, the total should be 5050..I.e 1+2+3+4+5+6........... like that
31st Dec 2022, 1:44 PM
Alex Boso Nzaphila
Alex Boso Nzaphila - avatar
0
int main(){ int i, n, sum=0; cin>>n; for(i=1; i<=n;i++){ sum+=n; } cout<<sum; return 0; }
2nd Jan 2023, 10:00 AM
Sachin Pal
Sachin Pal - avatar
0
You have used the variable n twice , once in the start and once in the for loop, the code can only work with one, and it uses the one in the for loop, so your first 2 lines go to waste, rename the variable and use it in the for loop like this : int n= 1; n <= your_variable; n++ so it goes until the number you used as input
2nd Jan 2023, 12:38 PM
MARIOS MANOUSAKIS
MARIOS MANOUSAKIS - avatar
0
#include <bits/stdc++.h> int main() { int n{}; std::cin>>n; std::valarray<int> x(n); std::iota(std::begin(x), std::end(x), 1); std::cout<<x.sum()<<"\n"; return 0; } //but so will simple.. //std::cout<<n*(n+1)/2<<"\n";
2nd Jan 2023, 8:48 PM
Smith Welder
Smith Welder - avatar
- 2
Just type the error I have made, no need to write the whole code
31st Dec 2022, 1:43 PM
Alex Boso Nzaphila
Alex Boso Nzaphila - avatar