Answer to Question #346506 in C++ for ali

Question #346506

Write a C++ program that takes a 2D pointer array and calculates the sum of even and odd using

pointer notation of the array.


1
Expert's answer
2022-06-02T10:27:12-0400
#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;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS