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 << ' ';
}
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 am learning C++ and would like some help with functionality for my code below.
Quick summary/usage of my code: Program is to display randomized (x,y) coordinates and then print out the coordinates in a grid.
I got everything to work regarding randomizing (x,y) coordinates and then displaying their grid location.
The problem I am having is my code displays a separate grid for each coordinate instead of showing ALL coordinates on the same grid. [I attached a picture of my current output below].
I know this is a functionality issue.. but I am having trouble thinking of how to manipulate my loops so that the coordinates can be displayed first, followed by ONE grid with all the coordinates on it... I hope this makes sense.
Snippet of my code:
//Note: value of n and k is given by user earlier in the code
vector<vector<int> > vec( n , vector<int> (n));
cout << "\nGrid with city locations:\n";
for(i=0; i<k; i++) {
//random select int coordinates (x,y) for each K(cities)
x = rand() % n + 0;
y = rand() % n + 0;
arrCity[i] = i;
//display coordinates for city 1..city2.. etc
cout << "City " << arrCity[i] <<": (" << x << "," << y << ")" << endl;
//display cities on grid
for (int rows=0; rows < n; rows++) {
for (int columns=0; columns < n; columns++) {
if ((rows == y) && (columns == x)) {
cout << "|" << (i);
} else {
cout << "|_";
}
}
cout << "\n";
}
cout << "\n";
}
Current Output:
As you can see there's a separate grid for each 'city coordinate'
You need to store all city coordinates in order to display them on a single grid print.
In the code below I changed a few things in order to hopefully address your problem.
I have moved all city-related data into a structure
Then all cities are initialized before the grid output
When printing the grid, we have to search all cities if their coordinates match the current position, if so, we print the corresponding index.
Live Demo
#include <vector>
#include <iostream>
struct City
{
int index;
int x, y;
City(int index_, int x_, int y_)
: index(index_), x(x_), y(y_)
{ }
};
int main()
{
int n = 10;
int k = 6;
std::vector<City> arrCity;
arrCity.reserve(k);
for(int i = 0; i < k; i++)
arrCity.emplace_back(i, rand() % n, rand() % n);
std::cout << "\nGrid with city locations:\n";
for (int k = 0; k < arrCity.size(); k++)
std::cout << "City " << arrCity[k].index << ": (" << arrCity[k].x << "," << arrCity[k].y << ")" << std::endl;
//display cities on grid
for (int i=0; i < n; i++) {
for (int j=0; j < n; j++) {
int w = -1;
for (int k = 0; k < arrCity.size(); k++)
if ((i == arrCity[k].y) && (j == arrCity[k].x))
w = k;
if (w >= 0)
std::cout << "|" << arrCity[w].index;
else
std::cout << "|_";
}
std::cout << "\n";
}
return 0;
}
You need to track which cells already has been visited. That's why you need to take another array which stores the cells that are already visited and by which value.
int vis[n][n];
memset(vis, -1, sizeof vis);
for(i=0; i<k; i++) {
//random select int coordinates (x,y) for each K(cities)
x = rand() % n + 0;
y = rand() % n + 0;
arrCity[i] = i;
vis[x][y] = i;
//display coordinates for city 1..city2.. etc
cout << "City " << arrCity[i] <<": (" << x << "," << y << ")" << endl;
//display cities on grid
for (int rows=0; rows < n; rows++) {
for (int columns=0; columns < n; columns++) {
if (vis[rows][columns] != -1) {
cout << "|" << (vis[rows][columns]);
} else {
cout << "|_";
}
}
cout << "\n";
}
cout << "\n";
}
Output:
I wrote the code to multiply two 2D Matrices in C++ language. I am using VS 2019 and there are no compiler errors.
When I execute the program, it gives me the output as well but I am not sure why I get the Matrix corruption error at run time.
Here is a simple program I wrote.
// CPP_ConsoleApp1.cpp : This file contains the 'main' function. Program execution begins and ends there.
//
#include "pch.h"
#include <iostream>
using namespace std;
int main()
{
int sum = 0;
cout << "Matrix 1" << endl;
int Matrix1[3][3] = { {1,2,3}, {2,3,1}, {2,1,0} };
for (int rows = 0; rows < 3; rows++)
{
for (int columns = 0; columns < 3; columns++)
{
cout << Matrix1[rows][columns] << "\t";
}
cout << endl;
}
cout << endl;
cout << "Matrix 2" << endl;
int Matrix2[3][2] = { {2,1},{2,2},{1,2} };
for (int rows = 0; rows < 3; rows++)
{
for (int columns = 0; columns < 2; columns++)
{
cout << Matrix2[rows][columns] << "\t";
}
cout << endl;
}
int Matrix3[3][2];
for (int rows = 0; rows < 3; rows++)
{
for (int column = 0; column < 3; column++)
{
for (int k = 0; k < 3; k++)
{
sum = sum + Matrix1[rows][k] * Matrix2[k][column];
}
Matrix3[rows][column] = sum;
sum = 0;
}
}
cout << endl;
cout << "Matrix 1 * Matrix 2" << endl;
for (int rows = 0; rows < 3; rows++)
{
for (int column = 0; column < 2; column++)
{
cout << Matrix3[rows][column] << "\t";
}
cout << endl;
}
}
I'm playing around to get the grip of multi dimensional arrays.
I have managed to have the array record the input from the user..
I'm trying to use 2 FOR loops to print with the idea that it should print 4 rows of 3 characters each
i know i can solve this if i manually type what to print, but for sure there is a way to have a loop do that for me...
here is the input and output code that i wrote:
cout << "Enter characters" << endl;
for (int i = 0; i < 4; i++)
{
for (int x = 0; x < 3; x++)
{
cin >> charArr[x][i];
}
}
cout << "Printing the array now" << endl;
for (int i = 0; i < 4; i++)
{
for (int x = 0; x < 3; x++)
{
cout << charArr[x][i];
}
cout << endl;
}
i don't understand why some letters are gone and why it doesn't print in order...
where i is row and j is a column. for loop should come like this only.
in this order only we can store the input.
In your case, you are swapping the orders.
Solution :
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 3; j++)
{
cin >> charArr[i][j];
}
}
cout << "Printing the array now" << endl;
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 3; j++)
{
cout << charArr[i][j];
}
cout << endl;
}
I'm having issues with this c++ code. It is supposed to print a hollow right isosceles triangle, but instead just prints asterisks over and over, so the for loops seem to be stuck.
#include "pch.h"
#include <string>
#include <iostream>
int main() {
int row;
std::string s = " ";
std::string a = " *";
int rows = 10;
for (int i = 0; i < rows; i++) {
if (i = 0) {
std::cout << a << std::endl;
}
while (i > 2 && i < rows) {
std::cout << a;
for (int pos = 0; pos < i; pos++) {
std::cout << s;
}
std::cout << a << std::endl;
}
std::cout << a << a << a << a << a << a << a << a << a << std::endl;
}
}
your while loop condition will never become false, AND you need to use comparison (==) instead of assignment in this line:
if (i = 0) {
Supposing that what you want to print is something of the following form:
Eg. for rows = 5
*
**
* *
* *
*****
Your code should have the following structure:
for (int i = 1; i <= rows; ++i)
{
//special case for the first line
if (i == 1)
std::cout << asterisk << std::endl;
//for each of the other lines print 2 asterisks and the rest spaces
if (i > 1 && i <= rows - 1)
{
//one at the start of the line
std::cout << asterisk;
//print line - 2 spaces
for (int j = 0; j < i - 2; ++j)
std::cout << space;
//one at the end of the line
std::cout << asterisk << std::endl;
}
//special case for the last line
if (i == rows)
{
for (int j = 1; j <= i; ++j )
std::cout << asterisk;
std::cout << endl;
}
}
https://ideone.com/peGRUG
Your while loop condition is the issue here, also you should use == instead of = inside if condition. Anyways,Here is a small fix in your solution..
void printTriangle() {
int row;
std::string s = " ";
std::string a = " *";
int rows = 10;
for (int i = 1; i < rows-1; i++) {
for (int j = 1; j <= i; ++j)
{
if (j == 1 || j == i)
std::cout << a;
else
std::cout << s;
}
std::cout << std::endl;
}
for (int i = 1; i < rows; ++i)
std::cout << a;
}