C++, Convert 1D Array into 2D Array - c++

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?

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] << " ";

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;
}
}
}

Related

Find first positive elemnt in 2d array [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed last month.
Improve this question
Maybe someone can help. The task is to find first positive element in 2D array and in which row is is located. But my program doesn't stop at the first one and keep searching while outputting the last one.
And second question, why my 2D array output not in rows and columns, but in one line.
#include<iostream>
#include<iomanip>
using namespace std;
int main()
{
int n, m;
cout << "Enter row count ";
cin >> n;
cout << "Enter column count ";
cin >> m;
float **arr = new float*[n];
for (int i = 0; i < n; i++)
arr[i] = new float[m];
srand(time(NULL));
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
{
cout << "Enter elements [" << i << "][" << j << "]: ";
cin >> arr[i][j];
}
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
{
cout << setw(4) << arr[i][j] << " ";
}
cout << endl;
int rowNumber;
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
{
if (arr[i][j] >= 0)
{
rowNumber = i;
break;
}
}
cout << "First positive elemnt is in row " << rowNumber << endl;
return 0;
}
Find first positive element
Remember that break only stops the loop it is part of. Any outside loops continue on their merry way.
There are two three ways to deal with this: goto, flags, and return.
for (...rows...)
{
for (...columns...)
{
if (...found it...)
goto done; // break from the inner ‘columns’ loop
} // AND from the outer ‘rows’ loop
}
done:
JSYK, people will burn you as a witch if you use goto.
You could use a little boolean flag in the outer loop(s) to quit early:
bool done = false;
for (int i = 0; (i < n) and !done; i++)
{
for (int j = 0; (i < m) and !done; j++)
{
if (...found it...)
{
done = true;
}
}
}
A “pro” to using a flag is that it will tell you whether or not you found what you were looking for: if done is still false after the loops then no positive value was found.
I personally think that flags add unnecessary complexity to the code: the computer has to do more work and it is harder to visually separate out the mechanism of the algorithm over the extra bookkeeping.
My recommendation: create yourself a little function instead, and use return:
int get_row_of_first_positive_value( float** arr, int nrows, int ncolumns )
{
for (int row = 0; row < nrows; row++)
for (int col = 0; col < ncolumns; col++)
{
if (arr[row][col] >= 0)
{
return row;
}
}
}
return -1; // no positive element found
}
You don’t need a sentinel value (like -1) to use a function. In this case it works, since -1 is not a valid row number, but you can easily return a std::optional value or use any number of other ways to return a success/failure flag.
As an aside: names matter. Most people will recognize things like i, j, n, m, etc, but even so it makes life much more readable to use better names. Here it is abundantly obvious that we are returning the row where the positive element was found.
Back in main you can say:
int rowNumber = get_row_of_first_positive_value( arr, n, m );
Print newlines between rows
Again this is a nested loop problem. The inner loop prints elements of the row. These are separated by spaces (or tabs or whatever).
for (int col = 0; col < ncolumns; col++)
{
std::cout << std::setw(4) << arr[row][col];
std::cout << " "; // printed after every element in the row
} // in order to separate columns
But the elements of the outer loop (the rows) are separated by newlines.
for (int row = 0; row < nrows; row++)
{
...print the row here...
std::cout << "\n"; // printed after every row in the matrix
} // in order to separate rows
See how the two structures are similar. Recommendation, write yourself a helper function just to print the array:
void print_matrix( float** arr, int nrows, int ncolumns )
{
...
}
Then you can use it in main easily:
print_matrix( arr, n, m );
int rowNumber = get_row_of_first_positive_value( arr, n, m );
if (rowNumber < 0)
std::cout << "Alas, ...\n";
else
std::cout << "First positive elemnt is in row " << rowNumber << "\n";
}

How do I set all the diagonals in a matrix equal to zero?

