Question

I've searched SO and can find questions addressing similar subjects, but nothing for this specific question and language. After reading some Q&A and not finding the answer, I searched , and and got zero results.

I've been asked this question in a university quiz:

If I have:

int n = 3;
   for (int i = 1; i <= n; i++)  {
      System.out.print(" x ");
        for (int j = 1; j <= n; j++)  {
         System.out.println(" x ");
           continue;
           //no content here
        }
     }

Without there being any content after the continue statement; how does this using continue affect this loop? Does it cause a break in the second loop of does the loop continue to iterate?

Was it helpful?

Solution 2

If there was a code under continue, it'll be a dead code (unreachable code).

The way you wrote it, it has no effect since it's already the last line. The loop would have continued if there was no continue;.

These two blocks of code have the same effect:

for(int i = 0; i < 10; i++) {
   // .. code ..
}

for(int i = 0; i < 10; i++) {
   // .. code ..
   continue;
}

However, the below snippet has unreachable code:

for(int i = 0; i < 10; i++) {
   // .. code ..
   continue;
   // .. unreachable code ..
}

OTHER TIPS

A continue statement without a label will re-execute from the condition the innermost while or do, or loop, and from the update expression the innermost for loop. It is often used to early-terminate a loop's processing and thereby avoid deeply-nested if statements.

Hence for your program , the keywork continue doesn't make much sense. It is used as a kind of a escape thing. For e.g:

aLoopName: for (;;) {
  // ...
  while (someCondition)
  // ...
    if (otherCondition)
      continue aLoopName;

Say, if you modify your program like:

int n = 3;
   for (int i = 1; i <= n; i++)  {
      System.out.print(" x ");
        for (int j = 1; j <= n; j++)  {
         if(j%2!=0)
         {
          System.out.println(" x ");
          continue;
         }
         else
         break;
     }

This will break the inner for loop for j=2. Hope you understand. :)

The answer to your question:

How does this using continue affect this loop? Does it cause a break in the second loop of does the loop continue to iterate?

is:

The second loop will not break, it will continue to iterate. break keyword is for breaking loop.

EDIT

Suppose you have for loop:

for(int i = 0; i < 5; i++){
   continue;
}

continue in for executes the statement of for loop (i++) to continue to the next iteration.

In other loops, while{} or do{}while(); the things will not be like this and may cause infinite loops.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top