My first nested for loop - c++

I am trying out my first nested for loop and I can't seem to see the problem. As the code is written, all 9 values come out as the number '9'. I want them to be 1 through 9.
int arraySize = 9;
for (int i = 0; i < arraySize; i++)
{
for (int j = 1; j < (arraySize + 1); j++)
{
gameBoard[i] = j;
}
}
Been looking at this too long - I am sure the solution is obvious... Thanks for the help.

Your outer loop goes through each slot in the array.
Your inner loop assigns 1 through 9 to current slot of the array.
Since the last assignment of your inner loop is 9, you have an array full of 9s.
You don't need nested loops for this. As Log1c mentioned above, you can do this with a single loop:
for (int i = 0; i < arraySize; i++)
{
gameBoard[i] = i + 1;
}

Related

How to initialize a character or string array using for loop in c++?

I want to make a 2 dimensional array of 13 rows and 6 columns all initialized with character X. to do so I'm doing this.
char myseats[13][5];
for (int i; i < 13; i++)
{
myseats[i] = { 'X' };
for (int j; j < 5; j++)
{
myseats[j] = {'X'};
}
}
}
however this gives me a error and the array wont initialize with X, same is the case with string. How can I achieve my purpose can anyone please help me?
If you want to access fields of two dimensional array, you should use myseats[i][j] (first you specify row, then the column). Also, your for loops are written incorrectly. When you initialize any variable in the body of for loop, you should assign its value (otherwise i and j can have any value that can be saved in int). Your code should look like that:
char myseats[13][5];
for (int i = 0; i < 13; i++)
{
for (int j = 0; j < 5; j++)
{
myseats[i][j] = {'X'};
}
}
Try this:
char myseats[13][5];
for (int i = 0; i < 13; i++)
{
for (int j = 0; j < 5; j++)
{
myseats[i][j] = 'X';
}
}
First, the i and j where not initialized in the loop. You need to define at what index you want them to start.
Second, the correct way to access a two dimensional array is with the syntax array[row_index][column_index] = 'your_desired_value_here'.

Understanding what happens within function loop

I would like to know why the inner for loop executes. My understanding is that since j = 1 and i = 0, j <= i; would produce nothing as j is already greater than i. Therefore, the inner loop would be skipped, producing the same result as the initial array.
void sortArray(int myArray[], int size)
{
int num1 = 0;
int num2 = 0;
int temp = 0;
for (int i = 0; i < size; i++)
{
int first = 0;
for (int j = 1; j <= i; j++)
{
if (myArray[j] > myArray[first])
{
first = j;
}
temp = myArray[first];
myArray[first] = myArray[i];
myArray[i] = temp;
}
}
}
The inner loop is skipped during first iteration. After i is incremented, j is now equal to i, therefore the inner loop will execute 1 time. Inner loop exits, outer loop increments i by 1, inner loop now iterates twice as i == 2.
This will repeat until i == size - 1 OR i < size (same condition, different wording).
The inner loop should skip for 1 iteration of the outer loop then will run for 1 time as j<=i returns true. (first iteration i=0, second iteration i=1)
this is equivalent to:
for (int j = 1; j <= 0; j++)
After that the second loop will run 1 time equivalent to
for (int j = 1; j <= 1; j++)
and so on..
for (int j = 1; j <= 2; j++)

What does a semicolon after for-loop means? Why is there a j++ in first loop statement?

I need to implement my own version of Dijkstra algorithm based on priority queues, and while searching some sites about it, I saw an algorithm that actually works but with strange for-loop statements:
int i,j,n;
cin >> n; //number of vertexes
bool *QS = new bool [n];
//whole QS is set to false here
for(i = 0; i < n; i++) {
for(j = 0; QS[j]; j++);
for(u = j++; j < n; j++)
if(!QS[j] && (d[j] < d[u])) //d[i] is table of distances
u = j;
QS[u] = true;
//some code
}
I know that ; after loop means it's empty statement, but if I comment second for-loop this program stops working, so it actually means something. I believe that this u = j++ was meant to be like start form u = j+1, but I'm not so sure.
for(j = 0; QS[j]; j++); is used as j=0; while(QS[j])j++;
i.e. to find the first j that QS[j] is false
for(j = 0; QS[j]; j++);
sets j to 0 and then increments j until the first element in QS that is false. You then use that value for the initial value of the third loop.
It is a cleaver way to write it but you can be a lot more expressive on what it is doing using std::find and std::distance like
for(i = 0; i < n; i++) {
int j = std::distance(std::begin(QS), std::find(std::begin(QS), std::end(QS), false));
for(u = j++; j < n; j++)
if(!QS[j] && (d[j] < d[u])) //d[i] is table of distances
u = j;
QS[u] = true;
//some code
}
which explicitly states that j will be the distance from the beginning of the array to the first false element.
the second for loop walks through all of the array QS which is an
array of booleans. Which will break when one is false, saving the current value of j and starting the next loop with that value +1.