I have a problem with my homework that asks me to have the compiler print out a matrix in which all the diagonals are outputted as zero. I also have to pass it to a function. However, I have no idea how to do this..
Here is my code:
#include <iostream>
using namespace std;
int diagonals();
int main()
{
//problem 1
int matrix[3][3];
for (int i = 1; i <= 3; i++)
{
for (int j = 1; j <= 3 ; j++)
{
cout << "Row " << i << " column " << j<< ": ";
cin >> matrix[i][j];
}
}
for (int i = 1; i <= 3; i++)
{
for (int j = 1; j <= 3; j++)
{
cout << matrix[i][j] << " ";
}
cout << endl;
}
cout << "\nReverse of the matrix:" << endl;
for (int j = 1; j <= 3; j++)
{
for (int i = 1; i <= 3; i++)
{
cout << matrix[i][j] << " ";
}
cout << endl;
}//end of problem 1
//problem 2
cout << "Diagonals changed to 0:\n" << endl;
}
your matrix declaration says int matrix[3][3]; that it has three 1-D array & in each 1-D array you can store three elements. And in C/C++ array index starts from zero.
Problematic statement is for (int i = 1; i <= 3; i++) as you are skipping matrix[0][0] and trying to store into matrix[3][3] which doesn't exist which in turn causes undefined behavior.
So firstly start iterating loop from 0 to number of rows & column respectively.
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3 ; j++) {
cout << "Row " << i << " column " << j<< ": ";
cin >> matrix[i][j];
}
}
Coming to task you mentioned, print out a matrix in which all the diagonals are outputted as zero. ? write one condition so that if row value & col value are equal then assign it to zero otherwise scan from user. Here is the sample code
int main(void) {
int matrix[3][3] = { 0 }; /* initialize it */
int row = sizeof(matrix)/sizeof(matrix[0]); /* find no of rows */
int col = sizeof(matrix[0])/sizeof(matrix[0][0]);/* find no of columns */
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
if( i == j)
matrix[i][j] = 0;/* when i and j are equal means thats diagonal and assign it to zero */
else /* if its not diagonal then scan from user */
std::cin>>matrix[i][j];
}
}
return 0;
}
Secondly, I also have to pass it to a function. for this learn how to pass 2d array to a function. Here is the sample example.
void diagonal(int (*mat)[3],int row, int col) { /* mat is pointer to an array */
std::cout<<"printing matrix "<<std::endl;
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
std::cout<<mat[i][j]<<"\t";
}
std::cout<<std::endl;
}
}
And call diagonal() like below from main() function as
diagonal(matrix,row,col); /* pass matrix, no of rows, no of columns */

When printing out double dimensional array to console, values are being set randomly

Let's say I create a double dimensional array in main fuction:
int board[8][8] = {0};
When I am printing it out to console with a simple FOR LOOP in MAIN everything works fine and console shows that all elements have been set to 0.
However, when I am trying to pass this array as an argument to the print function like shown below, some elements are set correctly to 0, whereas the rest become random values :
void print_board (int (*array)[8][8]);
int main (){
int board[8][8] = {0};
print_board(&board);
return 0;
}
void print_board (int (*array)[8][8]){
for (int i = 0; i < 8; i++){
for (int j = 0; j < 8; j++){
cout << *array[i][j] << " ";
}
cout << endl;
}
}
I played with pointers and ampersands, and tried to google, but guess I am missing something.
Would be very grateful for your help!
According to the Operator Precedence, operator[] has higher precedence than operator*. So *array[i][j] is equivalent to *(array[i][j]). And array is a pointer (to array), and array[i] might cause UB when i >= 1.
You should change it to
cout << (*array)[i][j] << " ";
You can change your output to std::cout << (*array)[i][j] or make things simpler:
void print_board(int array[8][8]){
for (int i = 0; i < 8; i++){
for (int j = 0; j < 8; j++){
std::cout << array[i][j] << " ";
}
std::cout << std::endl;
}
}
int main (){
int board[8][8] = {0};
print_board(board);
}

C++ Instances of value in array? (Histogram)

