w3resource

C Programming: Multiple two positive numbers represent as string

C String: Exercise-37 with Solution

Write a C program to multiply two positive numbers as strings. Return a string representation of the product.

Sample Data:

("100", "15") -> "1500"
("100", "") -> "00"
("", "") -> "00"

Sample Solution:

C Code:

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

// Function to multiply two numbers represented as strings
char *test(char *str_num1, char *str_num2, int len1, int len2){	
    int str_sum[512], tmp, index;
    char *result;

    // If any number is '0', the result will be '0'
    if( str_num1[0] == '0' || str_num2[0] == '0' )
        return "0";

    // Initialize str_sum array
    for(int i = 0; i < 512; i++)
        str_sum[i] = 0;

    // Perform multiplication of str_num1 and str_num2
    for(int i = len1 - 1; i >= 0; i--){
        for(int j = len2 - 1; j >= 0; j--){
            str_sum[i + j + 1] += (str_num1[i] - '0') * (str_num2[j] - '0');
            str_sum[i + j] += str_sum[i + j + 1] / 10;
            str_sum[i + j + 1] %= 10;
        }
    }

    // Finding the index where the non-zero value starts
    for(int i = 0; i < 512; i++){
        if (str_sum[i] != 0){
            index = i;
            break;
        }
    }

    // Allocate memory for result
    result = (char*)malloc(sizeof(char) * (len1 + len2 + 2));
    int tot_len = len1 + len2;

    // Constructing the string result based on the multiplication
    if (str_sum[0] != 0){
        for(int i = 0; i < tot_len; i++)
            result[i] = str_sum[i] + '0';
        result[tot_len] = '\0';
    }
    else{
        for(int i = 1; i < tot_len; i++)
            result[i - 1] = str_sum[i] + '0';
        result[tot_len - 1] = '\0';
    }
    return result;
}

int main()
{
   char str_num1[10] = "100";
   char str_num2[10] = "15";
   // char str_num1[10] = "100";
   // char str_num2[10] = "0";
   // char str_num1[10] = "0";
   // char str_num2[10] = "0";

   printf("Original numbers: %s and %s",str_num1, str_num2); 
   int len1 = strlen(str_num1), len2 = strlen(str_num2);

   // Output the result of multiplication
   printf("\nMultiple two said numbers represent as string? %s", test(str_num1, str_num2, len1, len2));
}

Sample Output:

Original numbers: 100 and 15
Multiple two said numbers represent as string? 1500

Flowchart :

Flowchart: Multiple two positive numbers represent as string

C Programming Code Editor:

Improve this sample solution and post your code through Disqus.

Previous C Exercise: Verify that a string contains valid parentheses.
Next C Exercise: Reverse all the vowels present in a string.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.