-1

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;} } 
6
  • 1
    Your code appears to use j before it has been initialized. Commented Sep 10, 2021 at 20:19
  • Could you explain, in pseudo code, what you intended your prime validation algorithm to be? Consider if you designed your code to use a function isPrime(int number), how would you use that in a loop? What would that loop iterate over? Commented Sep 10, 2021 at 20:21
  • Your code also appears to print the variable prime, which you have noted in the comments is a boolean. Your problem description says you should be printing an int. Commented Sep 10, 2021 at 20:22
  • 1
    Related: https://stackoverflow.com/questions/4424374/determining-if-a-number-is-prime Commented Sep 10, 2021 at 20:32
  • Are you sure you are checking primality? Suppose getNumber equals 57 and in the third iteration of the loop i is 4. Then i does not divide 57. As a result you go to the prime = true branch, even though 4 is certainly not prime. Commented Sep 10, 2021 at 20:33

2 Answers 2

0

Whenever you enter the else branch you set prime to true and then send it to cout. The boolean value true is output as integer 1. For input number 5 you enter the path twice, hence the result of 1 1.

Sign up to request clarification or add additional context in comments.

Comments

0

With this code, you will get all numbers printed less than the input number. You may consider creating a function to check if the "i" is prime & below "n".

Although, effective way is creating two functions- one for checking prime and other for printing the number below entered number. In short you will need 2 for loops.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.