I was wondering if it was possible in C++ to parse through an array and retrieve the amount of times an integer appears in the array. I'm trying to make a histogram of the values, but currently am stuck as to how to continue.
It is a one-dimensional array if that matters and I am using this function to print the array:
void print(int a[], int n)
{
int j = 1;
cout << endl;
for(int i=0; i < n; i++)
{
if(!(j%6))
{
j=1; cout << endl << endl;
}
cout << right << setw(2) << a[i] << " ";
++j;
}
}
Which is giving me correct output in this screenshot:
http://i.imgur.com/P8Jzj1V.png
However, once I go to my histogram function (which I know is coded incorrectly) I am getting the following output:
http://i.imgur.com/WJtBjoF.png
Because with my current code it is printing asterisks based on a value taken from the array:
for (int i = 0; i < size; i++)
{
cout << a[i] << ":" << bar(a[i-1]);
cout << endl;
}
P.S. - The "bar" function just returns a string with a specified amount of '*' based on the number given to it.
I know the last bit is incorrect, but that's what I'm trying to fix.
There are two easy ways to go:
sort+count
Sort the array
Iterate through them all, and print summaries on encountering a different element / the end.
unordered_map
Create an std::unordered_map<int,int>
Iterate through the array incrementing the count for each encountered element when you encounter it.
Print the summary.
An array of size 2**sizeof(int)*CHAR_BIT is prohibitively big.
Let's see. You can keep a map with the counts of each element, being each element a key to the map:
for (int i = 0; i < size; i++)
{
int current = a[i];
//if it doesn't find it it returns
if (countMap.find(current) != countMap.end())end()
{
countMap[current]++;
} else
{
countMap[current] = 1;
}
}
I don't know if the syntax is totally correct, but something like this will get you what you want.
Figured it out.
int tempVal = 0;
int tempTwo = 0;
int counter = 0;
for (int i = 0; i < size; i++) // Checks for histogram output
{
tempVal = a[i];
for (int j = 0; j < size; j++)
{
if(a[j] == tempVal)
{
counter += 1;
}
}
if(tempVal != tempTwo)
cout << setw(3) << tempVal << " : " << bar(counter) << endl;
tempTwo = tempVal;
counter = 0;
}

Pointer-to-pointer dynamic two-dimensional array

