Reputation: 33
I need to convert code that is currently using two functions to create a character 2D Array into one function that creates a character 2D Array.
The contents of the Array is the alphabet from 'A' to 'Y' (omitting 'Z', as I need a matrix of 5*5 size). Notes: I cannot use vectors or pointers.
The below code works, but it needs to be converted into one function, which I am having considerable trouble doing. I have been researching but I cannot find a clear enough solution, and I am a beginner in C++.
// Fills 4-Square Matrix 1 with Alphabet (1D Array)
void fill4Square1(char* FourSquare_1_Matrix)
{
int n;
for (n = 0; n < 25; n++)
FourSquare_1_Matrix[n] = 'A' + n;
}
// Fills 4-Square Matrix 1 with Alphabet (2D Array)
void fill4Square1_1()
{
char FourSquare_1_Matrix[5][5];
fill4Square1((char*)FourSquare_1_Matrix); //Function Call for 1D Array
for (int row = 0; row < 5; row++) //For Loop puts 1D array into 2D Array
{
for (int col = 0; col < 5; col++)
cout << FourSquare_1_Matrix[row][col] << " ";
cout << "\n";
}
}
I wrote the below code, but I cannot get the contents of the 1D Array into the 2D array. The 2D Array is being filled with random char characters. Program OUTPUT
void PlayFairMatrix1()
{
int i = 0;
char Matrix[25] = { {0} };
char PlayFairMatrix[5][5] = { {0} };
int n;
//1D Matrix
for (i = 0; i < 25; i++)
{
Matrix[i] = 'A' + i;
cout << Matrix[i];
}
cout << "\n";
cout << " " << endl;
////2D Matrix
for (int row = 0; row < 5; row++)
{
for (int col = 0; col < 5; col++)
{
PlayFairMatrix[row][col] = Matrix[i];
i++;
}
cout << PlayFairMatrix << " ";
cout << "\n";
}
cout << " " << endl;
}
Can anyone please help point me in the right direction?
Upvotes: 2
Views: 9674
Reputation: 15824
While populating PlayFairMatrix, you forgot to reinitialize variable i = 0
. That will fix your code.
But you can do it simply as follows
void PlayFairMatrix1()
{
char PlayFairMatrix[5][5] = { {0} };
int i = 0;
for(int row = 0; row < 5; ++row)
{
for(int col = 0; col < 5: ++col)
{
PlayFairMatrix[row][col]='A'+i;
}
}
}
Upvotes: 1
Reputation: 982
The problem lies on this line PlayFairMatrix[row][col] = Matrix[i];
i
starts off with the value 25 from previous loop. And you never reset it back to 0.
So, the simplest way to fix it is just add i = 0;
before the second loop.
Another way will accessing Matrix
using row and col, but I will leave that for you as an exercise.
Also, when you print PlayFairMatrix
, you are not accessing it with index so you will print the pointer instead. You should put cout << PlayFairMatrix << " ";
into inner loop and add the index, so it becomes cout << PlayFairMatrix[row][col] << " ";
Upvotes: 1