I am working with a 2D array in a VS2010 console application. I am allocating the array as such:
Thing::Thing(int _n, bool _control){
m = _n;
control = _control;
thisArray = new int*[m];
for(int ii = 0; ii < m; ii++){
thisArray[ii] = new int[m];
for (int jj = 0; jj < m; jj++){
thisArray[ii][jj] = 0;
}
}
if (control == true){
int num = 1;
for (int jj = 0; jj < m; jj++){
for ( int ii = 0; ii<m; ii++){
if ((jj == (m-1)) && (ii == (m-1))){
std::cout << "inserting " << 0 <<
"at[" << ii << "][" << jj << "]" << std::endl;
thisArray[ii][jj] = 0;
std::cout << thisArray[ii][jj] << std::endl;
} else{
std::cout << "inserting " << num <<
"at[" << ii << "][" << jj << "]" << std::endl;
thisArray[ii][jj] = num++;
std::cout << thisArray[ii][jj] << std::endl;
}
}
}
pi.x = m-1;
pi.y = m-1;
}
}
then I attempt to display it through
void Thing::display(){
int x = 0;
int y = 0;
for( ; y < m; y++){
for( x = 0; x < m; x++){
if (Point(x, y) == pi){
std::cout << "[ ]";
}
std::cout << "[" << thisArray[x][y] << "]";
if ( x == m ){
std::cout << std::endl;
}
}
}
}
but it seems like it is only displaying the first dimension as output when I pass in 4, and true looks like this:
inserting 1 at[0][0]1
inserting 2 at[1][0]2
inserting 3 at[2][0]3
inserting 4 at[3][0]4
inserting 5 at[0][1]5
inserting 6 at[1][1]6
inserting 7 at[2][1]7
inserting 8 at[3][1]8
inserting 9 at[0][2]9
inserting 10 at[1][2]10
inserting 11 at[2][2]11
inserting 12 at[3][2]12
inserting 13 at[0][3]13
inserting 14 at[1][3]14
inserting 15 at[2][3]15
inserting 0 at[3][3] 0
[1][2][3][4]
, and when I add the array to my watch list the system shows the pointer to pointer to a single value, and then will only show me the first element, and not all of the elements.
it throws no run time access errors, or anything like that, but when I try to display the array it only does the first row. Note: I have been asked to use an actual 2D-array of ints, and am not allowed to use a pre-written library, or a single dimensional lie.
edit: added additional output info.
edit2 (resolved): in display changed the second for loop to be
for (x = 0; x < m; x++)
when holding values external to a for loop insure that they are reset for circular iteration.
In your display function, you have to reset x at each iteration of the outer y loop.
It would even be clearer, if you did the initialization within the for statement:
for(int y = 0; ; y < m; y++){
for(int x = 0; ; x < m; x++){
And to view a pointer as an array in Visual C++ debugger, you can look at that other question.
Related
The idea I have is pretty simple. What I'd like to do is just have the user input a series of integers and plug those integers specified into an array. So for example, here's a segment of the program I'm writing.
const int size = 1000;
int array_one[size], array_two[size];
for (int i = 0; i < size; i++)
{
std::cin >> array_one[i];
if (array_one[i] == -1) break;
}
for (int i = 0; i < size; i++)
{
std::cin >> array_two[i];
if (array_two[i] == -1) break;
}
The cut off point is -1. Should the user enter this, one index of the array will be all integers greater than -1 with the following indexes housing 0's in this 1000 sized array.
What I'm doing next is simply replicating how you would write out basic addition on paper. So, lets say for example I plugged in 1 0 0 6 -1 as inputs for the first array and then 2 3 4 for the second array. The whole entire output should look something akin to this
1006
+ 234
------
1240
Here's what I've typed out to get this sort of output
int array_size_one = 0;
int array_size_two = 0;
int space_size = 3;
int cut_off_space = 0;
int count = 0;
for (int i = 0; i < size; ++i)
{
if (array_one[i] < 0) break;
array_size_one += 1;
}
for (int i = 0; i < size; ++i)
{
if (array_two[i] < 0) break;
array_size_two += 1;
}
if (array_size_one > array_size_two) space_size += array_size_one;
else if (array_size_two > array_size_one) space_size += array_size_two;
if (array_size_one < array_size_two) cut_off_space += array_size_one;
else if (array_size_two < array_size_one) cut_off_space += array_size_two;
std::cout << std::setw(space_size - array_size_one);
for (int j = 0; j < size; ++j)
{
if (array_one[j] < 0) break;
std::cout << array_one[j];
}
std::cout << "\n+";
std::cout << std::setw((space_size - 1) - array_size_two);
for (int j = 0; j < size; ++j)
{
if (array_two[j] < 0) break;
std::cout << array_two[j];
}
std::cout << "\n";
std::cout << std::setfill('-') << std::setw(space_size) << " " << std::endl;
for (int i = 0; i < (space_size - 3); ++i)
{
count = array_one[i] + array_two[i];
}
std::cout << count << std::endl;
return 0;
This is the part where I think I'm sure I'm having trouble with.
std::cout << "\n";
std::cout << std::setfill('-') << std::setw(space_size) << " " << std::endl;
for (int i = 0; i < (space_size - 3); ++i)
{
count = array_one[i] + array_two[i];
}
std::cout << count << std::endl;
return 0;
The idea was that I wanted to add up everything inside each index of the arrays to perform standard integer expressions. The for loop above isn't really cutting it. I'm getting outputs like 5 or 15. If going by the example above that has inputs of 1 0 0 6 -1 for the first array and then 2 3 4 -1 for the second array. What could I actually do inside the very last for loop iteration to make sure I get the correct outputs replicating standard integer expressions?
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 have the following code. I set each box equal to 1. Now I want to set 3 boxes at a time to 0. How do I do that without manually setting each of them to 1?
Is there a permutation formula that will set 3 at the time to 1?
#include <iostream>
using namespace std;
int main()
{
int array[2][2];
for (int x = 0; x<2; x++)
{
for (int y = 0; y<2; y++)
array[x][y] = 1;
}
// display all cells to see that all of them are set to zero
cout << "diplaying" << endl;
for (int x = 0; x<2; x++)
{
for (int y = 0; y<2; y++)
cout << array[x][y] << " " ;
cout << endl;
}
Printing this would look something like.
1 1
1 1
Now how do I get to print
0 1
0 0
and
1 0
0 0
and
0 0
1 0
and
0 0
0 1
without having to set them individually that way?
Personally, I would store the array as a 1D std::vector<int> of size n*n. Then you could call std::next_permutation() on it very simply. (It's worth noting that you don't have to use a std::vector; as long as it is contiguous in memory, you should be able to use std::next_permutation() properly)
The only thing you have to do that makes your permutation logic "2D" is the act of printing it out. However, your loop as-is should handle that properly, so no problems there either.
EDIT: Upon re-reading your code, you could not use this as-is. Instead, you should initialize your 1D std::vector to be 0 everywhere, except 1 at position 0. THEN, permutations of that would yield the output you want.
Furthermore, your printing loop would not print out the array properly. You probably want:
for (int i = 0; i < 2; ++i) {
for (int j = 0; j < 2; ++j) {
std::cout << vector[i*2+j] << " " ;
}
std::cout << std::endl;
}
After reading carefully, I interpreted your question this way:
You want to go from this
1 1
1 1
to this
0 1
0 0
using the for clause.
if you simply want to leave a cell unchanged.. you could just save it and restore it after filling the array with 0.
memo = array[0][1];
for (int x = 0; x<2; x++) {
for (int y = 0; y<2; y++) {
array[x][y] = 0;
}
}
array[0][1] = memo;
If that's what you want to do.
Where's the "string array" by the way..?
I would write a function that prints all zeros except where it needs to print the actual value, then call this function with different indexes for desired effect.
#include <iostream>
using namespace std;
#define SZ 2
void printValue(int a [SZ][SZ], int x, int y)
{
for(int i=0; i<SZ; ++i )
{
for(int j=0; j<SZ; ++j)
{
if(i==x && j==y) cout<<a[i][j];
else cout<<"0";
cout<<" ";
}
cout<<endl;
}
}
Now you can make use of this function in a for loop
int main()
{
int arr[SZ][SZ];
for (int x = 0; x<SZ; x++)
{
for (int y = 0; y<SZ; y++)
arr[x][y] = 1;
}
// display all cells to see that all of them are set to zero
cout << "diplaying" << endl;
for (int x = 0; x<SZ; x++)
{
for (int y = 0; y<SZ; y++)
cout << arr[x][y] << " " ;
cout << endl;
}
//now display all combos:
for(int i=0; i<SZ; ++i)
{
for(int j=0; j<SZ; ++j)
{
printValue(arr, i,j);
}
cout<<"\n\n";
}
}
I am trying to output a simple 2D char array using nested for loops
It does not output in a "Square form", and also it is crashing.
#include <iostream>
using namespace std;
int main(){
char array[x][y] = {
"000000",
"0 0",
"0 0",
"000000",
};
for (int i = 1; i <=x; i++) {
for (int j = 1; j <=y; j++)
cout << array[i][j];
}
}
C++ uses Zero-based indexing
your loops should be like
for (int i = 0; i <x; i++)
https://en.wikipedia.org/wiki/Zero-based_numbering
That's why it's crashing
Also you don't print line breaks. Insert cout << std::endl in the outer loop
The arrays are zero based, so you should loop from 0 to x-1 rather than from 1 to x.
You also need a line break, otherwise it will all be written on the same line.
for (int i = 0; i < x; i++) {
for (int j = 0; j < y; i++) {
cout << array[i][j];
}
cout << std::endl;
}
I suppose that x and y are constants defined like
const size_t x = 4;
const size_t y = 7;
C++ does not allow to use non-constant expressions as array sizes though some compilers have their own language extensions that allow to use variable length arrays.
In this case this array
char array[x][y] = {
"000000",
"0 0",
"0 0",
"000000",
};
can be outputed the following way
for ( auto &s : array ) std::cout << s << std::endl;
Take into account that indices of arrays in C++ start from 0. So if to use indices then the loop can look like
for ( size_t i = 0; i < x; i++ ) std::cout << array[i] << std::endl;
Take into account that to output this shape there is no need to declare a 2D array.:)
Here is a demonstrative program
#include <iostream>
#include <iomanip>
int main()
{
size_t n = 4;
size_t m = 6;
char c = '*';
for ( size_t i = 0; i < n; i++ )
{
std::cout << c
<< std::setfill( i % ( n - 1 ) == 0 ? c : ' ' )
<< std::setw( m - 1 )
<< c << std::endl;
}
}
Its output is what you expect:)
******
* *
* *
******
and can someone explain me why the second method outputs the array on other location ? i mean it starts to output on 2nd line while 1st method outputs from 00coord (by coord its mean location in console ,, not array position)
for (int i = 0; i < x; i++)
cout << array[i] << endl;
for (int i = 0; i <x; i++) {
cout << endl;
for (int j = 0; j <y; j++)
cout << map[i][j];
}
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 .