Write a C++ program that takes a 2D pointer array and calculates the sum of even and odd using
pointer notation of the array.
#include <iostream>
#include <ctime>
#include <iomanip>
int getSumOfElements(int* arr, int rows, int columns, bool isOddElements);
int main()
{
std::srand(std::time(nullptr));
int rows{0}, columns{0};
std::cout << "Enter the number of rows: ";
std::cin >> rows;
std::cout << "Enter the number of columns: ";
std::cin >> columns;
int* arr = new int[rows * columns];
for (int row = 0; row < rows; ++row)
{
for (int column = 0; column < columns; ++column)
{
//Populate array with random values in range [0, 9]
*(arr + row * columns + column) = rand() % 10;
std::cout << std::setw(2) <<*(arr +row * columns + column);
}
std::cout << std::endl;
}
std::cout << "Sum of even elemnts: " << getSumOfElements(arr, rows, columns, false) << std::endl;
std::cout << "Sum of odd elements: " << getSumOfElements(arr, rows, columns, true) << std::endl;
delete[] arr;
return 0;
}
int getSumOfElements(int* arr, int rows, int columns, bool isOddElements)
{
int sum = 0;
for(int row = 0; row < rows; ++row)
{
for(int column = 0; column < columns; column += 2)
{
//If isOddElements == true - calculates odd elements
//else - even elements
int index = row * columns + column + isOddElements;
sum += *(arr + index);
}
}
return sum;
}
Comments
Leave a comment