-3

Apparently, the for loop is executed everytime which changes the value of bool to false, and always show that the given number is composite

#include <iostream>
using namespace std;

int main()
{
    int a, b;
    bool Prime=true;
    cout << "Enter the number to check for Prime Number: ";
    cin >> b;
    if (b == 0, 1)
    {
        Prime=false;
    }
    else
    {
        for (a = 2; a < b; a++)
        {
            if (b % a == 0)
            {
                Prime=false;
                break;
            }
        }
    }
    if (Prime)
    {
        cout << "The given number is a Prime Number";
    }
    else
    {
        cout << "The given number is not Prime, i.e. it is composite";
    }
    return 0;
}
  • 4
    `b == 0, 1` should produce warning, with appropriate flags. – Jarod42 Oct 11 '21 at 15:02
  • 1
    As a beginner, you should start with a [good introductory book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). – Evg Oct 11 '21 at 15:04
  • 3
    What is `if (b == 0, 1)` supposed to do? Hint: it doesn't do what you think it does. – Jabberwocky Oct 11 '21 at 15:04
  • What makes you think the `for` loop is executed every time? What happens if you add some simple print statements to the `if` and `else` branches? – Tim Randall Oct 11 '21 at 15:07

1 Answers1

2

You have a comma in this if condition:

if (b == 0, 1)
{
    Prime=false;
}

This will evaluate b == 0, but then discard the result and evaluate if(1). That's causing Prime to always be set to false, then skipping the else clause entirely. (See this answer for why it behaves that way.)

If you want to check to see if b is equal to either 0 or 1, use:

if (b == 0 || b == 1)
Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880
  • 1
    I think this answer needs `if (b == 0 || b == 1)` which is presumably the test that OP was trying to create. – Tim Randall Oct 11 '21 at 15:09
  • @TimRandall Ah, that makes more sense! I'll update my answer. – Bill the Lizard Oct 11 '21 at 15:10
  • Oh thanks! But can you please tell what this | | symbol is called and what is its function? I don't think I have learnt about it yet – Priyanshu Makwana Oct 11 '21 at 15:18
  • 1
    @PriyanshuMakwana That's called the logical OR operator. It's one operator used to combine logical (boolean) conditional statements. https://learn.microsoft.com/en-us/cpp/cpp/logical-or-operator-pipe-pipe?view=msvc-160 – Bill the Lizard Oct 11 '21 at 15:21