I made an array and set the values from 1 to 9 in the initializeBoard function, but for some reason when I print the values they come out 0 to 8. Why is this happening? Shouldn't it print out 1 to 9 since those are the numbers I put in the array in initializeBoard?
int main()
{
initializeBoard();
ticTacToeBoard();
}
void initializeBoard()
{
for (int i = 1; i < 9; i++)
ticTacBoard[i] = i;
cout << endl;
}
void ticTacToeBoard ()
{
for (int y = 0; y < 3; y++)
{
for (int x = 0; x < 3; x++)
cout << ticTacBoard[3 * y + x] << " ";
cout << endl;
}
}
You have an off-by-one error. Arrays use zero-based indexing in C++. Your code does not assign a value to the zeroth element of the array.
Try this instead:
for (int i = 0; i < 9; i++)
{
ticTacBoard[i] = i + 1;
}
The loop:
for (int i = 1; i < 9; i++)
{
ticTacBoard[i] = i;
}
will only do 1-8 since it will stop when i++ increases it to 9, so you're not initializing all 9 elements.
You should realistically do the same loop like this:
for (int i = 0; i < 9; i++)
{
ticTacBoard[i] = (i + 1);
}
Problem lies in:
ticTacBoard[i] = i;
Should be:
ticTacBoard[i-1] = i;
Two suggestions:
Shouldn't you initialize ticTacBoard before accessing it with []? Make sure you give it enough memory for all of your slots! (I'm guessing you're doing tic tac toe, so you'll want 3x3 = 9 slots)
Indexing in C++ starts at 0. You want to do for (i=0; i<9; i++)
Hope this helps!
Your i starts at 0, so your first value will be 0. Since the inequality i < 9 breaks when i = 9, i is actually never 9 (the loop exits before your code is actually run).
Try using <= instead of just < to account for i = 9:
for (int i = 1; i <= 9; i++)
{
ticTacBoard[i - 1] = i;
}
Other than that, arrays are indexed starting from 0 in C++ (and virtually every other language), so the first element is array[0], second is array[1], etc.
You'll have to subtract 1 from your array index.
Related
Ok, im starting c++ and i want to assign a value to a specific position in a vector of a vector. I have done it with an array of array (2D) but now would like to do it with vectors.
int main() {
int newLine = 10;
int newColumm = 10;
const string WALL = "\u2588";
cout << endl;
string grille[10][10];
for (int j = 0; j < newColumm + 1; j++) {
int i = 0;
grille[i][j] = WALL;
}
for (int j = 0; j < newColumm + 1; j++) {
int i = newLine + 1;
grille[i][j] = WALL;
}
I would like to do the same thing with vectors.
I Have :
int main() {
int newLine = 10;
int newColumm = 10;
const string WALL = "\u2588";
cout << endl;
// string grille[10][10];
vector<vector<string>> grille;
for (int j = 0; j < newColumm + 1; j++) {
int i = 0;
grille.at(i).at(j) = WALL;
}
for (int j = 0; j < newColumm + 1; j++) {
int i = newLine + 1;
grille.at(i).at(j) = WALL;
}
It's obviously not working for the moment.
(Sorry for my bad language, english is my second language...)
Your vector has no size. You are getting a std::range_error exception when you access the vector out-of-bounds. Since you are not handling exceptions, your program crashes.
The naive fix for this is to simply pre-allocate your vector to the dimensions you expect:
vector<vector<string>> grille(10, std::vector<string>(10));
Note that your for-loops will naturally overshoot anyway and you'll still get an exception, since they are actually looping to 10 inclusive. Remember that if you have 10 elements, then the valid indices are 0 to 9 inclusive.
I am trying to fill an array of 52 with the numbers 0 - 12. Once it hits 12, it needs to go back to 0 - 12 again. You might have already guessed it's a deck of cards. My code is below and doesn't work. It prints 0 - 12 one time, but then prints the address of the array I believe for the remainder of the iterations left.
#include<iostream>
#include<string>
using namespace std;
int main()
{
int myArray[52];
for (int j = 0; j < 4; j++)
{
for (int i = 0; i < 13; i++)
{
myArray[i] = i;
}
}
for (int k = 0; k < 52; k++)
{
cout << myArray[k] << endl;
}
//system("pause");
return 0;
}
Can someone please help me with this brain fart?
int myints[52];
for (int idx = 0; idx < 52; idx++)
{
myints[idx] = idx % 13;
}
Modulus of 13 will range from 0 to 12.
You're indexing the same first 12 elements of the array in the inner loop for every iteration of the outer loop.
Try changing it to something like this
for (int j = 0; j < 4; j++)
{
for (int i = 0; i < 13; i++)
{
myArray[i + 13 * j] = i;
}
}
I am currently making a program that outputs a little triangle made off of stars (or asterisks) in c++, and I am facing some problems.
It seems as though whenever I write something to the function, the compiler interprets it as that number, minus two - something I find very strange.
int makePyramid(int len=1) {
// A pyramid (or triangle) can not consist of less than 1 length.
if(len < 1) {
cout << "does not make sense" << endl;
}
else {
// Go through the length
for(int i = 1; i < len; ++i) {
// Make one star for each number in the last loop
for(int j = 1; j < i; ++j) {
cout << "*";
}
// Makes a new line after the second loop is through
cout << endl;
}
}
}
Here is the function in question. As you can see, it should work - the first loop goes through the whole number and then goes to the next loop which prints one asterisks depending on the value of the number, and then it outputs a new line so it can get started on the next set of asterisks.
Keep in mind that I am pretty new to C++, and I am using minGW in cmd (Windows 10) to compile the code.
1) The loop for (int i = 1; i < len; i++) iterates len - 1 times. i have values in the range of [1; len - 1].
2) The loop for (int j = 1; j < i; ++j) iterates j - 1 times. j have values in the range of [1; i - 1].
That's why these function prints less asteriks. C style loops are tricky and are more powerful in comparison to, for example, Pascal loops. In order to fix that you need by initializing i and j with 0 or by replacing < with <=:
int makePyramid(int len=1) {
// A pyramid (or triangle) can not consist of less than 1 length.
if(len < 1) {
cout << "does not make sense" << endl;
}
else {
// Go through the length
for(int i = 0; i < len; ++i) {
// Make one star for each number in the last loop
for(int j = 0; j <= i; ++j) {
cout << "*";
}
// Makes a new line after the second loop is through
cout << endl;
}
}
}
First loop you should either start from 0 or change condition to <=
for( int i = 0; i < len; ++i )
or this
for( int i = 1; i <= len; ++i )
Though first one is more usual for C++ as commonly used to iterate over array indexes (from 0 to N-1). In your case it is irrelevant.
In the second loop you have to change condition to <= and start from the same number as i, so either:
for( int i = 0; i < len; ++i )
for( int j = 0; j <= i; ++j )
or
for( int i = 1; i <= len; ++i )
for( int j = 1; j <= i; ++j )
This has been annoying me for most of the day..
Suppose that I have the following vector:
v = [1, 2, 4, 9]
I transpose this, so the vector is in columns:
v = [1, 2
4, 9]
I do this, using the following method:
for(unsigned i=0; (i < cols); i++)
{
for(unsigned j=0; (j < 2); j++)
{
std::cout << vect[i*2+j] << " ";
}
std::cout << std::endl;
}
But how would I calculate the columns, first? My aim is to achieve the following:
(1 + 4)/2 = 2.5
(2 + 9)/2 = 5.5
Therefore, a resulting vector would return the mean matrix: x = [2.5, 5.5]
I have tried the following:
double summation = 0;
for(unsigned i=0; (i < cols); i++)
{
for(unsigned j=0; (j < size); j++)
{
summation += values[i*(i*j)+j];
}
std::cout << summation << std::endl;
}
Which produces:
3
8
I am probably missing something really stupid here, but, I can't seem to figure out what.
I have also tried to have a variable subRow which begins at 0 and increments each time by 3 but this did not work either.
Your last sentence has the right idea, but not quite the right number. Where you mention 3, it appears you need 2. That's normally called the "stride". Using it, averaging by columns would come out something like this:
for (int i=0; i<stride; i++) {
double total = 0;
for (int j=0; j<input.size(); j+=stride)
total += input[j];
result[i] = total / (j.size()/stride);
}
At least for the moment, this takes for granted that the size of the input matrix really is "correct" --i.e., an even multiple of the stride you specify.
You may find it easier to debug if keep your index calculations simple:
std::vector<int> v{1, 2, 4, 9};
const unsigned int WIDTH = 2;
for (unsigned int i = 0; i < WIDTH; ++i)
{
double sum = 0.0;
for (unsigned int j = i; j < v.size(); j += WIDTH)
{
sum += v[j];
}
// do something with sum
}
Your problem appears to be here: for(unsigned j=0; (j < size); j++)
You are starting j at 0 and increment by 1 to size() each time. Most of the values you hit will not be valid for what you are trying to do.
int v[] = {1,2,4,9};
int cols = 2;
int rows = 2;
for(int c=0 ; c < cols ; c++) {
double sum=0;
for(int r=0 ; r < rows ; r++)
sum += v[cols*r+c];
std::cout << sum /rows << std::endl;
}
I have a 49 space one dimensional array declared as int boardArray [49]; and I also have a two dimensional 7x7 array declared as int boardArrayTwo [7][7]' I am trying to use nested for loops to throw the one dimensional array into the two dimensional array here is the code I am using to test it.
for (int i = 0; i > 50; ++i)
{
boardArray[i] = i; //fills the array with ints 0 - 48 to test
}
for (int x = 0; x >= 7; ++x)
{
for (int k = 0; k >= 7; ++k)
{
for (int n = 0; n >= 49; ++n)
{
boardArrayTwo[x][k] = boardArray[n];
cout << boardArrayTwo[x][k] << " " << endl;
}
}
}
I tried running this but nothing happens. Am I doing it wrong?
for (int x = 0; x >= 7; ++x)
{
for (int k = 0; k >= 7; ++k){
for (int n = 0; n >= 49; ++n)
{
this is wrong. x and k should be < 7 (and the third cycle shouldn't be used) :
for (int x = 0; x < 7; ++x)
{
for (int k = 0; k < 7; ++k){
boardArrayTwo[x][k] = boardArray[7*x + k];
EDIT:
like #Fabio Ceconello make me notice in his comment, even the first loop is wrong because of the inverted condition checks, it should be modified this way:
for (int i = 0; i < 49; ++i)
{
boardArray[i] = i; //fills the array with ints 0 - 48 to test
}
Apart from the inverted logic in the loops (which the others mentioned), there's no need for the third inner loop. Just put the attribution in the second inner loop:
boardArrayTwo[x][k] = boardArray[x * 7 + k];
EDIT:
I should also mention that all these literals aren't good practice, and I added one more (7) above. I'd rewrite the code as follows:
#define arrlen(x) (sizeof(x)/sizeof((x)[0]))
for (int i = 0; i < arrlen(boardArray); ++i)
{
boardArray[i] = i;
}
int stride = arrlen(boardArrayTwo[0]);
for (int x = 0; x < arrlen(boardArrayTwo); ++x)
{
for (int k = 0; k < stride; ++k)
{
boardArrayTwo[x][k] = boardArray[stride * x + k];
cout << boardArrayTwo[x][k] << " " << endl;
}
}
caveat: if the arrays aren't declared here (were passed as parameters), arrlen() won't work. But that's another long story...
It looks like your destination array is in row-major order. You could just blast the source array directly into place.
memcpy(boardArrayTwo, boardArray, 49 * sizeof(int));
or if you prefer something in more idiomatic C++:
std::copy(boardArray, boardArray + 49, reinterpret_cast<int*>(boardArrayTwo));
You used i > 50 in your for loop. It should be i < 49 and same for all the other loops.
Also, this won't work. You're setting all of the boardArrayTwo[][] values to boardArray[49] You should instead do something like this:
for (int x = 0; x < 7; ++x)
{
for (int k = 0; k < 7; ++k)
{
boardArrayTwo[x][k] = boardArray[7*x + k];
cout << boardArrayTwo[x][k] << " " << endl;
}
}
or
int count = 0;
for (int x = 0; x < 7; ++x)
{
for (int k = 0; k < 7; ++k)
{
boardArrayTwo[x][k] = boardArray[count];
cout << boardArrayTwo[x][k] << " " << endl;
count++;
}
}
First of all, the second term in the for loop says the for loop would run while that condition is true. So you should use < instead of >= for all your loops.
Second, the loop over n is extra and shouldn't be there. What you need is to go through x and k, then copy the corresponding element from boardArray to boardArrayTwo.
You could do one of these:
int n = 0;
for (int x = 0; x < 7; ++x)
for (int k = 0; k < 7; ++k)
{
boardArrayTwo[x][k] = boardArray[n];
++n;
}
or use a formula to calculate the proper n:
for (int x = 0; x < 7; ++x)
for (int k = 0; k < 7; ++k)
boardArrayTwo[x][k] = boardArray[x*7+k];
I wrote x*7+k because it seems like x is iterating over the rows of the array, each row having 7 elements, says that x*7+kth element of the boardArray represents position [x][k] of boardArrayTwo/
Note
for (int i = 0; i > 50; ++i)
if i is initialized to 0, it won't be greater than 50 and thus it will never enter the loop.
In each of your loops you used greater than or equal (>) to rather than less than (<) or equal to. You should also notice that, as Fabio points out above, the third nested loop is setting boardArrayTwo[x][k] to 0-49 over and over again, 49 times. You will need to use arithmetic to manipulate x and k so that they will be an index into boardArray, and then assign that index to boardArrayTwo[x][k].
It's also important that you are using 0..7 inclusive, which is actually 8 positions. Your array are only of length 7 so you are actually ending up with some garbage values in there.
#include <iostream>
using std::cout;
using std::endl;
int main () {
int boardArray[49];
int boardArrayTwo[7][7];
for (int i = 0; i < 50; ++i)
{
boardArray[i] = i; //fills the array with ints 0 - 48 to test
}
for (int x = 0; x < 7; ++x)
{
for (int k = 0; k < 7; ++k)
{
boardArrayTwo[x][k] = boardArray[x*7 + k];
cout << boardArrayTwo[x][k] << " " << endl;
}
}
}
With any luck (unless I am embarrassing myself) this should do the trick!
EDIT: Special thanks to Fabio!
for(int i=0; i<49; i++)
b[i]=(i+1);
int p=0;
for(int i=0;i<7;i++){
for(int j=0;j<7;j++)
{a[i][j]=b[p];
p++;}
}
beside other errors, third loop is making your code wrong