ADDNATRL code getting wrong

#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

1 Like

Hi @althaf007,

With these modifications to your code, It should work. :white_check_mark:

#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;
}

1 Like

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

1 Like

Thanks a lot. It worked and now I understood where I wasn’t paying attention at.