C++ Break Statement in Loop

C++C++Beginner
Practice Now

Introduction

In this lab, we will learn how to use the break statement in loops within the C++ programming language. A break statement is used to interrupt the flow of execution within a loop, allowing the loop to terminate earlier than it normally would.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL cpp(("C++")) -.-> cpp/IOandFileHandlingGroup(["I/O and File Handling"]) cpp(("C++")) -.-> cpp/SyntaxandStyleGroup(["Syntax and Style"]) cpp(("C++")) -.-> cpp/ControlFlowGroup(["Control Flow"]) cpp/ControlFlowGroup -.-> cpp/break_continue("Break/Continue") cpp/IOandFileHandlingGroup -.-> cpp/output("Output") cpp/IOandFileHandlingGroup -.-> cpp/files("Files") cpp/SyntaxandStyleGroup -.-> cpp/code_formatting("Code Formatting") subgraph Lab Skills cpp/break_continue -.-> lab-96121{{"C++ Break Statement in Loop"}} cpp/output -.-> lab-96121{{"C++ Break Statement in Loop"}} cpp/files -.-> lab-96121{{"C++ Break Statement in Loop"}} cpp/code_formatting -.-> lab-96121{{"C++ Break Statement in Loop"}} end

Create a new directory

We will create a new directory named cpp_break in the terminal.

mkdir cpp_break

Navigate to the newly created directory.

cd cpp_break

Compile and run the program

In the terminal, compile and run the program using the following command:

g++ main.cpp -o main && ./main

The output of the program will be displayed in the terminal.

Summary

In this lab, we have learned how to use the break statement in loops within the C++ programming language. We have created a program that demonstrates the use of the break statement in a do-while loop to terminate the loop when a certain condition is met.