How do I implement this bubble sort differently?

I'm looking to implement a bubble sort. I have the following code that I wrote, which uses a for loop inside of a do loop. How can I make this into a bubble sort that uses two for loops?
Here's my code:
do {
switched = false;
for (int i = 1; i < size; i++) {
if (a[i] < a[i-1]) {
int temp = a[i];
a[i] = a[i-1];
a[i-1] = temp;
switched = true;
}
}
} while (switched);
(This is tagged homework, but this is studying for the final exam, not actual homework.)
Because you know the last element in the list will always be sorted (since it bubbled up to the top) you can stop there.
for(int x = size; x >= 0; x--) {
bool switched = false;
for(int i = 1; i < x; i++) {
if(blah) {
// swap code here
switched = true;
}
}
if(!switched) break; // not the biggest fan of this but it gets the job done
}
A bit obligate, but hey, you asked for it:
for(bool switched=true; switched;)
{
switched = false;
for (int i = 1; i < size; i++) {
if (a[i] < a[i-1]) {
int temp = a[i];
a[i] = a[i-1];
a[i-1] = temp;
switched = true;
}
}
}
Two for loops...
Since the maximum number of times your inner loop will run is size times, you know that the outer loop only can be bound by size.
for (int x = 0; x < size; x++ )
{
switched = false;
for (int i = 1; i < size; i++)
{
if (a[i] < a[i - 1])
{
int temp = a[i];
a[i] = a[i - 1];
a[i - 1] = temp;
switched = true;
}
}
if(switched)
{
break;
}
}
A simple improvement to bubble sort is to remember the last location where a swap occurred. After each pass the elements beyond that point are sorted. Next time through the loop only iterate up to the previous high water mark.
void bubble_sort(int *arr, int size)
{
for (int hwm; size > 1; size = hwm)
{
hwm = 0;
for (int i = 1; i < size; ++i)
{
if (arr[i] < arr[i-1])
{
std::swap(arr[i], arr[i-1]);
hwm = i;
}
}
}
}
You can run the inside loop size times instead of checking switched, by having an outer loop for(int j=0; j<size; ++j). To make it slightly less badly inefficient you can make the inner loop 1 step shorter each time.
The first full pass through the loop (that is, the first iteration of your outer do loop) is guaranteed to put the largest element in position a[size - 1]. (Do you see why?) The next full pass is guaranteed not to change that, and, in addition, to put the second-largest element in position a[size - 2]. (Again, do you see why?) And so on. So the first pass needs i to go from 1 to size - 1, but the second only needs i to go from 1 to size - 2, the third only needs i to go from 1 to size - 3, and so on. Overall, you need at most size - 1 passes (with the last pass just covering position 1 and comparing a[1] to a[0] to make sure the smallest element is in place).
So, your outer for-loop needs to vary max_i, initially set to size - 1 and ending up at 1, and your inner for-loop needs to vary i from 1 to max_i.
Think about the maximum number of times the do loop can execute.
A really silly method to use two for loops would be as follows:
for(bool switched=true;switched;)
{
switched=false;
for(int i=1; i<size; ++i)
{
if (a[i] < a[i-1])
{
int temp = a[i];
a[i] = a[i-1];
a[i-1] = temp;
switched = true;
}
}
}
A more serious answer might be as below... but now that I think about it this probably is not bubble sort:
for(int i=0; i<(size-1); ++i)
{
for(int j=(i+1); j<(size-1); ++j)
{
if(a[i]>a[j])
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}

Outputted array values different from the values stored

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.