Member-only story

In C++, write a method that compute squares using pointers

Marika Lam
1 min readMay 22, 2022

--

Question

Create a method that takes in a reference int and an int array. Return the memory address of the first element of the array.

Explanation

Within the computerSquares function, create a for loop that loops from 0 to the length of the array, n. Within the for loop, assign the value ((k+1)²) into the current element the for loop is iterating at. Once the for loop has finished iterating, then return the memory address of the first element of the array &arr[0].

Once the computerSquares function is done, the program will return the main method where the program will print the resulting values of the computerSquares function, using ptr[i].

#include <iostream>using namespace std;int* computeSquares(int& n, int arr[]){n = 10;for (int k = 0; k < n; k++){arr[k] = (k+1) * (k+1);
}
return &arr[0];}int main(){int m;int arr[10];int* ptr = computeSquares(m, arr);for (int i = 0; i < m; i++)cout << ptr[i] << ' ';}

To learn more about datastructures and algorithms:

Coursera — Algorithms Specialization (Stanford )

Coursera — Datastructures and Algorithms (HSE)

Coursera — Java Programming and Software Engineering Fundamentals (Duke University)

Coursera — Data Structures and Algorithms Specialization (UCSD)

--

--

No responses yet