Search code examples
c++principles

C++ Priciples and Practice Exercise - Finding primes from input value n


Found this answer to Ch4Ex15 of Stroustrups beginner book, the question is to find the first n amount of primes:

#include "std_lib_facilities.h"

bool prime (vector<int> table, int number) {
    for (int i = 0; i < table.size(); ++i)
        if (number%table[i] == 0) return false;
    return true;
}

int main () {
    int count, next;
    cout << "Input the number of primes\n";
    cin >> count;
    vector<int> table;
    next = 2;
    while (table.size() < count) {
        if (prime(table,next)) table.push_back(next);
        ++next;
    }
    for (int n = 0; n < table.size(); ++n)
        cout << table[n] << " ";
    cout << endl;

    // keep_window_open();
    return 0;
}

Two things I'm struggling to understand:

  1. Why is there a section of code outside int main at the top, is the executed after int main?
  2. How do these statements work (are they double conditions?) bool prime (vector<int> table, int number) and if (prime(table,next))

Thanks, Sean


Solution

  • The things you are asking are quite fundamental to the language of C and C++. A read through the first 2-3 chapters of any good C++ textbook would answer these questions for you.

    The example code defines 2 functions: prime and main.

    1. The code outside main is the definition of a prime function. It is defined (created) there for you to call later, in the main function.
    2. These are two separate things. The first thing you mention is the definition of the function prime, the second is the call to that function.