#include <stdio.h>
#include <math.h>
int main(void) {
int a[100], carry,i,j=0,length=0,temp,leftcarry=0,l,n;
clrscr();
scanf("%d",&n);
for(i=0;i<100;i++) a[i]=0;
for(i=1;i<=n;i++){
a[j]+=i;
while(a[j]>=10){
carry=a[j]%10;
if(a[j]>=pow(10,(j+1))){
if(leftcarry==0){
a[j]=a[j]/10;
j++;
a[j]+=carry;
if(j>length)length=j;
}
else{
for(l=j+1;l<=length;l++){
temp=a[l+1];
a[l+1]=a[l];
a[l+2]=temp;
}
a[j+1]=carry;
leftcarry=0;
length=length+1;
}
}
else{
a[j]=a[j]/10;
a[j-1]+=a[j];
a[j]=carry;
j--;
if(a[j]>=10) leftcarry=1;
}
}
j=length;
}
for(i=0;i<=length;i++){
printf("%d",a[i]);
}
return 0;
}
I wanted to get some experience handling big integers using arrays, so I wrote this code to find sum of first n natural numbers. I got the right answer for given number<45. But for given number>=45, I get the answer which is less than the correct answer by 2. I would like to know why it is so. And I would also like to know of other simpler methods of handling big integers. Thank you.
Edit: Thank you all for answering. The question is now solved.
a[0]contains the complete sum, not because there are a number of digits. Ignore my previous comments — which I'm about to delete.