How to write a function to compute cubes of multiple values
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
computeCubesfunction. It takes three parameters that are passed by reference, which is specified using the&operator. - Lines 9–13: We define the
mainfunction. It initializes threeintvariables with different values and then calls thecomputeCubesfunction. After the cubes are computed,printfis used to print the cubes in a formattedstring.
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
computeCubesusing the spread operator (...), which takes a variable number of arguments and stores them in an array callednumbers. - Lines 3–5: We call the method
forEachon the array to iterate through its elements and calculate and add their cubes to another array calledcubeArray. - Lines 9–13: We declare three
constwith different values and then call thecomputeCubesfunction on them. We then print their cubes using theconsole.logfunction.
Free Resources
Copyright ©2026 Educative, Inc. All rights reserved