First timer on this website, so here goes..
I'm a newbie to C++ and I'm currently working through the book "Data structures using C++ 2nd ed, of D.S. Malik".
In the book Malik offers two ways of creating a dynamic two-dimensional array.
In the first method, you declare a variable to be an array of pointers, where each pointer is of type integer. ex.
int *board[4];
..and then use a for-loop to create the 'columns' while using the array of pointers as 'rows'.
The second method, you use a pointer to a pointer.
int **board;
board = new int* [10];
etc.
My question is this: which is the better method? The ** method is easier for me to visualize, but the first method can be used in much the same way. Both ways can be used to make dynamic 2-d arrays.
Edit: Wasn't clear enough with the above post. Here's some code I tried:
int row, col;
cout << "Enter row size:";
cin >> row;
cout << "\ncol:";
cin >> col;
int *p_board[row];
for (int i=0; i < row; i++)
p_board[i] = new int[col];
for (int i=0; i < row; i++)
{
for (int j=0; j < col; j++)
{
p_board[i][j] = j;
cout << p_board[i][j] << " ";
}
cout << endl;
}
cout << endl << endl;
int **p_p_board;
p_p_board = new int* [row];
for (int i=0; i < row; i++)
p_p_board[i] = new int[col];
for (int i=0; i < row; i++)
{
for (int j=0; j < col; j++)
{
p_p_board[i][j] = j;
cout << p_p_board[i][j] << " ";
}
cout << endl;
}
The first method cannot be used to create dynamic 2D arrays because by doing:
int *board[4];
you essentially allocated an array of 4 pointers to int on stack. Therefore, if you now populate each of these 4 pointers with a dynamic array:
for (int i = 0; i < 4; ++i) {
board[i] = new int[10];
}
what you end-up with is a 2D array with static number of rows (in this case 4) and dynamic number of columns (in this case 10). So it is not fully dynamic because when you allocate an array on stack you should specify a constant size, i.e. known at compile-time. Dynamic array is called dynamic because its size is not necessary to be known at compile-time, but can rather be determined by some variable in runtime.
Once again, when you do:
int *board[4];
or:
const int x = 4; // <--- `const` qualifier is absolutely needed in this case!
int *board[x];
you supply a constant known at compile-time (in this case 4 or x) so that compiler can now pre-allocate this memory for your array, and when your program is loaded into the memory it would already have this amount of memory for the board array, that's why it is called static, i.e. because the size is hard-coded and cannot be changed dynamically (in runtime).
On the other hand, when you do:
int **board;
board = new int*[10];
or:
int x = 10; // <--- Notice that it does not have to be `const` anymore!
int **board;
board = new int*[x];
the compiler does not know how much memory board array will require, and therefore it does not pre-allocate anything. But when you start your program, the size of array would be determined by the value of x variable (in runtime) and the corresponding space for board array would be allocated on so-called heap - the area of memory where all programs running on your computer can allocate unknown beforehand (at compile-time) amounts memory for personal usage.
As a result, to truly create dynamic 2D array you have to go with the second method:
int **board;
board = new int*[10]; // dynamic array (size 10) of pointers to int
for (int i = 0; i < 10; ++i) {
board[i] = new int[10];
// each i-th pointer is now pointing to dynamic array (size 10) of actual int values
}
We've just created an square 2D array with 10 by 10 dimensions. To traverse it and populate it with actual values, for example 1, we could use nested loops:
for (int i = 0; i < 10; ++i) { // for each row
for (int j = 0; j < 10; ++j) { // for each column
board[i][j] = 1;
}
}
What you describe for the second method only gives you a 1D array:
int *board = new int[10];
This just allocates an array with 10 elements. Perhaps you meant something like this:
int **board = new int*[4];
for (int i = 0; i < 4; i++) {
board[i] = new int[10];
}
In this case, we allocate 4 int*s and then make each of those point to a dynamically allocated array of 10 ints.
So now we're comparing that with int* board[4];. The major difference is that when you use an array like this, the number of "rows" must be known at compile-time. That's because arrays must have compile-time fixed sizes. You may also have a problem if you want to perhaps return this array of int*s, as the array will be destroyed at the end of its scope.
The method where both the rows and columns are dynamically allocated does require more complicated measures to avoid memory leaks. You must deallocate the memory like so:
for (int i = 0; i < 4; i++) {
delete[] board[i];
}
delete[] board;
I must recommend using a standard container instead. You might like to use a std::array<int, std::array<int, 10> 4> or perhaps a std::vector<std::vector<int>> which you initialise to the appropriate size.
In both cases your inner dimension may be dynamically specified (i.e. taken from a variable), but the difference is in the outer dimension.
This question is basically equivalent to the following:
Is int* x = new int[4]; "better" than int x[4]?
The answer is: "no, unless you need to choose that array dimension dynamically."
This code works well with very few requirements on external libraries and shows a basic use of int **array.
This answer shows that each array is dynamically sized, as well as how to assign a dynamically sized leaf array into the dynamically sized branch array.
This program takes arguments from STDIN in the following format:
2 2
3 1 5 4
5 1 2 8 9 3
0 1
1 3
Code for program below...
#include <iostream>
int main()
{
int **array_of_arrays;
int num_arrays, num_queries;
num_arrays = num_queries = 0;
std::cin >> num_arrays >> num_queries;
//std::cout << num_arrays << " " << num_queries;
//Process the Arrays
array_of_arrays = new int*[num_arrays];
int size_current_array = 0;
for (int i = 0; i < num_arrays; i++)
{
std::cin >> size_current_array;
int *tmp_array = new int[size_current_array];
for (int j = 0; j < size_current_array; j++)
{
int tmp = 0;
std::cin >> tmp;
tmp_array[j] = tmp;
}
array_of_arrays[i] = tmp_array;
}
//Process the Queries
int x, y;
x = y = 0;
for (int q = 0; q < num_queries; q++)
{
std::cin >> x >> y;
//std::cout << "Current x & y: " << x << ", " << y << "\n";
std::cout << array_of_arrays[x][y] << "\n";
}
return 0;
}
It's a very simple implementation of int main and relies solely on std::cin and std::cout. Barebones, but good enough to show how to work with simple multidimensional arrays.
this can be done this way
I have used Operator Overloading
Overloaded Assignment
Overloaded Copy Constructor
/*
* Soumil Nitin SHah
* Github: https://github.com/soumilshah1995
*/
#include <iostream>
using namespace std;
class Matrix{
public:
/*
* Declare the Row and Column
*
*/
int r_size;
int c_size;
int **arr;
public:
/*
* Constructor and Destructor
*/
Matrix(int r_size, int c_size):r_size{r_size},c_size{c_size}
{
arr = new int*[r_size];
// This Creates a 2-D Pointers
for (int i=0 ;i < r_size; i++)
{
arr[i] = new int[c_size];
}
// Initialize all the Vector to 0 initially
for (int row=0; row<r_size; row ++)
{
for (int column=0; column < c_size; column ++)
{
arr[row][column] = 0;
}
}
std::cout << "Constructor -- creating Array Size ::" << r_size << " " << c_size << endl;
}
~Matrix()
{
std::cout << "Destructpr -- Deleting Array Size ::" << r_size <<" " << c_size << endl;
}
Matrix(const Matrix &source):Matrix(source.r_size, source.c_size)
{
for (int row=0; row<source.r_size; row ++)
{
for (int column=0; column < source.c_size; column ++)
{
arr[row][column] = source.arr[row][column];
}
}
cout << "Copy Constructor " << endl;
}
public:
/*
* Operator Overloading
*/
friend std::ostream &operator<<(std::ostream &os, Matrix & rhs)
{
int rowCounter = 0;
int columnCOUNTER = 0;
int globalCounter = 0;
for (int row =0; row < rhs.r_size; row ++)
{
for (int column=0; column < rhs.c_size ; column++)
{
globalCounter = globalCounter + 1;
}
rowCounter = rowCounter + 1;
}
os << "Total There are " << globalCounter << " Elements" << endl;
os << "Array Elements are as follow -------" << endl;
os << "\n";
for (int row =0; row < rhs.r_size; row ++)
{
for (int column=0; column < rhs.c_size ; column++)
{
os << rhs.arr[row][column] << " ";
}
os <<"\n";
}
return os;
}
void operator()(int row, int column , int Data)
{
arr[row][column] = Data;
}
int &operator()(int row, int column)
{
return arr[row][column];
}
Matrix &operator=(Matrix &rhs)
{
cout << "Assingment Operator called " << endl;cout <<"\n";
if(this == &rhs)
{
return *this;
} else
{
delete [] arr;
arr = new int*[r_size];
// This Creates a 2-D Pointers
for (int i=0 ;i < r_size; i++)
{
arr[i] = new int[c_size];
}
// Initialize all the Vector to 0 initially
for (int row=0; row<r_size; row ++)
{
for (int column=0; column < c_size; column ++)
{
arr[row][column] = rhs.arr[row][column];
}
}
return *this;
}
}
};
int main()
{
Matrix m1(3,3); // Initialize Matrix 3x3
cout << m1;cout << "\n";
m1(0,0,1);
m1(0,1,2);
m1(0,2,3);
m1(1,0,4);
m1(1,1,5);
m1(1,2,6);
m1(2,0,7);
m1(2,1,8);
m1(2,2,9);
cout << m1;cout <<"\n"; // print Matrix
cout << "Element at Position (1,2) : " << m1(1,2) << endl;
Matrix m2(3,3);
m2 = m1;
cout << m2;cout <<"\n";
print(m2);
return 0;
}
int row, col;
cout << "Enter row size:";
cin >> row;
cout << "\ncol:";
cin >> col;
int *p_board[row];
for (int i=0; i < row; i++)
p_board[i] = new int[col];
for (int i=0; i < row; i++)
{
for (int j=0; j < col; j++)
{
p_board[i][j] = j;
cout << p_board[i][j] << " ";
}
cout << endl;
}
cout << endl << endl;
// in this method of declaring 2d array using new ..first you have created an array of pointers locally not using new so it will be created on stack not on heap then you have created an array using new on every index of p_board, these all arrays are created on heap but due to locally created p_board will make these array of no use becoz when you will use this method in any function and will try to return the p_board pointer from that function ..at that time p_board will be vanished from stack because it was created on stack ...but 2nd method is preferable to use/
int **p_p_board;
p_p_board = new int* [row];
for (int i=0; i < row; i++)
p_p_board[i] = new int[col];
for (int i=0; i < row; i++)
{
for (int j=0; j < col; j++)
{
p_p_board[i][j] = j;
cout << p_p_board[i][j] << " ";
}
cout << endl;
}
//in this method both array will be created on heap