A cube is a value obtained by multiplying a number by itself three times. Mathematically, we can write it as follows:
We can write functions in different ways in different languages to compute the cube of multiple values. Some of these are given below.
#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);}
computeCubes
function. It takes three parameters that are passed by reference, which is specified using the &
operator.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
.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)
computeCubes
using the spread operator (...
), which takes a variable number of arguments and stores them in an array called numbers
.forEach
on the array to iterate through its elements and calculate and add their cubes to another array called cubeArray
.const
with different values and then call the computeCubes
function on them. We then print their cubes using the console.log
function.Free Resources