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:
bool prime (vector<int> table, int number)
and
if (prime(table,next))
Thanks, Sean
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
.
main
is the definition of a prime
function. It is defined (created) there for you to call later, in the main
function.prime
, the second is the call to that function.