144k views
0 votes
This problem will be discussed in Lab6. In Lab6, the TAs will also discuss about the solution of Function Problem 1 that required you to write several functions. Additionally, the last week's lab problems on loop will be discussed too, if you need more help on them. See the deadline. You should try your best to complete it within the lab time. First n prime numbers: Write a program that takes a positive integer n as input and prints all the prime numbers from 1 to n.

User David Ford
by
5.1k points

1 Answer

4 votes

Answer:

C++.

Step-by-step explanation:

#include <iostream>

using namespace std;

////////////////////////////////////////////////////////////////

void printPrime(int n) {

if (n > 0) {

cout<<2<<endl;

for (int i=3; i<=n; i++) {

bool isPrime = true;

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

if (i % j == 0) {

isPrime = false;

break;

}

}

if (isPrime == true)

cout<<i<<endl;

}

}

else {

cout<<"Invalid input";

}

}

int main() {

int n;

cout<<"Enter positive integer: ";

cin>>n;

printPrime(n);

return 0;

}

User Lasheika
by
4.4k points