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
8 Réponses
+ 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.
+ 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.
+ 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;
0
If u add from 1 to 100, the total should be 5050..I.e 1+2+3+4+5+6........... like that
0
int main(){
int i, n, sum=0;
cin>>n;
for(i=1; i<=n;i++){
sum+=n;
}
cout<<sum;
return 0;
}
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
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";
- 2
Just type the error I have made, no need to write the whole code