View the step-by-step solution to:

Question

#include <

style="color:rgb(206,145,120);">stdio.h>

#include <string.h>

#include <stdlib.h>

#include <stdbool.h>


char* str_compute_sum(const char* num1, const char* num2) {


char *temp, *str1, *str2, *str3;

char *revStr1, *revStr2, *revStr3;


//allocate memory for strings

temp=((char*)malloc(sizeof(char)));

str1=((char*)malloc(strlen(num1)*sizeof(char)));

str2=((char*)malloc(strlen(num2)*sizeof(char)));

revStr1=((char*)malloc(strlen(num2)*sizeof(char)));

revStr2=((char*)malloc(strlen(str2)*sizeof(char)));

str3=((char*)malloc(strlen(str2)*sizeof(char)));

revStr3=((char*)malloc(strlen(str2)*sizeof(char)));


int i, j, carry=0, sum=0;


strcpy(str1, num1);

strcpy(str2, num2);


//if lenfth of num1 > num2, swap

if(strlen(num1)>strlen(num2)) {

strcpy(temp, str1);

strcpy(str1, str2);

strcpy(str2, temp);

}


//reverse the strings

for(i=strlen(str1)-1; i>=0; i--) {

revStr1[j++]=str1[i];

revStr1[j]='0';

j=0;

}

for(i=strlen(str2)-1; i>=0; i--) {

revStr2[j++]=str2[i];

revStr2[i]='0';

}


//compute the sum

for(i=0; i<strlen(revStr1); i++) {

sum=((revStr1[i]-'0')+(revStr2[i]-'0')+carry);

str3[i]=sum%10+'0';

carry=sum/10;

}


for(i=strlen(revStr1);i<strlen(revStr2);i++) {

sum=((revStr2[i]-'0')+carry);

str3[i]=sum%10+'0';

carry=sum/10;

}


if(carry) {

str3[i++]=carry+'0';

str3[i]='0';

j=0;

}


for(i=strlen(str3)-1;i>=0;i--){

revStr3[j++]=str3[i];

revStr3[j]='0';

return revStr3;

}

free(temp);

free(str1);

free(str2);

free(revStr1);

free(revStr2);

free(str3);

free(revStr3);

}


bool test_q4_2() {

char* str1 = "123530124";

char* str2 = "981252430004";

char* sum = str_compute_sum(str1, str2);

if (sum && strcmp(sum, "981375960128") == 0) { // checks sum != NULL and the value is correct

printf("Q4-2 okn");

free(sum);

return true;

}

else {

printf("nQ4-2 ERRORn");

free(sum);

return false;

}

}


int main() {

printf("%s",str_compute_sum("123456789","987654321"));

test_q4_2();

return 0;

}


My program needs to sum large numbers of strings, however, it is not working.

Could you help me to find my problem? In addition, If I can improve my structure, please give me some guide.

Your help will be appreciated.

Top Answer

Sign up to view the full answer

Why Join Course Hero?

Course Hero has all the homework and study help you need to succeed! We’ve got course-specific notes, study guides, and practice tests along with expert tutors.

-

Educational Resources
  • -

    Study Documents

    Find the best study resources around, tagged to your specific courses. Share your own to gain free Course Hero access.

    Browse Documents
  • -

    Question & Answers

    Get one-on-one homework help from our expert tutors—available online 24/7. Ask your own questions or browse existing Q&A threads. Satisfaction guaranteed!

    Ask a Question