I am trying to create a program that will prompt a user for an input. From that input I am supposed to print all the prime numbers that are less than and equal to that value. I am really struggling to do this.
I know I need to loop through from 2 to the number. understand what I am missing. This is the code i have so far (all inside main) and when the input is 5 the output is 1 1 which is wrong. What I want to happen (example): if the input is 13 then the output should be 2 3 5 7 11 13.
int i = 0; int getNumber = 0; cin >> getNumber; for (i = 2; i <= getNumber; i++){ if (getNumber % i == 0){ prime = false; }else{ prime = true; } if (prime == true){ cout << i << " " << endl;} }
jbefore it has been initialized.isPrime(int number), how would you use that in a loop? What would that loop iterate over?prime, which you have noted in the comments is a boolean. Your problem description says you should be printing anint.getNumberequals 57 and in the third iteration of the loopiis 4. Thenidoes not divide 57. As a result you go to theprime = truebranch, even though 4 is certainly not prime.