How to break inner loop but the loop still increment [closed] - c++

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
for (int j=1; j<path.size(); j++) {
//do something
for (int z=0; z<path.size(); z++) {
//do something
}
break;
}
The inner loop can loop from 0 until it hits the end of the path size, but the outer loop just keeps giving me j=1 instead of doing the increment like inter loop does.
How can both loop do the increment at same time? I was trying to delete the break; but z loop through path.size()'s times.

The inner loop executes completely for every iteration of the outer loop, that's why you see z going looping path.size() times. After this your loop stops due to break so it won't iterate a second time over outer loop. So even if condition of outer loop is still true it won't even check it since you're breaking out of your loop.

Try running this test program with and without the break
for (int j=1; j<5; j++) {
printf("j=%d\n",j);
for (int z=0; z<5; z++) {
printf("z=%d\n",z);
}
break; // next time try to remove this break
}
and you might get enlightened.
If you want j and z to be counted up in parallel the you might want something like this
for (int j=1, z= 1; j<5; j++, z++) {
printf("j=%d\n",j);
printf("z=%d\n",z);
}

for(int j = 1 ; j < path.size() ; j++){
do something
for (int z = 0 ; z < j ; z++){
do something
}
I think that's what you're looking for

Related

Primitive operations and running time [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
For the given pseudo code I have to determine primitive operations and running time:
for( i=0; i<n; i++) ->1+n+n=2n+1
a[i] = 0; ->?
for( i=0; i<n; i++ ) ->2n+1
for( j=0; j<n; j++ ) ->n(2n+1)
a[i] += a[j] + i + j; ->?
Anyone to help me if it's correct and how to do the rows which I have put ?. please
As far as I understand, the for loop instruction going from 0 to n times would be executed n+1 times (once extra when loop index equals n itself, after which it breaks), so it would be n+1 and not 2n+1. Its contents would run for n times. Assigning values doesn't add additional complexity in terms of input size (n):
for(i = 0; i < n; i++) // 1+n
a[i] = 0; // runs for n times
Likewise, for the nested loops, the inner-loop statement will run for n+1 times, multiplied by n, as it in itself is the content of the outer loop, making the product of n(n+1). The contents would run for n*n times.
for(i = 0; i < n; i++) // n+1
for(j = 0; j < n; j++) // n(n+1) => n*n+n
a[i] += a[j] + i + j; // runs for n*n, for the dominant factor
With the innermost statements running for n*n times, the overall asymptotic time complexity would be O(n2).

Do different/older processors run c++ code differently? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I was coding a function that loops through a 2d array, if the current element in the array is less than the element next to it, then I would add 1 to my int counter variable. The issue is, when I run the code on my windows based machine with a AMD ryzen 7 processor, it works correctly and the counter gets to 20 (on a 5x5 array). But when I run it on my 2014 Macbook with a intel core i5 processor, on both MacOS and Windows 10 (bootcamp) the counter only gets to 19 using the same exact block of code. Here is my loop
int counter = 0;
for(int i=0; i < ROWS; i++){
for(int j=0; j < COLUMNS; j++){
if(board[i][j] < board[i][j + 1]){
counter += 1;
}
}
}
I would think this would work in any situation.
Well it would be nice to have a minimal reproducible example like others said, I think I can see it from here.
using j+1 will let the index go out of bounds causing undefined behaviour.
Try :
for(int i=0; i < ROWS; i++){
for(int j=0; j < COLUMNS - 1; j++){
if(board[i][j] < board[i][j + 1]){
counter += 1;
}
}
}
This should avoid that problem by simply stopping one sooner

How can I clear the variable after while loop is done [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I'm writing a program that multiplies matrices. And here I have got two variables "i" and "q" which at the beginning are both 0. While the loops proceed variables ("i" and "q") change their values. However after the loops are done I need "i" and "q" to come back to the value 0, so the loops can repeat themselves for different "w" and "k" . How can I do so??
int wynik[x][z]; //table that holds the result of the multiplication
int i=0;
int q=0;
int wyn=0;
for(int w=0; w<x; w++)
{
for(int k=0; k<z; k++)
{
while((i<y) && (q<v) )
{
wyn = (tab1[w][i] * tab2[q][k]) + wyn;
i++;
q++;
}
wynik[w][k] = wyn;
}
}
set those to 0 after the outer loop is done:
int wynik[x][z]; //table that holds the result of the multiplication
int i=0;
int q=0;
int wyn=0;
for(int w=0; w<x; w++)
{
for(int k=0; k<z; k++)
{
while((i<y) && (q<v) )
{
wyn = (tab1[w][i] * tab2[q][k]) + wyn;
i++;
q++;
}
wynik[w][k] = wyn;
}
//HERE
i = 0;
q = 0;
}
I feel like the most natural way according to your current design would be to change the most inner while loop into for (int i = 0, q = 0; (i < y) && (q < v); i++, q++). This lets for loop manage modification of i and q and both are inside the scope of the inner for loop since they are not needed anywhere else.
I would rethink the design. It sounds like a great example to study some algorithms.
Just dropping this here ;)
https://en.wikipedia.org/wiki/Matrix_multiplication_algorithm

How do I clean up these nested for loops? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
NOTE: Bad code ahead. You've been warned.
This code iterates through all elements in all 3x3 squares in a Sudoku puzzle. The way shown below is that it gets the coordinate of the upper-left-hand element for each square then iterates through each element in that square. This means that there will be a total of 4 "for" loops needed to just access the correct index, and then another "for" loop to do the correct action.
This code will work (if the retracted code were put in), but it looks very messy and is very hard to read. Is there a better way to do it that eliminates these nested "for" loops?
Thanks in advance.
void Sudoku::updateSquares(int grid[9][9], int possibleSolutions[9][9][10])
{
for (int i = 0; i < 9; i += 3)
{
for (int j = 0; j < 9; j += 3) //for every square:
{
//Other code
//...
//Other code
//updates the possibleSolutions array
for (int k = 0; k < 3; k++)
{
for (int l = 0; l < 3; l++) //for every element in every square:
{
if(grid[i+k][j+l] != 0)
continue;
for (int n = 0; n < 10; n++)
{
if(possibleSolutions[i+k][j+l][n] != 0 && numbers[n] == 0)
{
possibleSolutions[i+k][j+l][n] = 0;
possibleSolutions[i+k][j+l][0] -= 1; //reduce the size, which is held in [][][0]
}
}
}
}
}
}
}
You have implemented something called as "Exhaustive Searching" which is essentially trying out every possible combination of squares.
Have you heard about something called loop unwinding ?
--> Instead of 5 nested For loops use fewer nested loops multiple times; something like 2 nested loops .
Use a dynamic programming approach which is probably O(n^2)
Top Coder DP example.

How to exit (go to next element of parent loop) a for loop inside a for loop

for (int i = 0; i<10; i++)
{
//do some validation for record length
//if it is not valid
continue; // goes to the next iteration in for loop for 'i'
for (int j = 0; j<5; j+=2)
{
//do some more validation for individual record
//if it is not valid
Here it should go to the next i if i use continue. Here it will go to the next j
Can anyone please let me know how to do this?
You need to specifically test for a flag in the outer loop if there is something after the inner loop:
for(some_outer_vars){
bool should_skip = false;
// ...
for(some_inner_vars){
// ...
if(your_condition){
should_skip = true;
break;
}
}
if(should_skip)
continue;
// ...
}
Using break; inside the j loop will exit the j loop completely.
But at least spend a couple minutes deciding if an alternate algorithm, approach, or termination condition could remove the need to break in the middle of a loop.
Do you have anything after the inner loop? If not, you can just use break:
for (i = 0; i < 10; i++)
{
if (i is no good)
continue;
for (j = 0; j < 5; j++)
{
if (j is no good)
break;
}
}
If you do need to do something later, you can use break in combination with some other flag.
Place break; instead. This should get you out of the inner loop.
for (int i = o; i<10; i++)
{
}
for (int j = 0; j<5; j+=2)
{
break;
}
"break;" will end your current j loop and go to the next i.
If you can't arrange the logic so that break in the inner loop gets straight to continuing the outer loop, then do this:
for (int i = 0; i<10; i++)
{
if (!valid(i)) continue;
for (int j = 0; j<5; j+=2)
{
if (!valid(i,j)) goto continue_i;
do_whatever_with_i_and_j()
}
more_stuff_here();
continue_i:
}
There, I've said it. The code is shorter, simpler, easier to read and easier to analyse than the version that sets a flag, then breaks, then immediately checks the flag again and conditionally continues.
Another option is this
void inner_loop(int i) {
if (!valid(i)) return;
for (int j = 0; j<5; j+=2)
{
if (!valid(i,j)) return;
do_whatever_with_i_and_j()
}
more_stuff_here();
}
for (int i = 0; i<10; i++)
{
inner_loop(i);
}
Depending what the inner loop does, though, you might find yourself building quite a mechanism to give it access to whatever it's supposed to modify.
Community wiki, because this (or situations like it) has been argued so many times on SO as to practically define "subjective and argumentative".
I try to avoid break and continue when dealing with loops because they are easy to miss and their meanings change if you have to restructure the code later. You can use j=5; when you need to exit the inner loop. If you add a third loop or a switch the meaning of that line doesn't change. Sometimes you will need to add if statements inside your loops testing i and j or even a new variable like bool iIsInvalid but I think that makes the control flow easier to read.