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";
}
Related
Here is the coding below :) I have also commented on some parts so that it is easier to understand the output of the code.
I have a slight idea that I need to use an "if statement" with "rand()%" in order to make sure that the program knows we want to calculate the sum of 1s and -1s only. for e.g using "rand()%2-1" can help with getting the total sum of 1s outputted in the table. Again, I'm not sure if this idea will work or not.
So the program should output something like "The amount of 1s in the table is 5 and the amount of -1s in the table is 3" for the first time its ran. Then when it is ran the second time, it could output something like "The amount of 1s in the table is 2 and the amount is -1s in the table is 5"
Sorry for any confusions and All your help will be highly appreciated :) :)
#include<iostream>
#include<iomanip>
#include<ctime>
using namespace std;
int main() {
srand(time(0));
const int ROWS=3;
const int COLS=4;
int table[ROWS][COLS];
for (int i = 0; i < ROWS; i ++) {
for (int j = 0; j < COLS; j++) {
table[i][j] = rand()%3-1;
}
}
for (int i = 0; i < ROWS; i ++) {
for (int j = 0; j < COLS; j++)
cout << setw(3) << table[i][j];
cout << endl;
}
bool checkTable [ROWS][COLS];
for (int i = 0; i < ROWS; i ++) {
for (int j = 0; j < COLS; j++) {
if (table[i][j] !=0) {
checkTable[i][j] = true;
}
else{
checkTable[i][j] = false;
}
//The output in the line below is the final line outputted by the
console. This prints out "1" if there is a value in the index within
the table provided above (the value is represented by 1 or -1), and
prints out "0" if there is no value in the index (represented by 0)
cout << " " << checkTable[i][j];
}
}
return 0;
}
[...] for e.g using "rand()%2-1" can help with getting the total sum of 1s
outputted in the table.
I dont really understand what you mean by that. Counting and randomness dont go well together. I mean of course you can fill a matrix with random numbers and then do some counting, but rand() wont help anything for the counting.
You need something as simple as that:
int main() {
srand(time(0));
const int ROWS=3;
const int COLS=4;
int table[ROWS][COLS];
for (int i = 0; i < ROWS; i ++) {
for (int j = 0; j < COLS; j++) {
table[i][j] = rand()%3-1;
}
}
unsigned ones_counter = 0;
for (int i = 0; i < ROWS; i ++) {
for (int j = 0; j < COLS; j++) { // dont forget the bracket
cout << setw(3) << table[i][j];
if (table[i][j] == 1) { ones_counter++;} // <- this is counting
}
cout << endl;
}
std::cout << "number of 1s in the table : " << ones_counter << "\n";
....
first off sorry for the slightly messy code as I was fiddling with different things to try to get it to work. As of now, my code can multiply Square Matrices just fine; however, it has difficulties computing Non Square Matrices. My best guess after debugging is how i re-size my vectors, and that there is an out of bounds error which causes the program to crash. Any help would be appreciated, my code should be able to Multiply any Vectors sizes withing Matrix Multiplication Rules.
I also would like to note this is a HW assignment so I am limited to how I can build my code, basically ONLY using vectors, cannot write your own class etc....
#include <iostream>
#include <vector>
using namespace std;
void multiply_matrices(vector <vector<int> > matrix1,vector <vector<int> > matrix2, int cols, int rows2);
void setMatrix(vector <vector<int> > &matrix, int rows, int cols);
int main()
{
int rows, cols, rows2, cols2;
vector< vector<int> > matrix, matrix2;
cout<<"Please enter the number of Rows and Columns for your first Matrix."<<endl;
cout<<"Rows: ";
cin>>rows;
cout<<"Columns: ";
cin>>cols;
matrix.resize(cols, vector<int>(rows,0)); //Saw this online so not sure how it works but it works, if i take out one i cant do row<column and vice versa
matrix.resize(rows, vector<int>(cols,0));
cout<<"Size has been declared, please enter data for your matrix"<<endl;
setMatrix(matrix,rows,cols);
cout<<"Second Matrix Automatically Set by Matrix Multiplication Rule"<<endl; //Just automatically sets second matrix as per Matrix Multiplication Rule
rows2=cols;
cols2=rows;
cout<<"Second Matrix Size is: " << rows2 << " by " << cols2 << endl;
matrix2.resize(cols2, vector<int>(rows2,0));
matrix2.resize(rows2, vector<int>(cols2,0));
setMatrix(matrix2,rows2,cols2);
cout<<"Multiplied Matrix is:"<<endl;
multiply_matrices(matrix,matrix2,cols,rows2);
system("PAUSE");
return 0;
}
void setMatrix(vector <vector<int> > &matrix, int rows,int cols){
int num;
for(int i = 0; i < rows; i ++)
{
for (int j = 0; j < cols; j++)
{
cout << "Enter Value for Row " << (i+1) << " Column " << (j+1) << ": ";
cin>>num;
matrix[i][j]=num;
}
cout << endl;
}
/*for(int i = 0; i < rows; i ++)
{
for (int j = 0; j < cols; j++)
{
cout << matrix[i][j] << " ";
}
cout << endl;
}
*/
}
void multiply_matrices(vector <vector<int> > matrix1,vector <vector<int> > matrix2, int cols, int rows2){
vector< vector<int> > tempMatrix;
int newrows=rows2;
int newcols=cols;
int sum;
tempMatrix.resize(newcols, vector<int>(newrows,0)); //Resizing new matrix to proper size, so if it was (2x3)(3x2), new matrix is (3x3)
for (int i = 0; i < newrows; i++) //This Works Fine for Square Matrixes but not for others, i have no clue how to fix it?
{
for (int j = 0; j < newcols; j++){
//sum=0;
for (int u = 0; u < newcols; u++)
{
//sum+=matrix1[i][u] * matrix2[u][j];
//tempMatrix[i][j]=sum;
tempMatrix[i][j] += matrix1[i][u] * matrix2[u][j];
}
}
}
for(int i = 0; i < newrows; i ++)
{
for (int j = 0; j < newcols; j++)
{
cout << tempMatrix[i][j] << " ";
}
cout << endl;
}
}
Initialize your first matrix like this:
matrix.resize(rows, vector<int>(cols,0));
and your second like this:
matrix2.resize(rows2, vector<int>(cols2,0));
where rows2 = cols. Note that there is no "multiplication rule" that implies cols2 == rows.
The problem is in your multiply_matrices function where the loops should be
for (int i = 0; i < rows; i++) // or matrix1.size()
for (int j = 0; j < cols2; j++) // or tempMatrix[i].size()
for (int u = 0; u < cols; u++) // or rows2 or matrix1[i].size()
but as already stated in the comments, it would be better to use vector::size() instead of passing the sizes as additional parameters.
Also, if you multiply (2x3)(3x2), the result is (2x2):
tempMatrix.resize(rows, vector<int>(cols2,0));
There is nothing wrong with the resize() function. What may be wrong is that you ignore the maximum size and rely solely on variables that are passed to your functions.
For example, your setMatrix function is passed rows and cols, but this is not necessary.
The function should be rewritten using only the matrix to provide the sizes to the loops:
void setMatrix(vector<vector<int> > &matrix)
{
int num;
for(int i = 0; i < matrix.size(); ++i)
{
for (int j = 0; j < matrix[i].size(); ++j)
{
cout << "Enter Value for Row " << (i+1) << " Column " << (j+1) << ": ";
cin>>num;
matrix[i][j] = num;
}
cout << endl;
}
}
You have the same issue with multiply_matrix. What you should be doing is ensure that you're loops use the return value of vector::size(), which you do not do. The problem is here:
for (int i = 0; i < newrows; i++)
{
for (int j = 0; j < newcols; j++)
{
for (int u = 0; u < newcols; u++)
{
tempMatrix[i][j] += matrix1[i][u] * matrix2[u][j];
You sized the tempMatrix to newrows rows and newcols columns. But how do you know that matrix1 and matrix2 have at least newrows rows and newcols columns? You don't know, but you just assume they do.
So you either need to ensure that the size of matrix1 and matrix2 can accommodate the number of rows/columns, or you throttle those loops to use the minimum rows/columns.
Overall, the issue is that nowhere do you use vector::size() in your code that I see. So start to use size() to your advantage -- don't create superfluous (and possibly erroneously set) variables that supposedly denote the sizes of the rows and columns.
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;
}
I am learning C++ by myself,by solving different problems.
I am trying to solve problem which was originally designed for Pascal in C++.
It should ask user to input 3 integers M,N and q.
Then it should make 2d array of integers with size MxN, where all the elements of (I=I,...M) line will be the members of geometrical progression with first element equal to number of line (I) and denominator q.
I wanted to create a dynamic massive, but I realized that it won't really work with two undefined integers. So, I tried vectors. I guess that I created them in a right way, but I've got no idea how to make a geometrical progression.
Here is my code:
#include <iostream>
#include <vector>
using namespace std;
int main()
{
int m, n, q;
cout << "Enter the number for M \n";
cin >> m;
if (cin.fail())
{
cin.clear();
cin.ignore();
cout << "This is not a number! " << endl;
system("pause");
return 0;
}
cout << "Enter the number for N \n";
cin >> n;
if (cin.fail())
{
cin.clear();
cin.ignore();
cout << "This is not a number! " << endl;
system("pause");
return 0;
}
cout << "Enter the number for Q \n";
cin >> q;
if (cin.fail())
{
cin.clear();
cin.ignore();
cout << "This is not a number! " << endl;
system("pause");
return 0;
}
int** matrix;
matrix = new int*[m];
for (int i = 0; i < m; i++)
matrix[i] = new int[n];
for (int i = 0; i < m; i++)
{
matrix[i][0] = i + 1;
}
for (int i = 0; i < m; i++)
{
for (int j = 1; j < n; j++)
{
matrix[i][j] = (i + 1)*pow(i, j);
cout << matrix[i][j];
}
}
system("pause");
return 0;
}
Note: You can create a two dimensional array of a variable size, although it involves memory allocation and is slightly ugly.
int** matrix;
matrix = new int*[M];
for (int i = 0; i < M; i++)
matrix[i] = new int[N];
That's the code to create an array of size MxN.
Don't forget to deallocate your memory like so:
for (int i = 0; i < M; i++)
delete matrix[i];
delete matrix;
As far as your question about the geometric progression, I am unsure of what you are asking. When you say geometric progression do you refer to something along the lines of 2 10 50 250 etc.? I am not sure what you mean by "lines" as you don't refer to any such variable in your code.
EDIT
So once the MxN matrix is created, iterate through the rows and initialize the rows like so:
for (int i = 0; i < M; i++)
{
matrix[i][0] = i+1;
}
This should set the first column of each row to the correct number.
Then something along the lines of this should fill out the rest of the geometric progression:
for (int i = 0; i < M; i++)
{
for (int j = 1; j < N; j++)
{
matrix[i][j] = (i+1)*pow(r,j);
//note that you'll probably have to do some typecasting
//p.s. I'm not 100% sure that this is the correct formula
}
}
I think this is what you are looking for. Let me know if it works because I haven't tested it myself.
Print the matrix like this:
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
std::cout << matrix[i][j] << " ";
}
std::cout << "\n";
}
I have to create a program that allows a user to fill in a (partial) Latin Square of order 4. You can use 0's to represent empty cells. The user will give the number to place, the row and column. The number should only be placed if it does not violate the properties of a partial Latin square and it shouldn't rewrite numbers that have already been placed.
I have an matrix that is outputting all zeroes now. So next I have to replace each of these values by what the user is inputting. The problem is I don't know how to do this.
Here is my code:
#include <iostream>
using namespace std;
const int ORDER = 4;
void fill (int m[], int order);
void outputMatrix (int m[], int order);
void replaceValue (int m[], int order, int n, int row, int column);
int main(){
int matrix[ORDER];
int row;
int column;
int n;
fill (matrix, ORDER);
outputMatrix (matrix, ORDER);
do {
cout << "Enter the number to place, the row and the column, each seperated by a space: ";
cin >> n;
cin >> row;
cin >> column;
}while (n > 0 || n <= ORDER);
if (n <= 0 || n >= ORDER){
cout << "Thank you";
cout << endl;
}
return 0;
}
void fill (int m[], int order){
for (int i = 0; i < order*order; i++){
m[i] = 0;
}
}
void outputMatrix (int m[], int order){
int c = 0;
for (int i = 0; i < order*order; i++){
c++;
cout << m[i] << ' ';
if (c == order){
cout << endl;
c = 0;
}
}
cout << endl;
}
void replaceValue (int m[], int order, int n, int row, int column){
for (int i = 0; i < order; i++){
m[order] = m[row][column];
m[row][column] = n;
}
}
How do I replace values in a Matrix in C++?
If you have a matrix, matrix[row][col] = value; would do the trick. However, I see that you allocate a single array. Make sure you look at this.
EDIT:
I looked closer at you code and you are doing some things wrong.
First:
matrix[ORDER]
will create a single array of ORDER values. If you want and ORDER by ORDER matrix try:
matrix[ORDER][ORDER]
Second:
You are calling:
void fill (int m[], int order){
for (int i = 0; i < order*order; i++){
m[i] = 0;
}
}
with an of size 4 and order == 4. This will loop outside the array and give you problems.
Try something like:
matrix[ORDER][ORDER];
for (int row = 0; row != ORDER; ++row)
{
for (int col = 0; col != ORDER; ++col)
{
matrix[row][col] = 0;
}
}
Hope this helps.
You can't really write arr[i][j] if arr is defined as arr[]. There's no information about the length of the row (how many columns there are).
You could use arrays of type arr[][4], and write your functions like so:
// The & is to pass by reference.
void print(int (&arr)[][4], int length)
{
for(int i = 0; i < length; i++) {
for(int j = 0; j < 4; j++) {
cout << arr[i][j] << " ";
}
cout << endl;
}
}
But in my opinion for a low-order multidimensional array like this one, using a typedef for a vector of vectors is the better option:
typedef vector<vector<int> > Matrix;
void print(Matrix& arr)
{
for(int i = 0; i < arr.size(); i++) {
for(int j = 0; j < arr[i].size(); j++) {
cout << arr[i][j] << " ";
}
cout << endl;
}
}
In either case, writing arr[i][j] = k will behave as you expect.
The easiest way to clear/zero your matrix is that:
memset( &matrix, 0, sizeof(matrix));
;-)