Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

c++

# How to write a function to compute cubes of multiple values Muhammad Saad Mehmoon

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

### Overview

A cube is a value obtained by multiplying a number by itself three times. Mathematically, we can write it as follows:

### Code

We can write functions in different ways in different languages to compute the cube of multiple values. Some of these are given below.

### C/C++

#include <iostream>void computeCubes(int &a, int &b, int &c) {  a = a * a * a;  b = b * b * b;  c = c * c * c;}int main() {  int first = 3, second = 5, third = 2;  computeCubes(first, second, third);  printf("The cubes are %i, %i and %i.", first, second, third);}

### Explanation

• Lines 3–7: We define a computeCubes function. It takes three parameters that are passed by reference, which is specified using the & operator.
• Lines 9–13: We define the main function. It initializes three int variables with different values and then calls the computeCubes function. After the cubes are computed, printf is used to print the cubes in a formatted string.

### JavaScript (JS)

One of the advantages of using JS is that it allows functions to have a variable number of arguments. A JS function can also return arrays, thus making it more efficient than C++.

const computeCubes = (...numbers) => {  let cubeArray = [];  numbers.forEach(number => {    cubeArray.push(number * number * number);  });  return cubeArray;}const first = 3;const second = 5;const third = 2;const cubes = computeCubes(first, second, third);console.log("The cubes are", cubes)

### Explanation

• Lines 1–2: We define a function computeCubes using the spread operator (...), which takes a variable number of arguments and stores them in an array called numbers.
• Lines 3–5: We call the method forEach on the array to iterate through its elements and calculate and add their cubes to another array called cubeArray.
• Lines 9–13: We declare three const with different values and then call the computeCubes function on them. We then print their cubes using the console.log function.

RELATED TAGS

c++

CONTRIBUTOR Muhammad Saad Mehmoon 