C++: Why/How a Break Statement Works In This Code?

359 views Asked by At

I have started to use C++ programming language as a complete beginner. With the aim of becoming a better programmer for my STEM degree and with the goal of competitive programming in mind. I have started Functions and Loops in C++ recently and there was a problem I was not sure how to approach.

The probelem: "Write a function to check whether a number is prime"

My Approach:

-> I wanted to implement it on my own so I didn't want to copy paste code online where others have used functions with return type bool.

-> Here is the final version of my code that works:

void prime(int k){
    for(int k1=2;k1<k;k++){
        if(k%k1==0){
            cout<<"int is not prime"<<endl;
            break;
        }
        else{
            cout<<"int is prime"<<endl;
            break;
        }

    }
}

->I would then call this in int Main() and get the user to input integers and so on.

-> The above code was due to many trial-and-errors on my part and my thought process was as follows: 1)if i don't include the "break;" statement my code results in an infinite loop 2)I needed a way to stop my code from going toward an infinite loop 3) I remember a topic covered in the functions segment of this website , where we can use it to terminate a loop at will. Thats why i incorporated it into my code to produce the final version

My Question:

  1. Can someone explain how the break; statement is working in the context of my code? I know it produces my desired effect but I still haven't gotten an intuition as to how this would do my work.

  2. Many online resources just cite the break statement as something that does so and so and then gives examples. Without going through the code mechanics. Like how a loop would be going through its conditions and then when it encounters the break; statement what does it do? and as a consequence of that what does it do to help my code?

Any advice would be helpful. I still couldn't wrap my head around this the first time I encountered it.

2

There are 2 answers

12
rawrex On BEST ANSWER

In your case if k % k1 does not show that the k1 being a factor of the k, the loop is broken after the print statement. If the k % k1 does show that the k1 being a factor of the k, it also breaks out of the loop.

So, either of the break statements leads to the loop termination on the first iteration here. If you test for whether a number is being a prime, it does not work.

In essence, you don't need either of the break statements here. They are mostly forced here. Take a look at the following approach:

#include <iostream>
#include <cmath>

bool prime(unsigned k){
    if (k != 2) { // Direct check, so to remain similar to the OP's structure of the code 
        unsigned up_to = sqrt(k) + 1; // Calculate the limit up to which to check
        for (unsigned i = 2; i < up_to; ++i) {
            if (k % i == 0) {
                std::cout << "Is not prime" << std::endl;
                return false;
            }
            else std::cout << "Checking..." << std::endl;
        }
    }
    std::cout << "Is prime" << std::endl;
    return true;
}
// Note, we can check just up to the square root of a k

A note on the behavior of the break

The fact that it breaks out the the closest loop to it - has crucial nature for nested loops (all of them: for, while, and do while):

while (/* condition 1 */) // Outer loop
    while (/* condition 2 */) // Inner loop
        if (/* condition 3 */) break;

Here if the condition 3 is satisfied, the break will lead to break out of the Inner loop but the Outer loop will still continue to iterate.

For more, you may be interested in "How to exit nested loops?" thread. It addresses your second question.

2
Bob Logan On

Analogy... I found it in the last place I looked... like always!

Looking for your keys is the LOOP you are in... when you find them... you BREAK out and move on to another task... like maybe getting into your car...

SO if you are IN your car and know your car is where you left your keys... then you are in the PROCESS of getting prepared to drive away... BUT that process requires keys... THUS you change modes/focus and begin a cyclic process of looking for keys... when found to BREAK that searching process IMMEDIATLY and resume what your were doing.

MANY people would make use of the RETURN instrucion in your code pattern... in place of the break! Both do the same thing... however the RETURN is more descriptive english... and one should be concerned with the programmer behind him... Also a bit of digging might show how one is more efficient than the other...