FAQ: Loops - Jump Statements

This community-built FAQ covers the “Jump Statements” exercise from the lesson “Loops”.

Paths and Courses
This exercise can be found in the following Codecademy content:

Learn C#

FAQs on the exercise Jump Statements

There are currently no frequently asked questions associated with this exercise – that’s where you come in! You can contribute to this section by offering your own questions, answers, or clarifications on this exercise. Ask or answer a question by clicking reply (reply) below.

If you’ve had an “aha” moment about the concepts, formatting, syntax, or anything else with this exercise, consider sharing those insights! Teaching others and answering their questions is one of the best ways to learn and stay sharp.

Join the Discussion. Help a fellow learner on their journey.

Ask or answer a question about this exercise by clicking reply (reply) below!
You can also find further discussion and get answers to your questions over in Language Help.

Agree with a comment or answer? Like (like) to up-vote the contribution!

Need broader help or resources? Head to Language Help and Tips and Resources. If you are wanting feedback or inspiration for a project, check out Projects.

Looking for motivation to keep learning? Join our wider discussions in Community

Learn more about how to use this guide.

Found a bug? Report it online, or post in Bug Reporting

Have a question about your account or billing? Reach out to our customer support team!

None of the above? Find out where to ask other questions here!

Hello,
Here is a piece of source code.

using System;

class MainClass {
  public static void Main (string[] args) {
		for (int i=0; i<=10; i++) {
			if (i<5) {
				Console.WriteLine("Testing Act 1...");
				continue;
				Console.WriteLine("Testing Act 2...");
			}
			Console.WriteLine($"counter: {i}");
		}
		Console.WriteLine("Outside of loop...");
}
}

Can someone explain to me why “Testing Act 2…” is not printed?

This is in the C# section. The link of the lesson is this.

First time through the loop: i = 0. The if condition is true, so “Testing Act 1…” is printed, but then the “continue” keyword means all the rest of the loop is skipped and you go back to the top of the loop for the next iteration (this means the “Testing Act 2…” and the $“counter: {i}” are skipped).

Second time through the loop: i = 1. Same as above.

Same deal for i = 2 , i = 3 and i = 4.

In the i = 5 iteration, the if condition (i < 5) is no longer true, so none of the statements in the if {} block are executed. But the $“counter: {i}” is outside the if loop, so it will be printed and you will see “counter: 5” printed.

Same deal for i = 6, i = 7, i = 8, i = 9, and i = 10.
Finally “Outside of loop…” will be printed.

The output will look like:
Testing Act 1…
Testing Act 1…
Testing Act 1…
Testing Act 1…
Testing Act 1…
counter: 5
counter: 6
counter: 7
counter: 8
counter: 9
counter: 10
Outside of loop…

2 Likes

They switch the code from True to False. When done it correctly prints to the console 3 times, but if left True it only prints one time. Can someone explain what is happening here?

using System;

namespace JumpStatements
{
class Program
{
static void Main(string args)
{
bool buttonClick = false;
int times = 0;
do
{
Console.WriteLine(“BLARRRRR”);
times++;
if (times == 3)
{
break;
}

  } while(!buttonClick);
}

}
}

1 Like

There are two scenarios depending on the value of the bool variable buttonClick.

SCENARIO 1 (bool buttonClick = true;)
int times = 0; is initialized before the loop.
Then, we enter the do…while loop. The do…while loop is guaranteed to execute at least once, because in a do…while loop the condition is checked at the the end of an iteration (contrast this with a while loop in which the condition is checked before an iteration begins).
So, first time through: we print out BLARRRRR, times = 0 becomes times = 1. The if condition (times == 3) is false, so it is skipped.
Now, the loop condition is checked i.e. while(!buttonClick). Since buttonClick = true, so !buttonClick = false (Recall the ! operator flips true to false and vice versa). So while(!buttonClick) evaluates to false and we exit the do…while loop.
All said and done, BLARRRR only gets printed once.

SCENARIO 2 (bool buttonClick = false;)
int times = 0; is initialized before the loop.
So, first time through: we print out BLARRRRR, times = 0 becomes times = 1. The if condition (times == 3) is false, so it is skipped.
Now, the loop condition is checked i.e. while(!buttonClick). Since buttonClick = false, so !buttonClick = true. So while(!buttonClick) evaluates to true and we start the next iteration of the do…while loop.

Second time through: we print out BLARRRRR, times = 1 becomes times = 2. The if condition (times == 3) is false, so it is skipped.
Now, the loop condition is checked i.e. while(!buttonClick). Since buttonClick = false, so !buttonClick = true. So while(!buttonClick) evaluates to true and we start the next iteration of the do…while loop.

Third time through: we print out BLARRRRR, times = 2 becomes times = 3. The if condition (times == 3) is true, so the break statement in the if block is executed and we exit the do…while loop.

All said and done, BLARRRR gets printed thrice.


If you want to see BLARRRR printed 3 times, then you need the initialization bool buttonClick = false;
If you want to see BLARRRR printed 1 time, then you can leave the initialization as bool buttonClick = true;
Regardless of what you choose as initialization of buttonClick, the automatic grader will accept your code as long as you have followed the other instructions. In the solution, they used bool buttonClick = false; so that you could see BLARRRR being printed 3 times.

8 Likes

Thank you for the reply!

in simple words :

continue - just skip the current iteration flow and makes flow jump to next iteration
break - get out from the loop (so further iteration of loop doesn’t exist)
return - get out from the method and give the returned value… ( the control flow is returned to the place where the function is called )

