I have an array of integer values that is of one dimension.I need to print it as columns.
Although I can print the values as columns but it pritns more than 5 values. The ideal output would be like this:
1 1 1
1 1
How would i do this?
For example, my try is this:
int main(){
int array[5] = {1,1,1,1,1};
cout<<"array printed in the form of columns: "<<endl;
for ( int i = 0; i < 5; i++ ){
cout<<setw(3)<< array[i]<<endl<<setw(3)<<array[i];
}
return 0;
}
If as columns, then it the
for (int i=0; i<5; i++) {
cout << a[i] << endl;
}
would be sufficient.
But you probably want the row-representation. (1 1 1 1 1, right?). Then
for (int i=0; i<5; i++) {
cout << a[i] << " ";
}
would suffice. Or, you can use a pointer
int * p_array = array;
and then, inside the loop
cout << *(p_array + i) << " ";
EDIT:
That was for your unedited question :-) For the new output -> you can follow the answer of the Cigien
I guess you could simply insert an end line after each 3(or any number of columns that you want) element printed.
Here is an exemple with a longer array :
int main()
{
int colNum = 3;
int array[7] = {1,1,1,1,1,1,1};
int len = (sizeof(array)/sizeof(array[0]));
cout<<"array printed in the form of columns: " << endl;
for ( int i = 0; i < len ; i++ )
{
cout << array[i];
if ((i+1)%colNum==0) cout << '\n';
}
return 0;
}
You can just write 2 loops:
for ( int i = 0; i < 3; ++i ) {
cout << setw(3) << array[i]; // first row
}
cout << endl; // next row
for ( int i = 3; i < 5; ++i ) {
cout << setw(3) << array[i]; // second row
}
Related
Write a program that reads 12 integers into a 2D integer array with 4 rows and 3 columns. The program then outputs the 2D array in reverse order according to both rows and columns.
Ex: If the input is:
5 7 3
6 4 3
5 6 9
5 2 8
then the output is:
8 2 5
9 6 5
3 4 6
3 7 5
For coding simplicity, output a space after every integer, including the last one on each row.
#include <iostream>
using namespace std;
int main() {
const int ROWS = 4;
const int COLS = 3;
int arr[ROWS][COLS];
int i, j;
for(i = 0; i < ROWS; i++){
for(j = 0; j < COLS; j++){
cin>>arr[i][j];
}
}
cout << arr[3][2] << " " << arr[3][1] << " " << arr[3][0] << " " << endl;
cout << arr[2][2] << " " << arr[2][1] << " " << arr[2][0] << " "<< endl;
cout << arr[1][2] << " " << arr[1][1] << " " << arr[1][0] << " "<< endl;
cout << arr[0][2] << " " << arr[0][1] << " " << arr[0][0] << " "<< endl;
return 0;
}
I ended up having to hardcode this question because I couldnt find a way to reverse the 2D array with a loop and get it to be outputted in the form of a graph. Is there a way i could reverse the 2D array using for loops and would it be possible to be able to change the amount of rows and columns and still output the corresponding graph of values?
try this:
#include <iostream>
using namespace std;
int main() {
const int ROWS = 4;
const int COLS = 3;
int arr[ROWS][COLS];
int i, j;
for (i = 0; i < ROWS; i++) {
for (j = 0; j < COLS; j++) {
cin >> arr[i][j];
}
}
// output the reversed array
for (int i = ROWS - 1; i >= 0; i--) {
for (int j = COLS - 1; j >= 0; j--) {
cout << arr[i][j] << " ";
}
cout << endl;
}
return 0;
}
You can reverse a 2D array using nested for loops, try
#include <iostream>
using namespace std;
int main() {
const int ROWS = 4;
const int COLS = 3;
int arr[ROWS][COLS];
int i, j;
// Input the values into the 2D array
for(i = 0; i < ROWS; i++) {
for(j = 0; j < COLS; j++) {
cin >> arr[i][j];
}
}
// Reverse the rows and columns of the 2D array
for(i = ROWS - 1; i >= 0; i--) {
for(j = COLS - 1; j >= 0; j--) {
cout << arr[i][j] << " ";
}
cout << endl;
}
return 0;
}
As mentioned in comments below if you don't know ROWS and COLS size at compile time dynamically allocate the memory for 2D array(arr) in C++ using new operator.
There is very little point reading the data into a 2D array for this program. A std::vector would do the trick, sized with ROWS * COLS values. You then have the benefit of being able to read those dimensions from the user, which addresses the second part of your question.
size_t size = ROWS * COLS;
// Read data
std::vector<int> data;
data.reserve(size);
for (int value; std::cin >> value; )
{
data.push_back(value);
}
// Validate data
if (data.size() != size)
{
std::cerr << "Unexpected end of input!\n";
return EXIT_FAILURE;
}
When outputting, you can use a reverse iterator through the vector, and simply write a newline every COLS values.
// Output in reverse
int col = 0;
for (auto it = data.rbegin(); it != data.rend(); it++)
{
std::cout << *it << " ";
if (++col == COLS)
{
std::cout << "\n";
col = 0;
}
}
You can even easily fix the "space at the end of the line" problem by adjusting your output loop as follows:
// Output in reverse
int col = 0;
for (auto it = data.rbegin(); it != data.rend(); it++)
{
std::cout << *it;
if (++col == COLS)
{
std::cout << "\n";
col = 0;
}
else
{
std::cout << " ";
}
}
I have created a 2d array, so lets say as I did in the code below the array elements shows like this:
3 4
8 2
I want to compare the" ROWS" and get the minimum number, like what I do with 3 & 4, I get 3 is the min number and with the second row between 8 & 2, I get 2 is the min number.
My problem is that I can't get it to compare the columns as in 3 & 8 to get the max out between them, and 4 & 2.
In the code it just outputs the max number in the rows it still comparing the "ROWS"
P.S sorry for the long explanation. I just had to clarify it .
int main()
{
int d;
int max;
//array dimention
cout << "Enter the array dimention :- " << endl;
cin >> d;
//max_min for the final maximum numbers
int max_num[d];
//the 2d array
int arr[d][d];
// array input
cout << "please enter the array elements :- " << endl;
for (int i = 0; i < d; i++) {
for (int j = 0; j < d; j++) {
cin >> arr[i][j];
}
}
//array output
cout << "the array elements you enterd :-" << endl;
for (int i = 0; i < d; i++) {
for (int j = 0; j < d; j++) {
cout << arr[i][j] << " ";
}
cout << endl;
}
//the max numbers
for (int i = 0; i < d; i++) {
max = arr[0][i];
for (int j = 0; j < d; j++) {
if (max < arr[j][i]) {
max = arr[j][i];
}
}
max_num[i] = max;
}
cout << "the maximum elements in array :-" << endl;
for (int i = 0; i < d; i++) {
cout << max_num[i] << endl;
}
}
I've been struggling on this for about an hour now so I'm turning to the almighty entity that is the internet for assistance.
I'm trying to write a program that will A) read a matrix from a txt file in the following format where the first number is the columns (4) and the second number is the rows(3) in the matrix. And each row of numbers corresponds to a row in the matrix.
4 3
1 2 3 4
0 1 2 7
4 1 9 2
and B) calculate the number of ones in the matrix. So the above example would return 3. My code is below.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
void count_ones(int matrix[][], int rows, int columns)
{
int count = 0;
for(int i = 0; i < rows; i++)
{
for( int j = 0; j < columns; j++)
{
if( matrix[i][j] == 1)
{ count++;}
}
}
cout << "There are " << count << " ones in this matrix.";
}
int main(int argc, char* argv[])
{
int rows, columns;
string file_name = argv[1];
ifstream reader("m1.txt");
reader >> columns;
reader >> rows;
int matrix[rows][columns];
for(int i = 0; i < rows; i++)
{
for(int j = 0; j < columns; j++)
{
reader >> matrix[i][j];
}
}
cout << columns << " " << rows;
cout << endl;
for( int k = 0; k < rows; k++) {
for( int l = 0; l < columns; l++)
cout << matrix[k][l] << " ";
cout << endl;
reader.close();
count_ones(matrix, rows,columns);
return 0;
}
}
Right now I have two issues. The code i'm using to print the matrix I'm reading from the "m1.txt" file is only printing the first two lines and I have absolutely no clue what could be causing this but I'm guessing it has something to do with my ifstream reader.
4 3
1 2 3 4
Secondly, I'm getting a bunch of errors I don't understand when I try to pass my matrix to my count_ones function. I'm not very good with C++ so I would appreciate all the help I can get.
In a comment, you asked
Does anyone have a better way to pass the matrix to the count_ones method?
Don't use
int matrix[rows][columns];
This is not standard C++. It is supported by some compilers as an extension.
Use
std::vector<std::vector<int>> matrix;
You can initialize it with the correct sizes for rows and columns using
std::vector<std::vector<int>> matrix(rows, std::vector<int>(columns));
Change the declaration of count_ones to accept a std::vector<std::vector<in>>.
int count_ones(std::vector<std::vector<in>> const& matrix);
Update its implementation accordingly.
Suggestion for improvement
You can avoid the error of putting the closing } in the wrong place by using helper functions to write the matrix to cout.
std::ostream& operator<<(std::ostream& out, std::vector<int> const& row)
{
for ( int item : row )
out << item << " ";
return out;
}
std::ostream& operator<<(std::ostream& out, std::vector<std::vector<int>> const& matrix)
{
for ( auto const& row : matrix )
out << row << std::endl;
return out;
}
and then use
std::cout << matrix;
in main.
You have done a mistake in the last for loop.
for( int k = 0; k < rows; k++) {
for( int l = 0; l < columns; l++)
cout << matrix[k][l] << " ";
cout << endl;
reader.close();
count_ones(matrix, rows,columns);
return 0;
}
}
It should be like this
for( int k = 0; k < rows; k++) {
for( int l = 0; l < columns; l++)
cout << matrix[k][l] << " ";
cout << endl;
}
reader.close();
count_ones(matrix, rows,columns);
return 0;
}
Because of this the outer for loop in your code runs only once and prints only first row of matrix.
Edit:
Some more things to correct. You can not use matix[][] as a function parameter, it will through the error multidimensional array must have bounds for all dimensions except the first
You can use double pointer for this work. Change the check ones function declaration to this
void count_ones(int **matrix, int rows, int columns)
replace
int matrix[rows][columns];
with
int **matrix = (int **)malloc(sizeof(int *)*columns);
for(int i=0; i < columns; i++)
*(matrix + i) = (int *)malloc(sizeof(int)*rows);
and the code should work like a charm. And also remove this line, its redundant as file_name is not being used.
string file_name = argv[1];
So, I don't know what the errors are until you post them, but I have an idea why your output is cut off prematurely.
So, to recap, let's look at your code again (the relevant part":
cout << columns << " " << rows;
cout << endl;
for( int k = 0; k < rows; k++) {
for( int l = 0; l < columns; l++) /* { */
cout << matrix[k][l] << " ";
/* } */
cout << endl;
reader.close();
count_ones(matrix, rows,columns);
return 0;
}
I've indented it so it's easier to read as well as added the comment braces, just so it's clearer what is getting executed by what.
And now, the output:
4 3
1 2 3 4
Okay, now let's break down what's happening.
cout << columns << " " << rows;
cout << endl;
This is creating the line:
4 3
So far so good, right?
Now, we enter the lop:
for( int k = 0; k < rows; k++) {
for( int l = 0; l < columns; l++) /* { */
cout << matrix[k][l] << " ";
/* } */
cout << endl;
and get this:
1 2 3 4
This must be the first line of the matrix.
More code executes:
reader.close();
count_ones(matrix, rows,columns);
which isn't relevant to your problem.
And now this:
return 0;
}
Whoops! We've just left the function by calling return.
The loop will no longer execute because we've terminated it prematurely by returning, only outputting the first line of the matrix.
Solution: Just move the return statement outside the loop like so:
cout << columns << " " << rows;
cout << endl;
for( int k = 0; k < rows; k++) {
for( int l = 0; l < columns; l++) /* { */
cout << matrix[k][l] << " ";
/* } */
cout << endl;
reader.close();
count_ones(matrix, rows,columns);
}
return 0;
And that should fix the problem.
Finally, some friendly advice, take Sami Kuhmonen's advice and indent your code. It makes it easier to read and catch things like this.
EDIT: One more point, as R.k. Lohana mentioned, you probably want to pull these lines out of the loop too:
reader.close();
count_ones(matrix, rows,columns);
Like so:
for( int k = 0; k < rows; k++) {
for( int l = 0; l < columns; l++) /* { */
cout << matrix[k][l] << " ";
/* } */
cout << endl;
}
reader.close();
count_ones(matrix, rows,columns);
return 0;
Since you probably only want to do them once and not multiple times.
My task is to replace elements of vector and elements on diagonal matrix. Vector is entered by user and the matrix is random. For example, I write vector:
1 2 3
And the random matrix is
7 0 0
0 3 0
0 0 8
I must get this
1) 7 3 8
2)
1 0 0
0 2 0
0 0 3
The first part of it i got, but the second I'm stacked. Here is entering vector:
int size;
std::cout << ("Enter the dimentoinal of vector and matrix (enter one number): ");
std::cin >> size;
int * arrayPtr = (int*) calloc(size,sizeof(int));
if (arrayPtr == NULL) exit (1);
for (int ix = 0; ix < size; ix++)
{
std::cout << "Enter element #" << ix<< " ";
std::cin >> arrayPtr[ix];
}
system ("clear") ;
std::cout << "\n\nResulting vector is:\n[ ";
for (int ix = 0; ix < size; ix++)
{
std::cout << arrayPtr[ix] << " ";
}
cout << "]\n\n\n" ;
Here is code, that not working(on the screen is not correct result):
cout << "The new matrix is :\n" ;
int * matr_n = (int*) calloc(size,sizeof(int));
cout << "\n" ;
for (int ix = 0 ; ix<size; ix++)
{
matr_n = &arrayPtr[ix] ;
cout << *matr_n << " " ;
for (int i = 0; i<size; i++)
{
cout << "\n" ;
for (int j = 0; j<size; j++)
{
if (i==j)
{
cout << *matr_n << " " ;
}
else
cout << 0 << " " ;
}
}
}
I know that the problem is in using pointers or malloc/calloc function, but for beginner is hard to catch it fast.
Can you fix it, please?
The inner for-loop which prints the matrix should be separated from the loop which calculates its values.
In other words, you'll need to change the bottom part of the code as follows:
for (int ix = 0; ix < size; ix++)
{
matr_n = &arrayPtr[ix];
std::cout << *matr_n << " ";
}
for (int i = 0; i<size; i++)
{
std::cout << "\n";
for (int j = 0; j<size; j++)
{
if (i == j)
{
std::cout << *matr_n << " ";
}
else
std::cout << 0 << " ";
}
}
I am trying to print this array of 9 elements out in 3 lines.
I want to print it out in 3 lines with 3 rows such as .
xxx
xxx
xxx
But i am not sure how to tackle that.
void ticTacToeBoard ()
{
for (int i = 0; i < 9; i++)
{
cout << ticTacBoard[i] << " ";
}
}
I like to be verbose with my loops, so try this:
void ticTacToeBoard ()
{
for (int y = 0; y < 3; y++)
{
for (int x = 0; i < 3; x++)
{
cout << ticTacBoard[3 * y + x] << " ";
}
cout << endl;
}
}
Basically, I iterate over your board in rows (y), and then in columns (x), allowing me to print each cell and control the flow.
I just print a newline (endl) after each row.
Change ticTacBoard to a two dimensional array and do
using namespace std;
int main()
{
int ticTacBoard[3][3];
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
cout << ticTacBoard[i][j] << " ";
}
cout << endl;
}
return 0;
}
A two dimensional array will be easier to understand.
Use the modulo operator to detect every third iteration. Then print a newline.
void ticTacToeBoard ()
{
for (int i = 0; i < 9; i++)
{
cout << ticTacBoard[i] << " ";
if((i + 1) % 3 == 0) {
cout << endl;
}
}
}
You can switch frot the offset in a single-dimensional array (say i) to the offset in a bi-dimensional via this simple formula:
row = i div width
column = i mod width
So, basically:
for(int i = 0; i < 9; i++) {
cout << ticTacBoard[i];
if(i % 3 == 2)
cout << endl;
else
cout << ' ';
}