c++multidimensional-array3delementfind-occurrences

C++, 3D arrays, find target and its occurrences. My problem is, my elements only displaying zeros but i want to display 0-9 random numbers


#include<iostream>
#include<stdlib.h>
#include<time.h>

using namespace std;

int count_occurrences(int array[3][3][3], int size, int target)
{
    int result = 0;
    for (int i = 0; i < size; ++i) {
        for (int j = 0; j < size; ++j) {
            for (int k = 0; k < size; ++k) {
                if (target == array[i][j][k])
                    result++;
            }
        }
    }
    return result;
}


int main()
{
    int b;
    const int a = 3;
    int nums[a][a][a] = { rand() % 10 };
    int array = sizeof(nums);
    cout << "===================================================================================" << endl;
    cout << "==========================DISPLAYING 3X3X3 ARRAY ELEMENTS==========================" << endl;
    for (int i = 0; i < a; ++i) {
        for (int j = 0; j < a; ++j) {
            for (int k = 0; k < a; ++k) {
                cout << setw(10) << "[   array[" << i << "][" << j << "][" << k << "] = " << nums[i][j][k] << "   ]" << "  ";
            }
            cout << endl;
        }
    }
    cout << endl;
    cout << endl;
    cout << endl;
    cout << "Please enter a target value : ";
    cin >> b;
    cout << "The number of occurrences of " << b << " : " << count_occurrences(nums, a, b) << " times";
    return 0;
}

Solution

  • This doesn't work properly because you're not initializing the list with enough elements. You're passing in one element, rand() % 10, but nums is a 3D array where each dimension has length 3, so you need to initialize it with 3×3×3 = 27 elements.

    Doing that with the inline initializer looks like this:

    int nums[a][a][a] = { 
        rand() % 10, rand() % 10, rand() % 10, 
        rand() % 10, rand() % 10, rand() % 10, 
        rand() % 10, rand() % 10, rand() % 10, 
        rand() % 10, rand() % 10, rand() % 10, 
        rand() % 10, rand() % 10, rand() % 10, 
        rand() % 10, rand() % 10, rand() % 10, 
        rand() % 10, rand() % 10, rand() % 10, 
        rand() % 10, rand() % 10, rand() % 10, 
        rand() % 10, rand() % 10, rand() % 10 
    };
    

    A cleaner, more programmatic way would be like this:

    int nums[a][a][a];
    for(int i = 0; i < a; i++){
        for(int j = 0; j < a; j++){
            for(int k = 0; k < a; k++){
                nums[i][j][k] = rand()%10;
            }
        }
    }