Print 2D array in reverse (C++) - c++

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

Related

How to print an array of 5 values 1D as columns?

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
}

Putting the last integer on a new line when outputting integers in ascending order

In the code below, I am trying to output the integers in ascending order. It works, however I want the final integer to be put on a newline (final integer only- not the other integers). I have tried
cout << myVec[i] << " "; endl
and...
cout << myVec[i] << endl;
but, both do not give the output I am looking for (these affect the other integers which is not what I want.
#include <iostream>
#include <vector>
using namespace std;
void SortVector(vector<int>& myVec)
{
int n = myVec.size();
int i, j;
for (i = 0; i < n - 1; i++)
for (j = 0; j < n - i - 1; j++)
if (myVec[j] > myVec[j + 1])
{
int temp = myVec[j];
myVec[j] = myVec[j + 1];
myVec[j + 1] = temp;
}
}
int main()
{
int i, n, value;
cin >> n;
vector<int> myVec;
for (i = 0; i < n; i++)
{
cin >> value;
myVec.push_back(value);
}
SortVector(myVec);
for (i = 0; i < n; i++)
cout << myVec[i] << " ";
return 0;
}
Print all but the last element on one line:
for (i = 0; i < n-1; i++) // notice n-1
std::cout << myVec[i] << ' ';
std::cout << '\n';
Then you can print the last afterwards:
if(myVec.size())
std::cout << myVec.back() << '\n';

Can't figure out why only one line of matrix is being read from a file and why I can't pass a 2D array to a function

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.

Print an array in C++

I'm trying to do some of my C++ homework, but I seem to have run into an issue. I need to make it so that the user inputs 8 numbers, and those said 8 get stored in an array. Then, if one of the numbers is greater than 21, to output said number. The code is below, and it's kind of sloppy. Yes, first year C++ learner here :p
#include <iostream>
using namespace std;
int main() {
const int NUM_ELEMENTS = 8; // Number of elements
int userVals[NUM_ELEMENTS]; // User numbers
int i = 0; // Loop index
int sumVal = 0; // For computing sum
int prntSel = 0; // For printing greater than 21
// Prompt user to populate array
cout << "Enter " << NUM_ELEMENTS << " integer values..." << endl;
for (i = 0; i < NUM_ELEMENTS; ++i) {
cin >> userVals[i];
}
for (int i = NUM_ELEMENTS - 1; i > 21; i--)
cout << "Value: " << sumVal << endl;
// Determine sum
sumVal = 0;
for (i = 0; i < NUM_ELEMENTS; ++i) {
sumVal = sumVal + userVals[i];
}
cout << "Sum: " << sumVal << endl;
return 0;
}
Don't reinvent the wheel, use standard algorithms:
std::copy_if(std::begin(userVals), std::end(userVals),
std::ostream_iterator<int>(std::cout, "\n"),
[] (auto x) { return x > 21; });
I improved the rest of your program as well:
#include <algorithm>
#include <iostream>
#include <iterator>
#include <numeric>
#include <vector>
auto constexpr count = 8;
int main() {
std::vector<int> numbers(count);
std::cout << "Enter " << count << " integer values...\n";
std::copy_n(std::istream_iterator<int>(std::cin), numbers.size(), numbers.begin());
std::copy_if(numbers.begin(), numbers.end(),
std::ostream_iterator<int>(std::cout, "\n"),
[] (auto x) { return x > 21; });
auto sum = std::accumulate(numbers.begin(), numbers.end(), 0);
std::cout << "Sum: " << sum << '\n';
return 0;
}
See it live on Coliru!
Ok, I'm going to explain this to you and keep it simple. This loop
`for (int i = NUM_ELEMENTS - 1; i > 21; i--)`
will never execute because in your first iteration you are checking if (NUM_ELEMENTS-1=7)>21. You are then decrementing i so this will take the series (6,5,4,...) and nothing would ever happen here.
If you have to sum the numbers greater than 21, which I presume is what you need then you will have to remove the above loop and modify your second loop to:
for (i = 0; i < NUM_ELEMENTS; i++) {
if(userVals[i]>21)
sumVal = sumVal + userVals[i];
}
This way, you add the numbers in the array that are only greater than 21. The index of userVals is determined by the i variable which also acts as a counter.
You're on the right track. There's just a few things wrong with your approach.
#include <iostream>
#include <stdlib.h>
using namespace std;
int main() {
const int NUM_ELEMENTS = 8;
int userVals[NUM_ELEMENTS];
int i = 0;
int sumVal = 0;
int prntSel = 0;
int size = sizeof(userVals) / sizeof(int); // Get size of your array
// 32/4 = 8 (ints are 4 bytes)
cout << "Enter " << NUM_ELEMENTS << " integer values..." << endl;
for (i = 0; i < NUM_ELEMENTS; ++i) {
cin >> userVals[i];
}
for(int i = 0; i < size; i++) {
if(userVals[i] > 21) { // Is number > 21?
cout << userVals[i] << endl; // If so, print said number
exit(0); // And exit
}
else
sumVal += userVals[i]; // Else sum your values
}
cout << "Sum: " << sumVal << endl;
return 0;
}
#include <iostream>
using namespace std;
int main() {
const int NUM_ELEMENTS = 8; // Number of elements
int userVals[NUM_ELEMENTS]; // User numbers
int i = 0; // Loop index
int sumVal = 0; // For computing sum
int prntSel = 0; // For printing greater than 21
// Prompt user to populate array
cout << "Enter " << NUM_ELEMENTS << " integer values..." << endl;
for (i = 0; i < NUM_ELEMENTS; ++i) {
cin >> userVals[i];
}
// for (int i = NUM_ELEMENTS - 1; i > 21; i--)
// cout << "Value: " << sumVal << endl;
for( i = 0; i < NUM_ELEMENTS; ++i )
{
if( userVals[ i ] > 21 )
{
cout << "Value: " << i << " is " << userVals[ i ] << endl;
}
}
for (i = 0; i < NUM_ELEMENTS; ++i) {
sumVal = sumVal + userVals[i];
}
cout << "Sum: " << sumVal << endl;
return 0;
}
Try
for (int i = NUM_ELEMENTS - 1; i > 21; i--)
cout << "Value: " << sumVal << endl;
to
for (i = 0; i < NUM_ELEMENTS; ++i) {
if(userVals[i] > 21)
cout << "Value: " << userVals[i] << endl;
}
This line isnt needed as well, as you arent using it.
int prntSel = 0; // For printing greater than 21
for (int i = NUM_ELEMENTS - 1; i > 21; i--)
cout << "Value: " << sumVal << endl;
Here you are printing the value of sumVal, not the value of the array in the position i. The line should be:
cout << "Value: " << usersVals[i] << endl;
Also that that your for is not doing what you think it does. for doesn't use the condition you gave to decide if will execute the current iteration or not, it uses the condition to decide if the loop should continue or not. So when you put i > 21, means that it will continue running while i is bigger than 21. To achieve your goal, you should make a test (if statement) inside the loop.
The final result it would be:
for (i = 0; i < NUM_ELEMENTS; ++i) {
if (usersVals[i] > 21) {
cout << "Value: " << usersVals[i] << endl;
}
}

Print array 3 lines

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