put like if you understand …

1 Like

Why was break needed in this sample code from the lesson?

while (playerIsAlive) 
{ 
// this code will keep running

  if (playerIsAlive == false) 
  { 
    // eventually if this stopping condition is true, 
    // it will break out of the while loop
    break; 
   } 
 } 

It seems redundant there. I understand the use of break in other examples. But in the above example, it looks like the entire purpose of the ‘if’ statement containing the break is to tell the ‘while’ statement that it should stop when its run condition is no longer true. But the ‘while’ statement already knows that it should only run when its run condition is true. It’s like telling someone “If the light is green, you should go. But if the light is not green, then you should not go.” The latter is already implied by the former and doesn’t need to be said.

Is this break an intentional redundancy in case the while statement somehow experiences an error that prevents it from abiding by its run condition? If so, why would we rely on a redundancy instead of just fixing the error? I haven’t worked with long codes yet so maybe this is just my inexperience with errors talking.

1 Like

Perhaps they could have used a different sample code to demonstrate the use of break statements. But, I don’t think the condition within the loop is meant as a redundancy to account for any errors. There can be legitimate situations where the loop condition may have to be rechecked within the loop. Consider this hypothetical situation built upon the code sample mentioned by you:

while (playerIsAlive) 
{ 
// Create New Map. Prompt player to pick a room. 
// If there is an enemy in the room, commence battle.
// Update playerIsAlive status depending on whether player 
// wins (alive) or loses (dies).

 if (playerIsAlive == false) 
 { 
   break; 
  }

// Allow player to search room for items. Allow player to use/equip 
// items, food, weapons from inventory. Check player hunger level. 
// If hunger level is too high, the player should die and 
// playerIsAlive should be updated accordingly. 
} 

It makes sense to check the playerIsAlive variable before entering the loop because a dead player can’t carry out actions, so a while loop makes more sense than a do…while loop. If player fights a battle, the playerIsAlive variable should be checked and if player is dead, the loop should be exited immediately via a break statement. If player is alive, allow the player to carry out further actions and to use items/food. If player’s hunger is too high, the player should starve and playerIsAlive should be updated, but we won’t need to exit immediately because the looping condition will be checked at the beginning of the next iteration.

Hi! Can someone help me to understand the code example they give in this lesson (the game example).
For me, the way that the code is written, gives the impression that if you don’t have the right key, you’ll never get out of the WHILE loop. In what occasion the method UnlockDoor() would return FALSE?
I know there is a RETURNS FALSE in the end, but I don’t see how it could get away of the WHILE LOOP if you don’t have the right key, because then, keyFound is false, and you don’t enter in the “if” condition, but at the same time, you’re still in the while doorIsLocked ==true)…

class MainClass {
public static void Main (string args) {
UnlockDoor();

// after it hits the return statement, it will move on to this method
PickUpSword();
}

static bool UnlockDoor()
{
bool doorIsLocked = true;

// this code will keep running
while (doorIsLocked)
{
bool keyFound = TryKey();

  // eventually if this stopping condition is true,
  // it will break out of the while loop
 if (keyFound)
 {
  // this return statement will break out of the entire method
  return true;
 }

}
return false;
}
}

Yes, I don’t see how the UnlockDoor() method in the example would return false.

The TryKey() method hasn’t been shown in the example, but it is most likely a method which has some randomness built into it. The TryKey() method will return true/false either randomly OR some other logic which approximates randomness.
So, in the example snippet when UnlockDoor() method is called, the doorIsLocked variable is set to true. We then enter the while loop.

  • If the TryKey() method returns true, then we enter the if statement and exit the UnlockDoor() function by returning true.

  • If the TryKey() method returns false, we don’t enter the if statement. We do another iteration of the while loop. In the second iteration, we again call the TryKey() method. We keep repeating the iterations until eventually the TryKey() method returns true. Then we enter the if statement and exit the UnlockDoor() function by returning true. This of course assumes that TryKey() has some randomness built into it and will eventually return true. If there was no randomness and TryKey() always returns false, then we would indeed be stuck in an infinite loop.

1 Like

Hi! Thanks for your response :slight_smile: yeaah, … I was thinking about this example they give in this lesson and maybe of the RETURN FALSE was inside the WHILE LOOP, one bracket above from its current position in the code it would work well…
Thank you!!!

hello!
can someone please tell me why this wouldnt work? thnx

using System;

namespace JumpStatements
{
class Program
{
static void Main(string args)
{
bool buttonClick = true;
int pomCount = 0

  do
  {
    Console.WriteLine("BLARRRRR");
    pomCount++;
    continue: 
    if (pomCount == 3)
    {
      break;
    }

    
  } while(!buttonClick);
}

}
}

Why did you use continue?

  • Firstly, the correct syntax is continue; and not continue:
  • Secondly, continue isn’t appropriate in the code that you are writing.
  • If buttonClick is true, then you get lucky that you exit the loop after printing BLARRRR just once.
  • But, if buttonClick if false, you will be stuck in an infinite loop. You will never reach the if condition used to break out of the loop. First time through the loop, you will print BLARRR, increment pomCount, then you will encounter the continue statement which will cause you to ignore rest of the loop statements. You will simply go to the next iteration of the loop. You will print BLARR, increment pomCount, and again you will have the continue statement causing to you to skip to the next iteration. And so on. You will be stuck in an infinite loop.