I was wondering does anyone know how to convert a string into a 2d array? This was my attempt:
string w;
char s[9][9];
int p=0;
getline(cin, w);
while(p != w.size())
{
for (int k = 0; k < 9; k++)
{
for(int j = 0; j < 9; j++)
{
s[k][j] = w[p];
p++;
}
}
}
cout << "nums are: " << endl;
for(int k = 0; k < 9; k++)
{
for(int j = 0; j <9; j++)
{
cout << s[k][j];
}
}
But the numbers don't print out correctly. I want s[k][j] to print out everything in w but it simply prints out gibberish. I also noticed if i do string[81] then I get a whole bunch of errors. Could anyone help me? Thanks.
Try this:
const int NUM_ROWS = 9;
const int NUM_COLS = 9;
string w;
char s[NUM_ROWS][NUM_COLS];
getline(cin, w);
if (w.size() != (NUM_ROWS * NUM_COLS))
{
cerr << "Error! Size is " << w.size() << " rather than " << (NUM_ROWS * NUM_COLS) << endl;
exit(1);
}
for (int count = 0; count < w.size(); count++)
{
if (!isdigit(w[count]) && w[count] != '.')
{
cerr << "The character at " << count << " is not a number!" << endl;
}
}
for (int row = 0; row < NUM_ROWS; row++)
{
for(int col = 0; col < NUM_COLS; col++)
{
s[row][col] = w[col + (row * NUM_COLS)];
}
}
cout << "Nums are: " << endl;
for(int row = 0; row < NUM_ROWS; row++)
{
for(int col = 0; col < NUM_COLS; col++)
{
cout << s[row][col] << " ";
}
cout << endl;
}
Based on our chat, you might want this:
const int NUM_ROWS = 9;
const int NUM_COLS = 9;
string w;
char s[NUM_ROWS][NUM_COLS];
while (!cin.eof())
{
bool bad_input = false;
getline(cin, w);
if (w.size() != (NUM_ROWS * NUM_COLS))
{
cerr << "Error! Size is " << w.size() << " rather than " << (NUM_ROWS * NUM_COLS) << endl;
continue;
}
for (int count = 0; count < w.size(); count++)
{
if (!isdigit(w[count]) && w[count] != '.')
{
cerr << "The character at " << count << " is not a number!" << endl;
bad_input = true;
break;
}
}
if (bad_input)
continue;
for (int row = 0; row < NUM_ROWS; row++)
{
for(int col = 0; col < NUM_COLS; col++)
{
s[row][col] = w[col + (row * NUM_COLS)];
}
}
cout << "Nums are: " << endl;
for(int row = 0; row < NUM_ROWS; row++)
{
for(int col = 0; col < NUM_COLS; col++)
{
cout << s[row][col] << " ";
}
cout << endl;
}
}
You haven't described what you're trying to do very well and you haven't described the problem you're encountering, so the following is just based on guesses.
So it looks what you're trying to do is take a string like:
The quick brown fox jumped over the lazy dogs.
And put that into a 2D array like:
0 1 2 3 4 5 6 7 8
0 T h e q u i c k
1 b r o w n f o
2 x j u m p e d
3 o v e r t h e
4 l a z y d o g s
5 . x x x x x x x x
6 x x x x x x x x x
7 x x x x x x x x x
8 x x x x x x x x x
One thing wrong with your code is that as you copy values from w into s you don't ensure that the index p is actually within the bounds. You seem to have attempted to deal with this in the line that says while(p != w.size()); but that's an outer loop that does not protect p from being incremented out of bounds and used in the inner loops. Instead you'd have to put something like p++; if (p==w.size()) break; inside the inner most loop where you increment p. Or better yet, you should iterate over the string instead of over the array. Something like the following pseudo-code would replace your entire while(p){for(k){for(j){}}} set of loops.:
for(size_t i=0; i<w.size(); ++i) {
int k = compute target row from i
int j = compute target column from i
s[k][j] = w[i]
}
Also, here's some code to better visualize the array as you're debugging.
#include <iostream>
int main() {
char s[9][9] = {"The","quick","brown","fox","jumped","over","the","lazy","dogs."};
// your code to get input and copy it into the array goes here
//
// for(size_t i=0; i<w.size(); ++i) {
// int k = compute target row from i
// int j = compute target column from i
// s[k][j] = w[i]
// }
std::cout << " 0 1 2 3 4 5 6 7 8\n";
for (int i=0; i<9; ++i) {
std::cout << i;
for (int j=0; j<9; ++j)
std::cout << ' ' << s[i][j];
std::cout << '\n';
}
}
If you run this program without any changes the output should look like this:
0 1 2 3 4 5 6 7 8
0 T h e
1 q u i c k
2 b r o w n
3 f o x
4 j u m p e d
5 o v e r
6 t h e
7 l a z y
8 d o g s .
Related
I need help, I created a short little program a while ago where it would print a simple pyramid with "*" like this:
*
***
*****
but I decided to challenge myself and see if I could create a simple diamond shape like this:
*
***
*****
***
*
Here is my code so far.
I should also add that the value you input, for example 5, determines how big the diamond is.
#include <iostream>
#include <sstream>
using namespace std;
int main() {
int value = 0;
cout << "Please enter in a value: ";
cin >> value;
cout << endl;
for (int i = 0; i < value; i++) {
//print spaces v v v
for (int x = 0; x < (value - i - 1); x++) {
cout << " ";
}
//print * v v v
for (int y = 0; y < (2 * i + 1); y++) {
cout << "*";
}
cout << endl;
}
for (int i = 0; i < value; i++) {
int number = 0;
number+= 2;
//print spaces v v v
for (int x = 0; x < (value - value + i + 1); x++) {
cout << " ";
}
//print * v v v
for (int y = 0; y < (/*ATTENTION: What do I do here? Plz help*/); y++) {
cout << "*";
}
cout << endl;
}
return 0;
}
What I've been trying to do is figure out what to put inside the parenthesis where it says (//ATTENTION). I've been working for at least an hour trying to do random things, and one time it worked when I input 4, but not for 5, and it's just been very hard. This is key to building the diamond, try putting in just value and compile to see what happens. I need it to be symmetrical.
I need to know what to put inside the parenthesis please. I'm sorry this is very long but the help would be appreciated thanks.
I also apologize if my code is messy and hard to read.
int number = 0; and number+= 2;
value - value inside for (int x = 0; x < (value - value + i + 1); x++) {
are not required.
Inside the parenthesis, you can use
2*(value-i-1)-1
However, I would suggest you to first analyze the problem and then try to solve it instead of trying random things. For instance, let's consider the cases of even and odd inputs i.e., 2 and 3.
Even Case (2)
*
***
***
*
The Analysis
Row Index Number of Spaces Number of Stars
0 1 1
1 0 3
2 0 3
3 1 1
For row index < value
Number of Spaces = value - row index - 1
Number of Stars = 2 * row index + 1
For row index >=value
The number of spaces and stars are simply reversed. In the odd cases, the situation is similar too with a small exception.
Odd Case (3)
*
***
*****
***
*
The Analysis
Row Index Number of Spaces Number of Stars
0 2 1
1 1 3
2 0 5
3 1 3
4 2 1
The small exception is that while reversing, we have to ignore the row index = value.
Now, if we put the above analysis in code we get the solution
//Define the Print Function
void PrintDiamond(int rowIndex, int value)
{
//print spaces v v v
for (int x = 0; x < value - rowIndex -1; x++) {
cout << " ";
}
//print * v v v
for (int y = 0; y < 2 * rowIndex + 1; y++) {
cout << "*";
}
cout << endl;
}
And then inside main
//Row index < value
for (int i = 0; i < value; i++) {
PrintDiamond(i,value);
}
//For row index >= value reversing the above case
//value-(value%2)-1 subtracts 1 for even and 2 for odd cases
//ignore the row index = value in odd cases
for (int i = value-(value%2)-1; i >=0; i--) {
PrintDiamond(i,value);
}
#include <iostream>
#include <sstream>
using namespace std;
int main() {
int value = 0;
cout << "Please enter in a value: ";
cin >> value;
cout << endl;
for (int i = 0; i < value; i++) {
//print spaces v v v
for (int x = 0; x < (value - i - 1); x++) {
cout << " ";
}
//print * v v v
for (int y = 0; y < (2 * i + 1); y++) {
cout << "*";
}
cout << endl;
}
for (int i = 0; i < value-1; i++) {
// int number = 0;
// number+= 2;
// //print spaces v v v
for (int x = 0; x < i+1; x++) {
cout << " ";
}
//print * v v v
for (int y = 0; y < (2*(value-1-i)-1); y++) {
cout << "*";
}
cout << endl;
}
return 0;
}
I hope that you will get this .Also in the second for loop you were iterating it one extra time by iterating the loop upto value. But since the pyramid is symmetric so the no of rows in the pyramid will be 2*value-1.So I in the second loop i should vary upto value -1.
This code should resolve the problem:
#include <sstream>
using namespace std;
void printSpaces(int howMany) {
for(int i = 0; i < howMany; i++) cout << " ";
}
void figure(int size) {
bool oddSize = size % 2 == 1;
int center = size / 2;
int spaces = size / 2;
// If figure is of an odd size adjust center
if (oddSize) {
center++;
} else { // Else if figure is of even size adjust spaces
spaces--;
}
for (int i = 1; i <= center; i++) {
printSpaces(spaces);
for(int j = 0; j < 1 + (i - 1) * 2; j++) cout << "*";
cout << endl;
spaces--;
}
spaces = oddSize ? 1 : 0; // If the figure's size is odd number adjust spaces to 1
center -= oddSize ? 1 : 0; // Adjust center if it's an odd size figure
for(int i = center; i >= 1; i--) {
printSpaces(spaces);
for(int j = 0; j < 1 + (i - 1) * 2; j++)
cout << "*";
cout << endl;
spaces++;
}
}
int main() {
int value = 0;
while(value < 3) {
cout << "Please enter in a value (>= 3): ";
cin >> value;
cout << endl;
}
figure(value);
return 0;
}
i have a board of 10x10 and here his code:
for(int x = 0; x < 10; x++) // X
{
cout << 0;
for(int y = 0; y < 10; y++) // Y
{
cout << " " << 0;
}
cout << endl;
}
now I want to change 0 to 1 in the x,y location by user input.
how can I do that?
here is simply what I want to do ( in pictures ):
the user input is x = 2, y = 2 and the table changing from Table 1 Example to Table 2 Example ( as a new table ):
TABLE 1 Example | TABLE 2 Example
its just a curiosity question that I've been trying to make.
Get x0 and y0 before the loop using cin>> x0 and cin>> y0.
Inside the loop
if(x == x0 && y==y0)
cout << " " << 1;
else
cout << " " << 0;
The best way would be to keep all values in a two dimensional array. Then, play around with the
values of that array. After than, write the whole array once to the screen.
See the example below :
int matrix[10][10];
for(int i = 0; i < 10; i++)
for(int j = 0; j < 10; j++) matrix[i][j]=0;
matrix[2][3]=1;
matrix[3][4]=1;
matrix[4][5]=1;
for(int i = 0; i < 10; i++){
for(int j = 0; j < 10; j++){
cout<<matrix[i][j];
}
cout << endl;
}
you can print again the whole matrix and check the x,y pair before writing the 0 or the 1
for(int x = 0; x < 10; x++) // X
{
cout << 0;
for(int y = 0; y < 10; y++) // Y
{
//here verify the x,y against the user input
if(x == xUser && y == yUser)
{
cout << " " << 1;
} else{
cout << " " << 0;
}
}
cout << endl;
}
I'm working on a code that finds all saddle points in a matrix. Both smallest in their row and biggest in their column, and biggest in their row and smallest in their column fall under the definition (of my university) of a saddle point. Being a beginner I managed to get half of it done (finding saddle points which are smallest in their row and biggest in their column) by copying parts of what we've done in class and typing it myself. I have been stuck on it for quite some time and can't figure how to add the saddle points which are biggest in their row and smallest in their column to the program.
This is what I have so far:
#include <iostream>
#include <cstdlib>
using namespace std;
int a[10][10];
int x, y;
int pos_max(int j) //saddle points check
{
int max = 0;
for (int i = 1; i <= x - 1; i++) {
if (a[i][j] > a[max][j]) {
max = i;
}
}
return max;
}
int main() {
cout << "Enter the number of rows: ";
cin >> x;
cout << "Enter the number of columns: ";
cin >> y;
cout << "----------------------------" << endl;
for (int i = 0; i <= x - 1; i++) //input of the matrix
for (int j = 0; j <= y - 1; j++) {
cout << "a[" << i + 1 << ", " << j + 1 << "] = ";
cin >> a[i][j];
}
cout << "----------------------------\n";
for (int i = 0; i <= x - 1; i++) //visualization of the matrix
{
for (int j = 0; j <= y - 1; j++)
cout << a[i][j] << " ";
cout << endl;
}
cout << "----------------------------\n";
int r;
int flag = 0;
int i = y;
for (int j = 0; j <= y - 1; j++) {
r = pos_max(j);
for (i = 0; i <= y - 1; i++) {
if (a[r][i] < a[r][j]) {
break;
}
}
if (i == y) {
cout << "Saddle points are: ";
cout << "a[" << r + 1 << ", " << j + 1 << "] = " << a[r][j] << "\n";
flag = 1;
}
}
if (flag == 0) {
cout << "No saddle points\n";
}
cout << "----------------------------\n";
return 0;
}
First, there is a logical error with your code. In the pos_max function, it will return the index of the element which is maximum in the column. There can be a case when there are multiple maximum with the same value in the column, however, it returns the one which is not the minimum in the row, hence your program won't be able to print that saddle point.
To solve this, you can either return an array of all indices which are maximum in a column and then check for each of those points if it's minimum in their respective column, but I think it's not a very elegant solution. In any case, you will again have to write the entire code for the other condition for saddle points, minimum in column and maximum in row.
Hence, I would suggest a change in strategy. You create 4 arrays, max_row, max_col, min_row, min_col, where each array stores the minimum / maximum in that row / column respectively. Then you can traverse the array and check if that point satisfies saddle point condition.
Here is the code:
#include <iostream>
#include <cstdlib>
using namespace std;
int a[10][10];
int max_row[10], max_col[10], min_row[10], min_col[10];
int x, y;
bool is_saddle(int i, int j) {
int x = a[i][j];
return (max_row[i] == x && min_col[j] == x) || (min_row[i] == x && max_col[j] == x);
}
int main() {
/* code to input x, y and the matrix
...
*/
/* code to visualize the matrix
...
*/
/* populating max and min arrays */
for (int i = 0; i <= x-1; ++i) {
max_row[i] = a[i][0], min_row[i] = a[i][0];
for (int j = 0; j <= y-1; ++j) {
max_row[i] = max(max_row[i], a[i][j]);
min_row[i] = min(min_row[i], a[i][j]);
}
}
for (int j = 0; j <= y-1; ++j) {
max_col[j] = a[0][j], min_col[j] = a[0][j];
for (int i = 0; i <= x-1; ++i) {
max_col[j] = max(max_col[j], a[i][j]);
min_col[j] = min(min_col[j], a[i][j]);
}
}
/* Check for saddle point */
for (int i = 0; i <= x-1; ++i) {
for (int j = 0; j <= y-1; ++j) {
if (is_saddle(i, j)) {
cout << "Saddle points are: ";
cout << "a[" << i + 1 << ", " << j + 1 << "] = " << a[i][j] << "\n";
flag = 1;
}
}
}
if (flag == 0) {
cout << "No saddle points\n";
}
cout << "----------------------------\n";
return 0;
}
#include <iostream>
using namespace std;
int getMaxInRow(int[][5], int, int, int);
int getMinInColumn(int[][5], int, int, int);
void getSaddlePointCordinates(int [][5],int ,int );
void getInputOf2dArray(int a[][5], int, int);
int main()
{
int a[5][5] ;
int rows, columns;
cin >> rows >> columns;
getInputOf2dArray(a, 5, 5);
getSaddlePointCordinates(a,rows,columns);
}
void getInputOf2dArray(int a[][5], int rows, int columns)
{
for (int i = 0; i < rows; i = i + 1)
{
for (int j = 0; j < columns; j = j + 1)
{
cin >> a[i][j];
}
}
}
void getSaddlePointCordinates(int a[][5],int rows,int columns)
{
int flag = 0;
for (int rowNo = 0; rowNo < 5; rowNo++)
{
for (int columnNo = 0; columnNo < 5; columnNo++)
{
if (getMaxInRow(a, rows, columns, rowNo) == getMinInColumn(a, rows, columns, columnNo))
{
flag = 1;
cout << rowNo << columnNo;
}
}
}
if (flag == 0)
cout << "no saddle point";
cout << "\n";
}
int getMaxInRow(int a[][5], int row, int column, int rowNo)
{
int max = a[rowNo][0];
for (int i = 1; i < column; i = i + 1)
{
if (a[rowNo][i] > max)
max = a[rowNo][i];
}
return max;
}
int getMinInColumn(int a[][5], int row, int column, int columnNo)
{
int min = a[0][columnNo];
for (int i = 1; i < row; i = i + 1)
{
if (a[i][columnNo] < min)
min = a[i][columnNo];
}
return min;
}
just take the reference arr(ref[size]) // memorization method to check the minimum and maximum value in it.
Here is the Code Implementation with time complexity O(n *n) & space complexity O(n):
#include <bits/stdc++.h>
using namespace std;
#define size 5
void util(int arr[size][size], int *count)
{
int ref[size]; // array to hold all the max values of row's.
for(int r = 0; r < size; r++)
{
int max_row_val = arr[r][0];
for(int c = 1; c < size; c++)
{
if(max_row_val < arr[r][c])
max_row_val = arr[r][c];
}
ref[r] = max_row_val;
}
for(int c = 0; c < size; c++)
{
int min_col_val = arr[0][c];
for(int r = 1; r < size; r++) // min_val of the column
{
if(min_col_val > arr[r][c])
min_col_val = arr[r][c];
}
for(int r = 0; r < size; r++) // now search if the min_val of col and the ref[r] is same and the position is same, if both matches then print.
{
if(min_col_val == ref[r] && min_col_val == arr[r][c])
{
*count += 1;
if((*count) == 1)
cout << "The cordinate's are: \n";
cout << "(" << r << "," << c << ")" << endl;
}
}
}
}
// Driver function
int main()
{
int arr[size][size];
for(int i = 0; i < size; i++)
{
for(int j = 0; j < size; j++)
cin >> arr[i][j];
}
int count = 0;
util(arr, &count);
if(!count)
cout << "No saddle points" << endl;
}
// Test case -> Saddle Point
/*
Input1:
1 2 3 4 5
6 7 8 9 10
1 2 3 4 5
6 7 8 9 10
0 2 3 4 5
Output1:
The cordinate's are:
(0,4)
(2,4)
(4,4)
Input2:
1 2 3 4 5
6 7 8 9 1
10 11 12 13 14 15
16 17 18 19 20
21 22 23 24 25
Output2:
No saddle points
*/
I am currently working on a task which says the following:
Input a two-dimensional array A (m,n) [m < 10, n < 20]. In the n + 1 column calculate the sum of the rows, and in the m + 1 row the product of the columns. Print out the resulting matrix.
According to my understanding of this task, at the end of each column must be the sum of according rows (so on the right hand side), and the product of the column (at the end/bottom?).
This task is so confusing I do not know where to start. I found some code that covers the idea but does not include the product and it does not display these values as the task asks me to:
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int a[3][3];
int i, j, s = 0, sum = 0;
cout << "Enter 9 elements of 3*3 Matrix \n";
for (i = 0; i < 3; i++)
for (j = 0; j < 3; j++)
cin >> a[i][j];
cout << "Matrix Entered By you is \n";
for (i = 0; i < 3; i++)
{
for (j = 0; j < 3; j++)
cout << a[i][j] << " ";
cout << endl;
}
for (i = 0; i < 3; i++)
{
for (j = 0; j < 3; j++)
s = s + a[i][j];
cout << "sum of" << i + 1 << " Row is" << s;
s = 0;
cout << endl;
}
cout << endl;
for (i = 0; i < 3; i++)
{
for (j = 0; j < 3; j++)
s = s + a[j][i];
cout << "sum of" << i + 1 << " Column is" << s;
s = 0;
cout << endl;
}
cout << endl;
for (i = 0; i < 3; i++)
sum = sum + a[i][i];
cout << "Sum of Diagnols Elements is \n" << sum;
getch();
}
We beginners should help each other.
Here you are
#include <iostream>
#include <iomanip>
int main()
{
const size_t M = 10;
const size_t N = 20;
int a[M][N] = {};
std::cout << "Enter number of rows: (less than " << M << "): ";
size_t m;
std::cin >> m;
if (!(m < M) || (m == 0)) m = M - 1;
std::cout << "Enter number of columns: (less than " << N << "): ";
size_t n;
std::cin >> n;
if (!(n < N) || (n == 0)) n = N - 1;
std::cout << std::endl;
for (size_t i = 0; i < m; i++)
{
std::cout << "Enter " << n
<< " numbers for the row " << i << ": ";
for (size_t j = 0; j < n; j++) std::cin >> a[i][j];
}
for (size_t j = 0; j < n; j++) a[m][j] = 1;
for (size_t i = 0; i < m; i++)
{
for (size_t j = 0; j < n; j++)
{
a[i][n] += a[i][j];
a[m][j] *= a[i][j];
}
}
std::cout << std::endl;
for (size_t i = 0; i < m + 1; i++)
{
for (size_t j = 0; j < n + 1; j++)
{
std::cout << std::setw(3) << a[i][j] << ' ';
}
std::cout << '\n';
}
std::cout << std::endl;
}
The program output might look like
Enter number of rows: (less than 10): 3
Enter number of columns: (less than 20): 3
Enter 3 numbers for the row 0: 1 2 3
Enter 3 numbers for the row 1: 4 5 6
Enter 3 numbers for the row 2: 7 8 9
1 2 3 6
4 5 6 15
7 8 9 24
28 80 162 0
So you have to declare an array with 10 rows and 20 columns. The user should enter the dimensions of the array that are correspondingly less than 10 and 20. One row and one column are reserved for sums and products.
It is desirable that the array would be initially initialized by zeroes.
int a[M][N] = {};
In this case you need not to set the last column with zeroes as you have to do with last row initializing it with ones.
That is all.:)
Start with the declaration: make sure that your program works with m×n matrix, not simply a 3×3 matrix. Since m and n have limits of 10 and 20, and because you must add an extra row and a column to the result, the declaration should be
int a[11][21];
You also need to declare m and n, have end-user enter them, and validate them to be within their acceptable ranges:
int m, n;
cin >> m >> n;
... // Do the validation
Now you can rewrite your loops in terms of m and n, rather than using 3 throughout your code.
With these declarations in place, you can total the numbers in place, i.e. for each row r you would write
for (int i = 0 ; i != n ; i++) {
a[r][n+1] += a[r][i];
}
Similarly, you would compute the product (don't forget to start it with the initial value of 1, not 0).
At the end you would print an (m+1)×(n+1) matrix to complete the task.
Solution : use this kind of functions for your array after making it global.
void Adder(int row, int colum)
{
for (int i = 0; i < row - 1; i++)
{
int temp = 0;
for (int j = 0; j < colum - 1; j++)
{
temp += a[i][j]; // added all other than last one
}
a[i][j] = temp; // assigned to last one in row
}
}
void Mul(int row, int colum)
{
for (int i = 0; i < colum- 1; i++)
{
int temp = 1;
for (int j = 0; j < row - 1; j++)
{
temp *= a[j][i]; // multiplied all element other than last one
}
a[j][i] = temp; // assigned to last one in column
}
}
I am trying to find min (by row) and max (by column) element in two-dimensional (4,4) array and then store them in new array (5,5).
That is how it should look for new array (5,5):
1 2 3 4 min
5 6 7 8 min
4 4 4 5 min
3 5 5 6 min
m m m m 0
*m - max
Here it is the entire code:
#include <iostream>
using namespace std;
int main() {
int A[4][4];/*First array*/
int i, j;
for (i = 0; i < 4; i++)
for (j = 0; j < 4; j++) {
cout << "\n A[" << i + 1 << "][" << j + 1 << "]=";
cin >> A[i][j];
}
for (i = 0; i < 4; i++) {
for (j = 0; j < 4; j++)
cout << A[i][j] << "\t";
cout << "\n";
}
{
int min[4];/* find min on each row*/
for (i = 0; i < 4; i++) {
min[i] = A[0][i];
for (j = 1; j < 4; j++) {
if (min[i] > A[i][j])
min[i] = A[i][j];
}
}
int newarr[5][5];/* here i create the new array 5,5)*/
int max[5] = { 1,2,3,4,5 };
for (i = 0; i < 4; i++) {
for (j = 0; j < 4; j++) {
newarr[i][j] = A[i][j];
newarr[i][5] = max[i];
}
}
for (j = 0; j < 4; j++)
newarr[5][j] = min[j];
cout << newarr[5][j] << "\t";
cout << "\n";
}
}
I put random elements to max. Because so far I only test. But once I started my program it show correct only the first array. And where should be the new array it shows zero. Here it is the outcome of the debugging:
5 4 3 1
5 6 7 9
4 2 3 9
4 8 4 6
0
How to fix it?
And how to put zero in the last element (as you can see in the first table for the new array).
You can do it in a single pass over all the elements:
// returns a (rows+1, cols+1) matrix
int* make_min_max_vectors(const int* arr, size_t rows, size_t cols) {
size_t out_size = (rows+1) * (cols+1);
int* res = malloc(out_size * sizeof(int));
// set up initial values in the right/bottom vectors
res[out_size - 1] = 0;
for (size_t col = 0; col < cols; ++col)
res[rows*(cols+1) + col] = INT_MIN;
for (size_t row = 0; row < rows; ++row)
res[row*(cols+1) + cols] = INT_MAX;
for (size_t row = 0; row < rows; ++row)
for (size_t col = 0; col < cols; ++col) {
const int* cell = &arr[row*cols + col];
res[row*(cols+1) + col] = *cell; // copy
if (*cell < res[row*(cols+1) + cols]) // min
res[row*(cols+1) + cols] = *cell;
if (*cell < res[rows*(cols+1) + col]) // max
res[rows*(cols+1) + col] = *cell;
}
}
return res;
}
That is, you simply run over all the input elements once, copying each one to the output plus checking if each one is less than its row minimum or greater than its column maximum. You don't need temporary vectors for min and max, and you don't need to run over the entire input twice.
John Swincks answer is awesome (+1'd) and I would definitely recommend his answer simply for future proofing your code. I am relatively new to programming myself and understand how intimidating the above code can seem (especially malloc). Because of this I have written the a version of your code that is very similar however gets rid of the need to have the original 4x4 matrix and instead uses a 5x5. The code is shown below, let me know if you have any issue with it. The code can be compiled as is and will demonstrate what you are trying to acheive.
#include <iostream>
int main()
{
// Initialised inline to simplify example.
int A[5][5] = {0};
// Only uses 4x4 of the 5x5 array meaning that you don't need to use two arrays.
for (int x = 0; x < 4; ++x)
{
for (int y = 0; y < 4; ++y)
{
std::cout << "Enter in value for row " << x << ", column " << y << ".\n";
std::cin >> A[x][y];
}
}
std::cout << "Input:" << std::endl;
for (int x = 0; x < 4; ++x)
{
for (int y = 0; y < 4; ++y)
{
std::cout << A[x][y] << "\t";
}
std::cout << "\n";
}
// Finds the max down each column in the array
for (int x = 0; x < 4; ++x)
{
for (int y = 0; y < 4; ++y)
{
if (A[x][4] < A[x][y])
A[x][4] = A[x][y];
}
}
// Finds the min across the array (along row)
for (int y = 0; y < 4; ++y)
{
for (int x = 0; x < 4; ++x)
{
// Assign the min to a value in that row.
A[4][y] = A[1][y];
if (A[4][y] > A[x][y])
A[4][y] = A[x][y];
}
}
std::cout << "Output:" << std::endl;
for (int x = 0; x < 5; ++x)
{
for (int y = 0; y < 5; ++y)
{
std::cout << A[x][y] << "\t";
}
std::cout << "\n";
}
std::cin.get();
std::cin.get();
return 0;
}
Edit: Sample input and output for clarification.
Input:
1 2 3 4
5 62 4 6
8 9 1 2
4 6 8 9
Output:
1 2 3 4 1
5 62 4 6 4
8 9 1 2 1
4 6 8 9 4
8 62 8 9 0