Hello and welcome to our community! Is this your first visit?
Enjoy an ad free experience by logging in. Not a member yet? Register.

# Thread: Create a function that calculates multiplication/division using addition and subtract

1. ## Create a function that calculates multiplication/division using addition and subtract

I'm a beginner in javascript, or any other programming language.

I have two functions
//
function sum(a,b){
return a + b;
}
function reduce(a,b){
return a - b;
}

I need to create another function, let's call it calculate, a function that gets a string argument, something like this "4*5", or "9/3". The calculate function will have to use additions, the sum function respectively, in order to calculate the multiplication, and subtractions, the reduce function, in order to calculate the division.

Can some one please give me some hints on how to do this ??
Thanks

• A few functions that might come in handy:

https://developer.mozilla.org/en-US/...s/String/split
https://developer.mozilla.org/en-US/...String/indexOf

Also, make sure to convert the numbers you collected from the string to actual Javascript numbers (i.e. using Number('5')), otherwise a+b will result in wrong results ('5' + '3' will evaluate to '53', not 8).

I'd call your reduce() function subtract() by the way, but that's up to you. Anyway, here is a skeleton to get you started:

Code:
```function multiply(input) {
// do something to fill these variables with the corresponding values
// make sure leftOperand and rightOperand are actually numerical values!
var leftOperand, rightOperand, operationSymbol;

// instead of if/elseif/else you could use a switch statement here (if you already know it)
if(operationSymbol === "*") {
// calculate multiplication
} else if(operationSymbol === "/") {
// calculate division
}
}```

• Hope this helps you also:
Code:
```<script type="text/javascript">
function sum(a,b){
return a + b;
}
function multiply (a,b){
var c = 0;
for(i=1;i<=b;i++){
c += sum(a, 0);
}
return (c);
}

document.write('multiply 3 x 3 = '+multiply (3,3));
</script>```

• Edit: never mind.

•

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•