#include <stdio.h>
int main(void) { int n; scanf("%d",&n); if((n>=1&&n<=1000000000)){ float sum=0; for(int i=1;i<=n;i++){ sum=sum+i; } printf("%f",sum); } return 0; }
This is my code for adding natural numbers but it shows me wrong answer. I cant understand why
Hi @althaf007,
With these modifications to your code, It should work.
#include <stdio.h> int main(void) { long int n; scanf("%ld",&n); long int sum=0; for(long int i=1;i<=n;i++){ sum=sum+i; } printf("%ld",sum); return 0; }
If n is very large, the linear time complexity may result in TLE. You can also use the formula to calculate the sum from 1 to n
sum = n*(n+1) / 2 ; // declare sum as long long int
Thanks a lot. It worked and now I understood where I wasn’t paying attention at.