How can I print 2D arrays with four columns - c++

I am struggling with printing an array with 4 rows and 4 columns, when I initialized the array and entered all the values. Then, I used for loop to get all the values together so I can print them. But I get is an array that companied all the values in one row.
I have attached the output when I run the code.
Here is a portion of my code, it is long code but I am struggling in specific part:
#include <iostream>
using namespace std;
int main()
{
cout << "The martix before I flipped it: " << endl;
cout << endl;
int array[4][4] = { 16,3,2,13,5,10,11,8,9,6,7,12,4,5,14,1 };
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
cout << array[i][j] << " ";
}
}
return 0;

The standard output utility std::cout is a stream from the stl and, as such, its << operator does not usually automagically append a linebreak.
Which is quite practical since, otherwise, you would not be able to print multiple numbers on a single line.
That being, said, you'll need to add the linebreak manually, like so :
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
std::cout << array[i][j] << " ";
}
std::cout << std::endl;
}
Alternatively, you can consider printing lines 4 at a time since your matrix is of constant size :
for (int i = 0; i < 4; i++) {
std::cout << array[i][0] << " "
<< array[i][1] << " "
<< array[i][2] << " "
<< array[i][3] << " " << std::endl;
}
Have a great day,

Related

Print 2D array in reverse (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 << " ";
}
}

Program wont run to the end after function is called

I wrote a program to accept 15 integer values in an array, then pass this array to a function which will multiply each even index value by 4.
Currently the program displays the initial array, but seems like it's getting hung up before it displays the modified array.
Please help me understand why the program is getting stuck here!
int main(){
const int SIZE = 15;
int quad[SIZE] = {};
void quadruple(int[], const int);
cout << "Enter 15 integer values into an array." << endl;
for (int i = 0; i < SIZE; i++) // Accept 15 int values
{
cout << i << ": ";
cin >> quad[i];
}
cout << "Before quadruple function is called: " << endl;
for (int i = 0; i < SIZE; i++)
{
cout << quad[i] << " ";
}
cout << endl;
quadruple(quad, SIZE);
cout << "After even index value multiplication: " << endl;
for (int i = 0; i < SIZE; i++)
{
cout << quad[i] << " ";
}
cout << endl;
return 0;
}
void quadruple(int values[], const int SZ){
for (int i = 0; i < SZ; i + 2) // Multiply even values by 4
{
if ((i % 2) == 0)
{
values[i] = values[i] * 4;
}
else // Keep odd values the same
{
values[i] = values[i] * 1;
}
}
}
for (int i = 0; i < SZ; i + 2)
"i + 2" doesn't do anything.
You probably meant "i += 2;".
Your homework assignment is to find some documentation about your system's debugger. And find where your rubber duck is, as it's been suggested in the comments.

C++: How to print a multiplication table using nested loop?

I am running a program in c++ which prints the multiplication table from 1 to 40 but it starts from 13*10=130 to 40 so whats the reason behind this?
Below is the formatted version of the code you posted:
#include<iostream>
using namespace std;
int main() {
for (int i = 1; i <= 40; i++) {
for (int j = 1; j <= 10; j++) {
cout << i << " * " << j << " = " << i*j << endl;
}
cout << endl;
}
return 0;
}
It starts printing at 13 * 10. What's the reason for this?
Notably, we can see the variables of both loops (i and j) are initialized to 1 when the loop starts. Because of this, you would be right in expecting the first loop-through to print 1 * 1 = 1.
This suggests, as PRIME has pointed out, that the environment (such as the Windows Console) that you are printing to may not have a large enough buffer to store and display the 440 lines of output the program will try to print.
How can I get around this?
You can try re-sizing your printing environment's internal buffer (if it allows) to allow for 440 lines of print. In MS-DOS, for example, you can manually change this by right-clicking the title-bar, going into Properties, then the Layout tab, and changing the Screen Buffer width and height to values that suit.
Alternatively, you could conserve print-space by replacing endl statements with regular spaces, a la:
for (int i = 1; i <= 40; i++) {
for (int j = 1; j <= 10; j++)
cout << i << " * " << j << " = " << i*j << ' ';
}
You also have the option of outputting to a file instead of your current printing environment:
#include <fstream>
using namespace std;
int main() {
ofstream Output("Output.txt"); //Creates a file "Output.txt"
if (Output.is_open()) { //If the file is open, proceeed
for (int i = 1; i <= 40; i++) {
for (int j = 1; j <= 10; j++)
Output << i << " * " << j << " = " << i*j << '\n';
Output << '\n'; //^^^Write multiplication table to the file
}
}
return 0;
}

