Write a C program to multiply two numbers without the “*” operator.

Function Main
    Declare Integer fact1
    Declare Integer fact2
    Output " First factor"
    Input fact1
    Output "Second factor"
    Input fact2
    Output multiply(fact1, fact2)
End

Function multiply (Integer x, Integer y)
    Declare Integer result
    If y = 0
        Assign result = 0
    End
    If y > 0
        Assign result = x + multiply(x, y-1)
    End
    If y < 0
        Assign result = -multiply(x, -y)
    End
Return Integer result

#include <stdio.h>

int multiply(int x, int y);

int main() {
    int fact1;
    int fact2;
    
    printf("First factor:\n");
    scanf("%d", &fact1);
    printf("Second factor:\n");
    scanf("%d", &fact2);
    printf("%d\n", multiply(fact1, fact2));
    
    return 0;
}

int multiply(int x, int y) {
    int result;
    
    if (y == 0) {
        result = 0;
    }
    if (y > 0) {
        result = x + multiply(x, y - 1);
    }
    if (y < 0) {
        result = (int) (-multiply(x, (int) (-y)));
    }
    
    return result;
}

First factor:
5
Second factor:
3
15

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.