Sign In Start Free Trial
Account

Add to playlist

Create a Playlist

Modal Close icon
You need to login to use this feature.
  • Book Overview & Buying The C++ Workshop
  • Table Of Contents Toc
The C++ Workshop

The C++ Workshop

By : Dale Green , Kurt Guntheroth , Shaun Ross Mitchell
5 (8)
close
close
The C++ Workshop

The C++ Workshop

5 (8)
By: Dale Green , Kurt Guntheroth , Shaun Ross Mitchell

Overview of this book

C++ is the backbone of many games, GUI-based applications, and operating systems. Learning C++ effectively is more than a matter of simply reading through theory, as the real challenge is understanding the fundamentals in depth and being able to use them in the real world. If you're looking to learn C++ programming efficiently, this Workshop is a comprehensive guide that covers all the core features of C++ and how to apply them. It will help you take the next big step toward writing efficient, reliable C++ programs. The C++ Workshop begins by explaining the basic structure of a C++ application, showing you how to write and run your first program to understand data types, operators, variables and the flow of control structures. You'll also see how to make smarter decisions when it comes to using storage space by declaring dynamic variables during program runtime. Moving ahead, you'll use object-oriented programming (OOP) techniques such as inheritance, polymorphism, and class hierarchies to make your code structure organized and efficient. Finally, you'll use the C++ standard library?s built-in functions and templates to speed up different programming tasks. By the end of this C++ book, you will have the knowledge and skills to confidently tackle your own ambitious projects and advance your career as a C++ developer.
Table of Contents (15 chapters)
close
close

break/continue

Having the ability to loop sections of code is very important, but it has to be used carefully. We've seen that it's possible to create loops that never end, and another concern is ensuring that they're used efficiently. So far, the loops we've looked at have been small, and we've been happy to see them run through in their entirety. But what if we needed more control over our loops, perhaps to end one early? Thankfully, we have two important keywords to help us with that—break and continue.

break

break is a C++ keyword that will exit the current loop, with execution jumping to the next section of code if there is any. This keyword works with the different types of loop that we've covered so far, and we can demonstrate it nicely using a simple counting application, as shown in the following snippet:

// Break example.
#include <iostream>
#include <string>
int main()
{
    std::cout << "Loop Starting ...\n";
    int count = 0;
    while (count < 5)
    {
        ++count;
        std::cout << "\n" << count;
    }
    std::cout << "\n\nLoop finished.";
}

In this example, we're going to print out 5 numbers, 0-4. If we run this code as is, we can see that the loop runs in its entirety and gives us our expected outcome. We've also got statements at the start and end of the loop so we can see the flow execution more clearly:

Figure 2.12: Example counting application will print out numbers 0-4

Figure 2.12: Example counting application will print out numbers 0-4

Now, what if there was a condition that meant we wanted this loop to stop executing when the count was equal to 2? Well, we can put a break statement inside that check using an if statement:

#include <iostream>
using namespace std;
int main()
{
    std::cout << "Loop Starting ...\n";
    int count = 1; // init
    while (count <= 5) // condition
    {
        std::cout << "\n" << count;
        if (count == 2)
        break;
        ++count; // increment
    }
    std::cout << "\n\nLoop finished.";
   
    return 0;
}

