Search code examples
c++visual-c++

How to print int and char together from 2d array


What I want to get is 4x4 matrix or larger and replace integers of center to characters. such as

 1   2   3   4
 5   6   7   8
 9  10  11  12
13  14  15  16

fill out numbers not by manual writing. It can be 8X8 10X10 matrix

 1   2   3   4 
 5   A   B   8
 9   B   B  12
13  14  15  16
void (int arr[MAX_ARRAY_SIZE][MAX_ARRAY_SIZE],int nrow){

    for (int row = 0; row < nrow; row++)
    {
        for (int col = 0; col < nrow; col++)
        {
            arr[row][col] = i++;
            if (nrow / 2 == row && nrow / 2 == col)
            {
                arr[row - 1][col - 1] = 'A';
                arr[row - 1][col] = 'B';
                arr[row][col - 1] = 'B';
                arr[row][col] = 'A';
            }
        }
    }
    
    for (int row = 0; row < nrow; row++)
    {
        for (int col = 0; col < nrow; col++)
        {
            cout<< arr[row][col];
        }
        cout << endl;
    }
}

I tried to make it char by

char charArray[MAX_ARRAY_SIZE][MAX_ARRAY_SIZE]=arr[MAX_ARRAY_SIZE][MAX_ARRAY_SIZE];

But It shows weird characters and if I do

charArray[row][col] =i +'0';

It shows me numbers before 10 and over 10 would be the same weird charaters.

Can anybody help me please?


Solution

  • Run this code and let me know if you have any qeustions.

    #include <iostream>
    
    const int MAX_ARRAY_SIZE = 8; // You can change this to create larger matrices
    
    void fillMatrix(char arr[MAX_ARRAY_SIZE][MAX_ARRAY_SIZE], int nrow) {
        char ch = 'A';
        int center = nrow / 2;
    
        for (int row = 0; row < nrow; row++) {
            for (int col = 0; col < nrow; col++) {
                if (row == center && col == center) {
                    arr[row][col] = ch++;
                } else {
                    arr[row][col] = ch;
                }
                ch++; // Move to the next character
            }
        }
    }
    
    int main() {
        char charArray[MAX_ARRAY_SIZE][MAX_ARRAY_SIZE];
    
        fillMatrix(charArray, MAX_ARRAY_SIZE);
    
        for (int row = 0; row < MAX_ARRAY_SIZE; row++) {
            for (int col = 0; col < MAX_ARRAY_SIZE; col++) {
                std::cout << charArray[row][col] << "\t";
            }
            std::cout << std::endl;
        }
    
        return 0;
    }