how to break the outer loop within the inner loop [duplicate] - loops

This question already has answers here:
How to break out of nested loops in Go?
(6 answers)
Closed 6 days ago.
for i := 0; i < 5; i++ {
fmt.Println("i is", i)
for j := 0; j < 3; j++ {
if j == 2 {
break
}
fmt.Println("j is ", j)
}
}
I want this code to break the program if the i was equal to 2. how can I signal that I wanna break the outer loop within the inner loop ?
I can't figure it out how to break or continue the outer loop

outerLoop:
for i := 0; i < 5; i++ {
for j := 0; j < 3; j++ {
if i == 3 {
break outerLoop
}
fmt.Println(i, j)
}
}
here is the answer . you can use labels in Go to refer to different loops

Related

How to out from looping without running the script below

i want to out from second looping to first looping (like break) but after break i dont want to print fmt.Println("The value of i is", i). How is the algorithm?
package main
import "fmt"
func main() {
for i := 0; i < 2; i++ {
for j := 0; j < 4; j++ {
if j == 2 {
fmt.Println("Breaking out of loop")
break
} else {
fmt.Println("j = ", j)
}
}
fmt.Println("The value of i is", i)
}
}
Edit: You edited you code, so here's the edited answer for that.
To continue the outer loop from the inner (breaking the inner loop and skipping the rest of the outer loop), you have to continue the outer loop.
To address the outer loop with the continue statement use a label:
outer:
for i := 0; i < 2; i++ {
for j := 0; j < 4; j++ {
if j == 2 {
fmt.Println("Breaking out of loop")
continue outer
} else {
fmt.Println("j = ", j)
}
}
fmt.Println("The value of i is", i)
}
This will output (try it on the Go Playground):
j = 0
j = 1
Breaking out of loop
j = 0
j = 1
Breaking out of loop
Original answer:
break always breaks from the innermost loop (more specifically a for, switch or select), so after that the outer loop will continue with its next iteration.
If you have nested loops and from an inner loop you want to break from the outer loop, you have to use labels:
outer:
for i := 0; i < 2; i++ {
for j := 0; j < 4; j++ {
if j == 2 {
fmt.Println("Breaking out of loop")
break outer
}
fmt.Println("The value of j is", j)
}
}
This will output (try it on the Go Playground):
The value of j is 0
The value of j is 1
Breaking out of loop

For loop in C and how it works?

#include <stdio.h>
int main() {
int i, j;
for (i = 2; i < 20; i++) {
for (j = 2; j <= (i/j); j++) {
if (!(i%j)) break;
}
if (j > (i/j)) printf("%d\n", i);
}
return 0;
}
I am a Beginner at C and trying to understand how the for loop works. My question is at the 4th iteration, the condition in the nested loop will return TRUE
(j < (i/j)) // 2 <= 4/2
and the first if statement will also return TRUE because of NOT operator
(!(i%j)); // 4/2 = !(0)
so now the value of j = 3 because of incrementation, but why the second if statement did not print the output if it is TRUE?
(j > (i/j)); // 3 > 4/3
You're breaking out of the loop before j is incremented, so j is still 2, not 3
A break statement ends its nearest enclosing loop prematurely. Everything after it (and that includes the third statement of the for loop), will not occur.
So j is still 2 when the condition for printing is checked, like Mark answered.

continue statement inside nested for loop

I don't understand what exactly does the continue statement inside this for loop do. How is code any different if I remove it? Which lines does it skip if it's placed at the end of for loop?
int sum = 0, i, j, stop = 0;
for( i = 1; i <= 5 && !stop; i++)
{
for( j = 1; j <= 5 ; j++)
{
if (j%4 == 0)
{
stop = 1;
continue;
}
sum += i+j;
}
}
printf("%d\n", sum);
If you run this program the sum is going to be 15, and if you comment out countinue line then it's going to be 20.
It would be more clear if you would format the code. Let's consider the inner loop
for( j = 1; j <= 5 ; j++)
{
if ( j % 4 == 0)
{
stop = 1;
continue;
}
sum += i+j;
}
Thus as you see if j % 4 == 0 then statement
sum += i+j;
is skipped.
As for the code in whole then it has no any sense.:) It is a silly code.
In fact your code is equivalent to the following
int sum = 0, j;
for( j = 1; j <= 5 ; j++ )
{
if ( j != 4 ) sum += j + 1
}
printf("%d\n", sum);
So you will get sum 2 + 3 + 4 + 6 that is equal to 15.:)
The continue statement skips the remainder of the current loop. In the case of nested loops, it skips to the next iteration of the innermost loop.
In this case, if you didn't continue, you would execute sum += i+j; in every iteration, where it appears you only want it sometimes.
That being said, this is a very awkward loop to begin with. The whole stop variable is rather ill conceived from the get-go anyway.
The continue statement is used to start the next iteration of a loop,skipping everything in the loop,after the continue. In your case,once the execution of the program reaches the continue statement,then the next iteration of your inner loop starts,skipping whatever there was after the continue. It skips sum += i+j; as it is after the continue and the sum will not be added when j is 4 as j%4 will be 0. This is why you get 20 when you comment the continue and 15 when you uncomment it.
P.S: Your outer loop will execute only once as stop will be changed inside the if in your inner loop.
continue causes the enclosing for loop to begin the next iteration. As a more basic example, take the following code:
for(int i = 0; i < 50; i++)
{
if(i % 2 == 1) // If it's odd
continue;
printf("%d\n", i);
}
In this case, the continue statement will cause the for loop to immediately begin the next iteration if i is odd, hence this code will print the even numbers between 0 and 50.
int sum = 0, i, j, stop = 0;
for( i = 1; i <= 5 && !stop; i++)
{
for( j = 1; j <= 5 ; j++)
{
if (j%4 == 0) <===== is j divisible by 4 ?
{
stop = 1; <=== set stop flag, will continue for J loop
but stop next I loop and end the routine
continue; <==== skip the rest of the J loop for this itteration
}
sum += i+j;
}
}
printf("%d\n", sum);
http://msdn.microsoft.com/en-us/library/0ceyyskb.aspx explains the continue statement

