0

I am trying to randomly generate two 30-digits array and add them up. The result has to be put into a separate new array. I am having trouble to add up two numbers together if their sum is bigger than 10. Can anyone help me?

#include <stdio.h>
#include <time.h>
#include <stdlib.h>


int main()
{
int numlist[30],numlist2[30],addnum[60],i,j,k;
srand(time(NULL));


for (i=0;i<30;i++)
{
    numlist[i] = rand()%10;

}

for (j=0;j<30;j++)
{
    numlist2[j]=rand()%10;
}

for (k=0;k<30;k++)
{

    if ((numlist[k]+numlist2[k])<10)
        addnum[k] =  numlist[k]+numlist2[k];
    else
       /*dont know what to do*/



}
return 0;
}
5
  • 1
    you need to implement a carry register. Commented Sep 24, 2014 at 21:12
  • Hint: Result array index should not dependent on the variable looped over the array ( if you wish to keep the result sequentially in the addnum ). Commented Sep 24, 2014 at 21:14
  • first think what you've to do if the sum is not bigger than 10. you obviously have to put some kind of MARKER there so you can identify later if it was run in case of the ELSE block. Commented Sep 24, 2014 at 21:15
  • 1
    you guys are nuts. This is just long addition, right? How would you do it on paper? You carry the 1 to the next column. same concept. Commented Sep 24, 2014 at 21:17
  • Hello Garr. How do you achieve that? Commented Sep 24, 2014 at 21:19

1 Answer 1

1

Use a carry register:

int carry = 0;
for (k=0;k<30;k++)
{
    int adder = numlist[k]+numlist2[k]+carry;
    carry = adder/10;
    addnum[k] = adder % 10;
}
addnum[k] = carry;
Sign up to request clarification or add additional context in comments.

4 Comments

Minor: A complete addition needs to continue with for (k++;k<60;k++) { addnum[k] = 0; }
ah, yes. either that or zero-init the array.
(technically, adding 2 30 digit numbers will result in at most a 31 digit number)
True about the sum being 31 significant digits. As addnum has room for 60 digits and there is no variable indicating how many of the digits are considered significant, filling all 60 with something, even with 29 leading 0 is good practice.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.