Write a program that takes a 2D pointer array and calculate sum of even and odd using recursive
function.
int sum(int **array, int row, int column, int &evenSum, int &oddSum)
#include <iostream>
using namespace std;
int sum(int **array, int row, int column, int &evenSum, int &oddSum)
{
static int cl = column;
if (array[row][column] % 2 == 0)
{
evenSum += array[row][column];
}
else
{
oddSum+= array[row][column];
}
if (column > 0)
return sum(array, row, column-1, evenSum, oddSum);
else if (row > 0)
{
row--;
column = cl;
return sum(array, row, column, evenSum, oddSum);
}
else return 0;
}
int main()
{
int row,col;
cout << "Please, enter a number of rows: ";
cin >> row;
cout << "Please, enter a number of cols: ";
cin >> col;
int **arr = new int*[row];
for (int i = 0; i < row; i++)
{
arr[i] = new int[col];
}
for (int i = 0; i < row; i++)
{
for (int j = 0; j < col; j++)
{
cout << "Please, enter a value of arr[" << i << "][" << j << "]: ";
cin>>arr[i][j];
}
}
for (int i = 0; i < row; i++)
{
for (int j = 0; j < col; j++)
{
cout<< arr[i][j]<<" ";
}
cout << endl;
}
int oddSum=0;
int evenSum=0;
sum(arr,row-1, col-1, evenSum, oddSum);
cout << "OddSum is " << oddSum;
cout << "\nEvenSum is " << evenSum;
}
Comments
Leave a comment