C++ program to find square of an array elements

In this blog, we will create a program to print the square of an array of elements in C++.

What is Array?

An array is a collection of similar data elements stored in contiguous memory locations. It is the simplest data structure where each data element can be directly accessed using only its index number.

For example, if we want to store the marks achieved by a student in 5 subjects, then there is no need to define individual variables for each subject. Rather, we can define an array that will store data elements in contiguous memory locations.

Algorithm to find square of an array of elements

  • Initialize left=0 and right=n-1
  • if abs(left) >= abs(right) then store square (arr[left])
  • at the end of the result field and increment the left pointer
  • else store the square(arr[right]) in the result array and decrement the right pointer
  • decrease the result array index

C++ Code to print the square of an array of elements

// CPP code for the above access
#include <bits/stdc++.h>
using namespace std;

// Function to sort a square array
void sortSquares(vector<int>& arr, int n)
{
int left = 0, right = n - 1;
int result[n];

// Repeat from n - 1 to 0
for (int index = n - 1; index >= 0; index--) {

// Check if abs(arr[left]) is greater
// than arr[right]
if (abs(arr[left]) > arr[right]) {
result[index] = arr[left] * arr[left];
left++;
}
otherwise {
result[index] = arr[right] * arr[right];
right--;
}
}
for (int i = 0; i < n; i++)
arr[i] = result[i];
}

// Driver code
int main()
{
vector<int> arr;
arr.push_back(-6);
arr.push_back(-3);
arr.push_back(-1);
arr.push_back(2);
arr.push_back(4);
arr.push_back(5);

int n = 6;

cout << "Before sorting" << endl;
for (int i = 0; i < n; i++)
cout << arr[i] << " ";

sortSquares(arr, n);
cout << endl;
cout << "After sort" << endl;
for (int i = 0; i < n; i++)
cout << arr[i] << " ";
return 0;
}

Explanation of the code:

Explanation of the program
1. Declare a 2D array of some fixed row and column size (say 3 and 4).
2. Define all its elements at declaration time.
3. Run a for loop from 0 to row 1 and pass each row of the 2D array in the printSquare() function as its parameter.
4. Inside this function, a loop again runs to access all the column values ​​of that row.
5. So the loop runs from 0 to column-1, accesses each column value, evaluates its square, and stores the result in the same location.
6. Now print the array.

Output of the code