C++ Displaying An Organized List of Words

I am making a 20 questions game in C++ and have everything working, except for the displayWords function. The code I currently have keeps breaking. Any explanation would be appreciated! Thank you!
void displayWords()
{
int x = 0;
string words[50] = {"LCHS","Shark","Pencil","Pizza","New York","Fish","Car","Ice Cream","Los Angeles","Bird","Basketball","Fried Chicken",
"Dog","Tiger","Penguin","Plane","Rock","Barbecue Sauce","Mustard","Ketchup","Hot sauce","Peppers","Salt","Tacos","Shrimp","Pickels",
"Tomatos","Bannanas","Burger","Computer","Iphone","Motorcycle","Bicycle","Skateboard","Lightbulb","Golf Ball","Surfboard","Luggage",
"Rollercoaster","Cat","Lion","Cockroach","Grasshopper","Beach","Theme Park","Swimming Pool","Bowling Ally","Movie Theater","Golf Course","Shopping Mall"};
cout << "The following list of words are what the computer is capable of guessing" << endl;
cout << endl;
while(x < 50)
{
for (int y = 0; y <= 5; y++)
{
cout << words[x] << ", ";
if(x<50)
x++;
}
cout << endl;
}
}
I would like it to display the list of 50 words in an organized fashion.
By example, as:
for( int x = 0; x<sizeof(words)/sizeof(*words); x++ ) {
if( x%5==0 ) cout << endl; else cout << ", ";
cout << words[x];
}
take into account the problematic of the array's size calculation: see this link How do I find the length of an array?
If I understand correctly, you want your list displayed as 5 columns. Simplest way, use a nested for loop and proper formatting with std::setw (must #include <iomanip>):
for(size_t i = 0; i < 10; ++i)
{
for(size_t j = 0; j < 5; ++j)
{
std::cout << std::setw(20) << std::left << words[i * 5 + j];
}
std::cout << std::endl;
}
Your actual loop is incorrect, as it will lead to repetitions.
Maybe I'm not interpreting your question correctly but if you want to just print out the 50 words then you can use something like the code below. Not sure of the reason that the nested for loop iterating y was there.
Edit
void displayWords()
{
int x;
string words[50] = {"LCHS","Shark","Pencil","Pizza","New York","Fish","Car","Ice Cream","Los Angeles","Bird","Basketball","Fried Chicken",
"Dog","Tiger","Penguin","Plane","Rock","Barbecue Sauce","Mustard","Ketchup","Hot sauce","Peppers","Salt","Tacos","Shrimp","Pickels",
"Tomatos","Bannanas","Burger","Computer","Iphone","Motorcycle","Bicycle","Skateboard","Lightbulb","Golf Ball","Surfboard","Luggage",
"Rollercoaster","Cat","Lion","Cockroach","Grasshopper","Beach","Theme Park","Swimming Pool","Bowling Ally","Movie Theater","Golf Course","Shopping Mall"};
cout << "The following list of words are what the computer is capable of guessing" << endl;
cout << endl;
for(x = 0; x < words.size();x++)
{
cout << words[x]<< ", ";
}
}
Also some information on how the code is breaking, like are any errors being thrown or has debugging caused issues so far?

How To Change Multidimensional Array Size In Program?

Hey I was wondering how I could have settings in-game which would allow the user to set the size of the 'game-board' by changing the array values. Here is the code. I know the code is messy and over the place but it is my first program.
#include "stdafx.h"
#include "iostream"
#include "string"
#include "cstdlib"
#include "ctime"
int xRan;
int choicei = 17;
int choicej = 17;
const int row = 15;
const int col = 16;
int play = 0;
void fill(char Array[row][col]);
int main()
{
int play = 0;
char Array[row][col];
srand((unsigned int)time(0));
xRan = rand() % 15 + 1;
if (play == 0)
{
std::cout << "1. To Play Treasure Hunt!" << std::endl;
std::cout << "2. How To Play Treaure Hunt!" << std::endl;
std::cout << "3. Treaure Hunt Settings! (Comming Soon)\n" << std::endl;
std::cin >> play;
std::cout << "-----------------------------------------------------------------------" << std::endl;
}
if (play == 2)
{
std::cout << "1. Select a row number. Be sure to make it less than or equal to " << row << "!" << std::endl;
std::cout << "2. Select a column number. Be sure to make it less than or equal to " << col << "!" << std::endl;
std::cout << "3. If you see the 'X' you have won! If you see the 'O' you lose!" << std::endl;
std::cout << "-----------------------------------------------------------------------\n" << std::endl;
std::cin >> play;
}
if (play == 3)
{
std::cout << "\nComming Soon!" << std::endl;
std::cout << "-----------------------------------------------------------------------\n" << std::endl;
std::cin >> play;
}
while (choicei > row || choicej > col || choicei < 1 || choicej < 1)
{
std::cout << "\nEnter The Row Number Less Than Or Equal To " << row << "!" << std::endl;
std::cin >> choicei;
std::cout << std::endl;
std::cout << "Enter The Column Number Less Than Or Equal To " << col << "!" << std::endl;
std::cin >> choicej;
std::cout << "\n-----------------------------------------------------------------------" << std::endl;
if (choicei > row || choicej > row)
{
std::cout << "Make Sure The Row And Column Numbers Are Less Than Or Equal To " << row << "and" << col << "!\n" "---------------------------------------------------------------------- - " << std::endl;
}
if (choicei < 1 || choicej < 1)
{
std::cout << "Make Sure The Row And Column Numbers Are More Than Or Equal To 1" << "!\n" "-----------------------------------------------------------------------" << std::endl;
}
}
fill(Array);
std::cout << std::endl;
for (int i = 0; i < row; i++)
{
for (int j = 0; j < col; j++)
{
std::cout << Array[i][j] << " ";
}
std::cout << std::endl;
}
if (xRan > 11)
{
std::cout << "\nCongratulations! You Won!\n" << std::endl;
}
else
{
std::cout << "\nBetter Luck Next Time!\n" << std::endl;
}
}
void fill(char Array[row][col])
{
for (int i = 0; i < row; i++)
{
for (int j = 0; j < col; j++)
{
Array[i][j] = '*';
}
}
if (xRan > 11)
{
for (int i = 0; i < 1; i++)
{
for (int j = 0; j < col; j++)
{
Array[choicei - 1][choicej - 1] = 'X';
}
}
}
else
{
for (int i = 0; i < 1; i++)
{
for (int j = 0; j < col; j++)
{
Array[choicei - 1][choicej - 1] = 'O';
}
}
}
}
Thank you in advance.
you can't do that with ordinary arrays. you should use dynamic arrays, for example std::vector http://www.cplusplus.com/reference/vector/vector/
Actually, what you want to do can be done in C, not in C++: C++ requires array dimensions to be compile time constants, C can use any runtime value.
If you stay in C++, you should take a look at vector<>. If, however, you choose to use C you can simply remove the const from the declaration of row and col.
You may find this answer useful. It lists several methods to create dynamic arrays.
Quoting the answer :
In C++, variable length arrays are not legal. G++ allows this as an "extension" (because C allows it), so in G++ (without being -pedantic about following the C++ standard)
Based on the suggestions, here are some ways you could initialize it (ignoring how you take the input value) :-
vector<vector<char>> Array(row, vector<char>(col));
or
char **Array = new char*[row];
for(int i = 0; i < row; i++)
{
Array[i] = new char[col];
}
UPDATE
Based on the comments, I am adding how to use the vector method and use it with the function 'fill'. fill uses reference while fill_with_ptr makes use of pointer. Although I list both the methods, I strongly recommend the one using reference.
void fill(vector<vector<char> >& array);
void fill_with_ptr(vector<vector<char> >* array);
int main()
{
...
cin >> row;
cin >> col;
vector<vector<char> > Array(row, vector<char>(col));
...
fill (Array); // or fill_with_ptr(&Array);
}
void fill(vector<vector<char> >& array)
{
... // access elements as array[i][j]
}
void fill_with_ptr(vector<vector<char> >* array)
{
... // access elements as (*array)[i][j]
}