How can I print a x by x matrix in C?

int main() {
char gameArea[][8] = {
{'X','X','X','X','X','X','X','X'},
{'X','X','X','X','X','X','X','X'},
{'X','X','X','X','X','X','X','X'},
{'X','X','X','X','X','X','X','X'},
{'X','X','X','X','X','X','X','X'},
{'X','X','X','X','X','X','X','X'},
{'X','X','X','X','X','X','X','X'},
{'X','X','X','X','X','X','X','X'}};
int i = 0; int j = 0;
while (i<8) {
while (j<8) {
printf("%c",gameArea[i][j]);
j++;
}
i++;
}
return 0;
}
Output:
XXXXXXXX
Process returned 0 (0x0) execution time : 0.563 s
Press any key to continue.
In theory, the i would run through the columns, and print all of it, but that's not what happened. I thank you very much for your help.
I think you want a for-loop:
for (int i = 0; i < 8; ++i) {
for (int j = 0; j < 8; ++j) {
printf("%c", gameArea[i][j]);
}
printf("\n");
}
This is the progression of your loops:
i = 0 and j = 0, print X and increment j.
...
i = 0 and j = 7, print X and increment j.
Since j = 8, stop j-loop and increment i.
i = 1 but j is still 8 as we cannot perform j-loop, so increment i.
...
i = 7 but j is still 8 as we cannot perform j-loop, so increment i.
Now i = 8 so stop i-loop.
What you want to do is after the j-loop when you increment i you also want to reset j to 0. Along with that, you want to print a new-line for the next row otherwise you'll end up with 64 consecutive Xs.
Using a for-loop:
for (/*initialization*/; /*condition*/; /*increment*/) {
/*loop body*/
}
Is a short-cut for doing this with a while-loop:
/*initialization*/
while(/*condition*/) {
/*loop body*/
/*increment*/
}
You need to set j back to zero after each inner loop
printf("%c",gameArea[i][j]);
j++;
}
j = 0;
i++;
But for loop is more suitable for your task, as stated in other answers.
After the first while (j<8) loop, nothing resets j to 0, similarly for i, so the loops only run once, hence only one row is printed.
Consider using for loops:
for (int i = 0; i < 8; i++)
Also, did you try debugging the code, i.e. setting breakpoints and stepping through the execution?
The j counter needs to be initialised at the start of each i loop.
What's happening is j is looped once, at the end j is 8 so the j loop is only iterated once.
while (i<8) {
int j = 0;
while (j<8) {
printf("%c",gameArea[i][j]);
j++;
}
i++;
}
Insert a j=0:
while (i<8) {
j = 0;
while (j<8) {
printf("%c",gameArea[i][j]);
j++;
}
i++;
}
Without it your inner loop will be executed only once, since j never changes after the first run and the loop condition is not met again.
As other users suggested, you might want to use for loops with sort of thing.
int i = 0; int j = 0;
while (i<8) {
while (j<8) {
printf("%c",gameArea[i][j]);
j++;
}
i++;
printf("\n")
}
You need to reset j to 0 at the beginning of the first while loop, so that on each iteration, you can still loop through the inner one. Otherwise, once j is equal to 8, the inner loop will not be entered anymore.

What is Innermost loop in imperfectly nested loops?

Helo, I'm a bit confused about the definition of an inner loop in the case of imperfectly nested loops. Consider this code
for (i = 0; i < n; ++i)
{
for (j = 0; j <= i - 1; ++j)
/*some statement*/
p[i] = 1.0 / sqrt (x);
for (j = i + 1; j < n; ++j)
{
x = a[i][j];
for (k = 0; k <= i - 1; ++k)
/*some statement*/
a[j][i] = x * p[i];
}
}
Here, we have two loops in the same nesting level. But, in the second loop which iterates over "j" starting from j+1, there is a again another nesting level. Considering the entire loop structure, which is the inner most loop in the code ?
Both j loops are nested inside i equally, k is the inner most loop
Lol I don't know how to explain this so i'll give it my best shot I recommend using a debugger! it may help you so much you won't even know
for (i = 0; i < n; ++i)
{
//Goes in here first.. i = 0..
for (j = 0; j <= i - 1; ++j) {
//Goes here second..
//Goes inside here and gets stuck until j is greater then (i- 1) (right now i = 0)
//So (i-1) = -1 so it does this only once.
/*some statement*/
p[i] = 1.0 / sqrt (x);
}
for (j = i + 1; j < n; ++j)
{
//Goes sixth here.. etc.. ..
//when this is done.. goes to loop for (i = 0; i < n; ++i)
//Goes here third and gets stuck
//j = i which is 0 + 1.. so, j == 1
//keeps looping inside this loop until j is greater then n.. idk what is n..
//Can stay here until it hits n.. which could be a while.
x = a[i][j];
for (k = 0; k <= i - 1; ++k) {
//Goes in here fourth until k > (i-1).. i is still 0..
//So (i-1) = -1 so it does this only once
/*some statement*/
a[j][i] = x * p[i];
}
//Goes here fifth.. which goes.... to this same loop!
}
}
I'd say that k is the inner-most loop, because if you count the number of loops required to reach it from the outside, it's three loops, and that's the most out of all four of the loops in your code.

Resources