Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a program that reads in an integer N and prints out all the prime numbers

ID: 3881316 • Letter: W

Question

Write a program that reads in an integer N and prints out all the prime numbers strictly less than N. These should be printed one per line.

Sample Input 10:

Sample OutPut: 2,3,5,11

This is what I have, but I dont know why it's incorrect when I try to submit it? Someone help?

int main()

{

int N, i;

cin >> N;

for (int i = 2; N >= i; ++i)

{

bool isPrime = true;

for (int j = 2; j < i; ++j)

{

if (i % j == 0) //If the answer is 0 the statement is false and will be blank

{

isPrime = false;

break;

}

}

if (isPrime)

{

-+N;

cout << i << endl;

}

}

return 0;
}

Explanation / Answer

There were a slight number of unwanted codes and execution in your program. I have corrected them now.

#include<iostream>

using namespace std;

int main()

{

int N, i;

cout<<"Input N: ";

cin >> N;

for (int i = 2; N >= i; ++i)

{

bool isPrime = true;

for (int j = 2; j < ((i/2) + 1); ++j) // run the inner loop to i / 2 because

// any factor should have to be atleast 2 times of main number

{

if (i % j == 0) //If the answer is 0 the statement is false and will be blank

{

isPrime = false;

break;

}

}

if (isPrime)

{

// why -+N ??

cout << i << endl;

}

}

return 0;

}

Modified C++ Code

#include<iostream>

using namespace std;

int main()

{

int N, i;

cout<<"Input N: ";

cin >> N;

for (int i = 2; N >= i; ++i)

{

bool isPrime = true;

for (int j = 2; j < ((i/2) + 1); ++j) // run the inner loop to i / 2 because

// any factor should have to be atleast 2 times of main number

{

if (i % j == 0) //If the answer is 0 the statement is false and will be blank

{

isPrime = false;

break;

}

}

if (isPrime)

{

// why -+N ??

cout << i << endl;

}

}

return 0;

}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote