howdy,
as part of an introductory C course, i have been tasked to write a program that will add two large integers (in this case 10 digits max). the method that we have been asked to use is:
read in the user input integers as character strings
convert the character strings to int strings
add them
my addition method (as you'll see in the code below) is successful, until it reaches c[0] (where c[] is the final sum). i'm not sure what the error is, but i get a "junk" number in that position and when i print my final summation the value of c[] is returned as "-1".
here's my code:
the large group of printf statements was my way of debugging, and it proves that the addition method works until c[0].
i'd greatly appreciate any insight.
thanks!
p.s. attached is the code in a .txt in case... whatever.
as part of an introductory C course, i have been tasked to write a program that will add two large integers (in this case 10 digits max). the method that we have been asked to use is:
read in the user input integers as character strings
convert the character strings to int strings
add them
my addition method (as you'll see in the code below) is successful, until it reaches c[0] (where c[] is the final sum). i'm not sure what the error is, but i get a "junk" number in that position and when i print my final summation the value of c[] is returned as "-1".
here's my code:
Code:
#include<stdio.h>
#include<string.h>
int main ()
{
int Length1, Length2, i, j, E;
char str1[11], str2[11];
int a[10]={0}, b[10]={0}, c[11]={0};
printf("Please Enter Two Integers, 10 Digits Maximum >>");
scanf("%s%s", str1, str2);
Length1 = strlen(str1);
Length2 = strlen(str2);
i=0;
while(str1[i] != '\0')
{
a[(10-(Length1-i))] = ((int)str1[i] - 48);
i++;
}
i=0;
while(str2[i] != '\0')
{
b[(10-(Length2-i))] = ((int)str2[i] - 48);
i++;
}
j=10;
E=0;
while(j > -1)
{
if(j==0)
{
E=0;
E=(a[0]+b[0])/10;
c[0]=E;
}
c[j] = (a[j-1]+b[j-1]+E)%10;
E=(a[j-1]+b[j-1])/10;
j--;
}
printf("%d\n", c[10]);
printf("%d\n", c[9]);
printf("%d\n", c[8]);
printf("%d\n", c[7]);
printf("%d\n", c[6]);
printf("%d\n", c[5]);
printf("%d\n", c[4]);
printf("%d\n", c[3]);
printf("%d\n", c[2]);
printf("%d\n", c[1]);
printf("%d\n", c[0]);
for(i=0; i < 10; i++)
printf("%d", a[i]);
printf(" + ");
for(i=0; i < 10; i++)
printf("%d", b[i]);
printf(" = ");
for(i=0; i < 11; i++);
printf("%d", c[i]);
printf("\n");
return 0;
}
i'd greatly appreciate any insight.
thanks!
p.s. attached is the code in a .txt in case... whatever.
Comment