Home > Blockchain >  my yes\no loop is not working the way it should
my yes\no loop is not working the way it should

Time:03-24

I am required to make a program that checks if a number is prime or not. After checking if the number is prime or not the program should ask the user whether they want to check again or not. I am struggling to be able to enter a number after picking the check again option.

here is my code:

#include <iostream>

using namespace std;

int main()
{
    int n, i, m=0, flag=0;
    char choice;

  cout << "Enter the Number to check: ";
  cin >> n;
  m=n/2;
  for(i = 2; i <= m; i  )
  {
      if(n % i == 0)
      {
          cout<<"Number is not Prime."<<endl;
          flag=1;
          break;
      }
  }
  if (flag==0)
      cout << "Number is Prime."<<endl;

  cout << "Execute check again (yes/no): ";
  cin >> choice;
  while (choice == 'yes')
   {
    cout << "Enter the Number to check: ";
    cin >> n;
  m=n/2;
  for(i = 2; i <= m; i  )
  {
      if(n % i == 0)
      {
          cout<<"Number is not Prime."<<endl;
          flag=1;
          break;
      }
  }
  if (flag==0)
      cout << "Number is Prime."<<endl;
   }
    while (choice == 'no')
  {
   return 0;
  }

}

CodePudding user response:

You can use the do while statement for this case, for example:

#include <iostream>

using namespace std;

int main()
{
  do{
    int n, i, m=0, flag=0;
    char choice;

    cout << "Enter the Number to check: ";
    cin >> n;
    m=n/2;
    for(i = 2; i <= m; i  )
    {
        if(n % i == 0)
        {
            cout<<"Number is not Prime."<<endl;
            flag=1;
            break;
        }
    }
  if (flag==0)
    cout << "Number is Prime."<<endl;

  cout << "Execute check again (yes/no): ";
  cin >> choice;
} while (choice == 'yes');

}

CodePudding user response:

This statement

cin >> choice;

reads only one character from the input stream because the variable choice is declared as having the type char

char choice;

But you are trying to compare it with the integer multibyte literal containing two or even three characters

while (choice == 'yes')

//...

while (choice == 'no')

In any case this while loop

    while (choice == 'no')
  {
   return 0;
  }

does not make a sense.

It seems what you need is a do while loop like

#include <string>

//...

std::string choice;

do
{
    int flag = 0;

    cout << "Enter the Number to check: ";

    //...

    std::cout << "Execute check again (yes/no): ";
    std::cin >> choice;
} while ( choice == "yes" );

Pay attention to that your approach incorrectly considers 0 and 1 and any negative number as prime numbers.

  • Related