c++functionbreakprimality-test

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


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.


Solution

  • 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.