How to double values in 2d array? C++

2.7k views Asked by At

I'm trying to double each number in 2D arrays. For example the values in array1 would become {2,4,6}{4,8,12}{6,12,18}. The problem is that my code doubles the only the first number. Can someone give me some direction on what to do?

#include <iostream> 
#include <iomanip>

using namespace std; 

const int N = 3; 

int doubleValues(int arr[][N])
{
    for (int i = 0; i < N; i++) 
    {
        arr[i][N] *= 2; 

        for (int j = 0; j < N; j++)
        {
            arr[N][j] *= 2;
            return arr[i][j]; 
        }
    }   
}

void showArray(int arr[][N])
{
    for (int i = 0; i < N; i++)
    {
        for (int j = 0; j < N; j++)
        {
            cout << setw(4) << arr[i][j] << " ";
        }

        cout << endl; 
     }
}

int main()
{
    int array1 [N][N] = {
        { 1, 2, 3 } ,
        { 2, 4, 6 } ,
        { 3, 6, 9 } 
    };

    int array2 [N][N] = {
        { 3, 4, 5 } ,
        { 6, 8, 10 } ,
        { 9, 12, 15 } 
    };

    cout << "The values for array1 doubled are: \n";
    doubleValues(array1);
    showArray(array1);

    cout << "The values for array2 double are: \n";
    doubleValues(array2);
    showArray(array2);

    system("pause");
}
2

There are 2 answers

0
Greg Hewgill On BEST ANSWER

You have a return arr[i][j] in the inner loop of your doubleValues function. After doubling the first element, your function returns without doing any more work.

The solution is to remove this return statement. (And change doubleValues to a void function, because it doesn't need to return a value.)

Also, your doubleValues function seems to be modifying the wrong elements anyway. Both your accesses to arr[i][N] and arr[N][j] access elements out of bounds of your declared array size. You should probably be modifying arr[i][j] within your loop.

0
Alejandro On

If you can use std::array for this project (since you know the size of your array at compile time) , you can use the functions within the <algorithm> header to easily implement your doubleValues function and not worry about hand-writing the loops.

template<typename T, std::size_t size>
void doubleValues(std::array<T,size>& arr)
{
    std::transform(std::begin(arr),std::end(arr),std::begin(arr), [](auto x) { return 2 * x; });
}

This method would require that you break your 2d-array structure down into a single dimension, which can be accomplished with relative ease. For example,

std::array<int,N*N> array1 = { 1, 2, 3, 2, 4, 6, 3, 6, 9 };
std::array<int,N*N> array2 = { 3, 4, 5, 6, 8, 10, 9, 12, 15}

In the case where the size of the arrays could change dynamically, you can swap out std::array for std::vector.