SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Walter Savitch ,julia Lobur
Chapter:
More Flow Of Control
Exercise:
Programming Projects
Question:14 | ISBN:9780321531346 | Edition: 7

Question

Write a program that finds and prints all of the prime numbers between 3 and 100. A prime number is a number such that one and itself are the only numbers that evenly divide it (e.g., 3, 5, 7, 11, 13, 17, …).

One way to solve this problem is to use a doubly nested loop. The outer loop can iterate from 3 to 100 while the inner loop checks to see if the counter value for the outer loop is prime. One way to see if number n is prime is to loop from 2 to n−1 and if any of these numbers evenly divides n, then n cannot be prime. If none of the values from 2 to n−1 evenly divide n, then n must be prime. (Note that there are several easy ways to make this algorithm more efficient.)

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

PROGRAM CODE:

#include <iostream>
using namespace std;
bool isPrime(int num) {
    if (num < 2) {
        return false; // Numbers less than 2 are not prime
    }

    // Check divisibility from 2 to sqrt(num)
    for (int i = 2; i * i <= num; i++) {
        if (num % i == 0) {
            return false; // num is divisible by i, so it's not prime
        }
    }

    return true; // num is prime
}

int main() {
    int lowerLimit = 3;
    int upperLimit = 100;

    cout << "Prime numbers between " << lowerLimit << " and " << upperLimit << " are:\n";

    for (int i = lowerLimit; i <= upperLimit; i++) {
        if (isPrime(i)) {
            cout << i << " ";
        }
    }

    cout << endl;

    return 0;
}

 

OUTPUT OF THE PROGRAM CODE:

Prime numbers between 3 and 100 are:
3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 

 

0 0

Discussions

Post the discussion to improve the above solution.