With that break condition in place, as soon as the count is equal to 2 (meaning we'll have had 2 iterations of the loop) then the break will be hit and we'll exit the loop. Now, let's run the application and see what we get:

Figure 2.13: With the break statement in place, we only execute 2 loop iterations

Figure 2.13: With the break statement in place, we only execute 2 loop iterations

We can now see, as soon as that condition is met and the break statement is hit, that the loop stops iterating, and code execution picks up immediately after the loop. The outcome of this will be exactly the same if we write it as a dowhile:

#include <iostream>
using namespace std;
int main()
{
    std::cout << "Loop Starting ...\n";
    int count = 1; // init
    do
    {
        std::cout << "\n" << count;
        if (count == 2)
        break;
        ++count; // increment
        }
        while (count <= 5); // condition
        
        std::cout << "\n\nLoop finished.";
        return 0;
}

And it will be the same if we write it as a for loop:

#include <iostream>
using namespace std;
int main()
{   
    std::cout << "Loop Starting ...\n";
    // init condition increment
    for (int count = 1; count <= 5; ++count)
    {
        std::cout << "\n" << count;
        if (count == 2)
        break;
    }
   
    std::cout << "\n\nLoop finished.";
    return 0;
}

Both these loops give the exact same behavior; two iterations before hitting the break statement and exiting the loop:

Figure 2.14: All loops give the same outcome: two iterations before exiting

Figure 2.14: All loops give the same outcome: two iterations before exiting

This shows that these loops are sometimes interchangeable, though some are more suited to certain use cases than others. For instance, with the counting example we're using here, a for loop is probably most suitable since it comes with an integer value that increments each loop—something we have to do manually with while and do while loops. When an incrementing integer is not required, however, a range-based for loop is recommended.

continue

The other keyword we have at our disposal is continue. This keyword allows us to skip over the current loop iteration but remain in the loop, in contrast with break. Again, the counting example will allow us to demonstrate this. In our example, we're printing the numbers 0-4; let's use the continue keyword to skip the printing of the number 3.

As we did with break, we can write a condition to check whether the count is equal to 3, and call count if so:

    if (count == 3)
    {
        continue;
    }

We also need to change the location of this within our function. The continue keyword will skip the rest of the loop's body. Currently, this code is at the end of that body, so we won't actually be skipping anything. In order for continue to work as expected, it needs to come before any code that we want to skip but after any code we want to execute.

For this example, we will place the continue keyword with the if statement:

// continue example.
#include <iostream>
#include <string>
int main() 
{
    std::cout << "Loop Starting ...\n";
    int count = 0;
    while (count < 5) 
    {
        ++count;
        if (count == 3) 
        {
            continue;
        }
        std::cout << "\n" << count;
    }
    std::cout << "\n\nLoop finished.";
}

Here, we're always going to increment our counter variable and then check whether we want to skip the current iteration. If we do skip it, we'll just go back to the start of the next loop, and if we don't, we'll execute the remainder of the loop as usual. Once you run this code, you will obtain the following output:

Figure 2.15: The printing of number 3 has been skipped

Figure 2.15: The printing of number 3 has been skipped

We've skipped the printing of number 3 as we wanted, but the loop continued to execute the rest of the way. This can be extremely useful when searching for something. Imagine we have a list of names, and we only want to do things with those that start with the letter D. We could iterate over all our names, first checking whether or not the first letter is D; if not, we continue. In this way, we efficiently skip the use cases that don't interest us.

Exercise 12: Making a Loop More Efficient Using break and continue

In this exercise, we're going to make use of break and continue to make a loop more efficient. We'll create a loop that will run over the numbers 1-100, printing out only specific multiples of a given value.

Note

The complete code for this can be found here: https://packt.live/2KJrnN8.

Follow these steps to complete the exercise:

  1. We'll first ask the user to choose the value whose multiples will be printed, as well as the maximum number of multiples to print:
    #include <iostream>
    #include <string>
    int main()
    {
        int multiple = 0;
        int count = 0;
        int numbersPrinted = 0;
        std::string input = "";
        std::cout << "Enter the value whose multiples will be printed: ";
        getline(std::cin, input);
        multiple = std::stoi(input);
        std::cout << "Enter maximum amount of numbers to print: ";
        getline(std::cin, input);
        count = std::stoi(input);
  2. Next, we'll create the for loop to iterate over the numbers 1-100:
        for (int i = 1; i <= 100; ++i)
        {
        }
  3. Now, within the for loop, we can write the logic for determining our multiples. First of all, we have a set amount of numbers that we're going to print, so we can check that and break if that number has been reached:
            if (numbersPrinted == count)
            {
                break;
            }
  4. We're only interested in numbers of our given multiple, so if that's not the case, we can use the continue statement to jump straight to the next iteration:
            if (i % multiple != 0)
            {
                continue;
            }
  5. If the loop iteration makes it past both of these statements, then we've found a valid number. In this case, we'll print it, and then increment our numbersPrinted variable using the following snippet:
                std::cout << i << "\n";
                ++numbersPrinted;
            }
  6. The complete code looks like this:
    #include <iostream>
    #include <string>
    int main()
    {
        int multiple = 0;
        int count = 0;
        int numbersPrinted = 0;
        std::string input = "";
        
        std::cout << "Enter the value whose multiples will be printed: ";
        getline(std::cin, input);
        multiple = std::stoi(input);
        
        std::cout << "Enter maximum amount of numbers to print: ";
        getline(std::cin, input);
        count = std::stoi(input);
        for (int i = 1; i <= 100; ++i)
        {
              if (numbersPrinted == count)
              {
                  break;
              }
              if (i % multiple != 0)
              {
                  continue;
              }
              std::cout << i << "\n";
              ++numbersPrinted;
        }
    }
  7. Run the application. You will obtain the following output:
Figure 2.16: We use break and continue to control loop execution

Figure 2.16: We use break and continue to control loop execution

By using the break and continue statements, we're able to control the execution of our loops, making them more efficient and controlled.

Activity 2: Creating a Number-Guessing Game Using Loops and Conditional Statements

For this chapter's activity, we're going to write a small number-guessing game. This will allow us to utilize the techniques that we've covered in this chapter. Thus, before attempting this activity, ensure that you have completed all the previous exercises in this chapter.

The program will allow the user to select a number of guesses: a minimum number and a maximum number. The application will generate a number within that range and then allow the user to guess the number. If they do so within the number of guesses they specified at the start, they win the game. Upon winning a game, the final output should be similar to the following:

Figure 2.17: Number-guessing game output

Figure 2.17: Number-guessing game output

Note

The complete code for this activity can be found here: https://packt.live/2pBYnPT.

Here are the steps to complete the activity, along with a few hints:

  1. Declare all the variables we'll need. This includes guessCount, minNumber, maxNumber, and randomNumber.
  2. Create a main outer loop that will run the application.
  3. Present the user with some introductory text ("Enter the number of guesses") and get from them the following: a number of guesses, a minimum number, and a maximum number.

    Note

    You can pass the user input for the number of guesses, the minimum number, and the maximum number, to the variables.

  4. Generate a random number within the range specified by the user.

    Note

    In Exercise 11, Generating Random Numbers Using Loops, we've used rand() for generating random numbers between 0 to 9. Here, you can use a function similar to rand () % (maxNumber - minNumber + 1) to generate random numbers between two arbitrary limits.

  5. Create a loop that will iterate the number of times that the user specified as their guess count.
  6. Inside the count loop, fetch the user's guess.
  7. Inside the count loop, check whether the user's guess is correct or too high/low. We can use break here to exit when the correct value has been guessed.

    Hint: Refer to Exercise 7, Refactor an if/else Chain into switch/case, to see how we used break to exit loops early.

  8. When the number has been found, or the user has run out of guesses, present them with the option to either continue or exit the application.

    Note

    The solution for this activity can be found via this link.

Within this application, we've used a number of techniques to control the flow of code to replicate a more complex scenario. We used a while loop for the main application loop, as we didn't know initially how many iterations were required. We then used a for loop to run the code a set number of times, and if/else statements to check the user's input and act accordingly.

CONTINUE READING
83
Tech Concepts
36
Programming languages
73
Tech Tools
Icon Unlimited access to the largest independent learning library in tech of over 8,000 expert-authored tech books and videos.
Icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Icon 50+ new titles added per month and exclusive early access to books as they are being written.
The C++ Workshop
notes
bookmark Notes and Bookmarks search Search in title playlist Add to playlist download Download options font-size Font size

Change the font size

margin-width Margin width

Change margin width

day-mode Day/Sepia/Night Modes

Change background colour

Close icon Search
Country selected

Close icon Your notes and bookmarks

Confirmation

Modal Close icon
claim successful

Buy this book with your credits?

Modal Close icon
Are you sure you want to buy this book with one of your credits?
Close
YES, BUY

Submit Your Feedback

Modal Close icon
Modal Close icon
Modal Close icon