//Testing numbers for primality
#include <iostream>
#include <cmath>
using namespace std;
int main() {
int n; //User input number
int i; //Input number will be divided by i
int count;
count = 0;
cout << endl;
while(n != 'q') {
cout << "#: ";
cin >> n;
for(i = 1; i <= n; i++) {
//increase the divisor until it's equal to n
if(n % i == 0) {
count++;
}
//If there is no remainder, count increases by 1. Since prime numbers are only divisible by 1 and themselves, count will be exactly 2 in the case of a prime number.
}
if(count == 2) {
cout << " 1\n"; //1 = yes prime
}else if(count != 2) {
cout << " 0\n"; //0 = not prime
}
count = 0;
}
if(n == 'q') {
return(0);
}
}
Here I am testing numbers to see if they are prime. Count increases every time the remainder of division n/i is 0 so when count=2, output is 1 for yes, otherwise 0 for no. I’ve gotten the program to test as many numbers as I want correctly during a session, but I am trying to create an escape sequence.
I tried using the condition (n==’q’) for quit, but when I input q, the program loops infinitely. I tried putting a break; statement for this condition within the while loop but the result is the same. I am guessing this problem has to do with char-int/int-char conversion. Can someone hint to me how I can create a working exit sequence?
You have no code that can read a
q. Your input logic only accepts a number. You then test if that number is equivalent to aqcharacter. The equivalent integer to the letterqis 113. If you try that, it will quit.Since you really want to input a number or a letter, you’ll need to write input logic that can accept either. Then you’ll need to check what input you got, and then process it accordingly.