Question 1 I want you to add two numbers together, representing the numbers as i
ID: 3640194 • Letter: Q
Question
Question 1
I want you to add two numbers together, representing the numbers as integer arrays.
The basic idea is to use arrays to represent the numbers as digits and adding them much like one would add by hand. I want you to be able to type in the command line something like
(Adder 1234567890 987654321) and have something similar to "2222222211" as the output.
I am willing to let you use the function below. So you can have a main function starting with
main(int argc, char**argv)
then somewhere in your code you can say GetNumber(argv[1],MyFirstNumber); and you will have the proper input in MyFirstNumber.
//This function will take a string and give a number for that string, assuming that all of the string's characters are numeric.
//This function is pass by reference, so you will need an array in main that will take the results of this array.
void GetNumber(char* Input,int Number[])
{
int i=0;
int Temp;
//This loop sets all of the elements of Number to zero. LENGTH was a define in my code you can have lengths >= 100
for(i;i<LENGTH;i++)
{
Number[i]=0;
}
i=0;
//This loop grabs every element in Input and places them in Number after subtracting 48
//We're assuming that these are ascii characters, which will give us the actual numbers after subtracting 48
//To see more consult an ascii character chart.
while(Input[i]!='')
{
Number[i]=(int)Input[i]-48;
i++;
}
int j=0;
i--;
//The Endianness of the numbers will be wrong right after inputing them. This simply does some flipping.
while(i>j)
{
Temp=Number[i];
Number[i]=Number[j];
Number[j]=Temp;
j++;
i--;
}
}
Explanation / Answer
#include<stdio.h>
#define LENGTH 100
int GetNumber(char *,int []);
void main(int argc, char **argv)
{
int i,l1,l2,l,an[LENGTH],c=0,e,j,Temp;
int MyFirstNumber[LENGTH];
int MySecondNumber[LENGTH];
for(i;i<LENGTH;i++)
{
an[i]=0;
}
l1=GetNumber(argv[1],MyFirstNumber);
l2=GetNumber(argv[2],MySecondNumber);
if(l2>l1)l=l2;
else l=l1;
for(i=0;i<l;i++)
{
an[i]=(c+MyFirstNumber[i]+MySecondNumber[i])%10;
c=(c+MyFirstNumber[i]+MySecondNumber[i])/10;
an[i+1]=c;
}
e=l;
j=0;
while(l>j)
{
Temp=an[l];
an[l]=an[j];
an[j]=Temp;
j++;
l--;
}
an[e+1]='';
for(i=0;i<=e;i++)
{
printf("%d",an[i]);
}
}
int GetNumber(char *Input,int Number[])
{
int i=0,t,j;
int Temp;
for(i;i<LENGTH;i++)
{
Number[i]=0;
}
i=0;
while(Input[i]!='')
{
Number[i]=(int)Input[i]-48;
i++;
}
Number[i]='';
t=i;
j=0;
i--;
while(i>j)
{
Temp=Number[i];
Number[i]=Number[j];
Number[j]=Temp;
j++;
i--;
}
return t;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.