Hi, I've been reading C++ without fear (2nd edition) and at the beginning it's proved quite resourceful and helpful. However at later exercises it started to be a little careless. About 90 pages through everything got so hard so quick with no helps, hint or answers or anything. I mean look at these questions..
Exercise 4.2.1. Optimize the prime-number function by calculating the square root
of n only once during each function call. Declare a local variable sqrt_of_n of
type double. (Hint: A variable is local if it is declared inside the function.) Then
use this variable in the loop condition.
Exercise 4.2.2. Rewrite main so that it tests all the numbers from 2 to 20 and prints
out the results, each on a separate line. (Hint: Use a for loop, with i running from
2 to 20.)
How the hell am I supposed to know that? How exactly do I rewrite main? It doesn't even explain. Anyway here is the source
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
|
#include <iostream>
#include <cmath>
using namespace std;// Function must be declared before being used.
bool prime(int n);
int main() {
int i;
// Set up an infinite loop; break if user enters 0.
// Otherwise, evaluate n from prime-ness.
while (true) {
cout << "Enter num (0 = exit) and press ENTER: ";
cin >> i;
if (i == 0) // If user entered 0, EXIT
break;
if (prime(i)) // Call prime(i)
cout << i << " is prime" << endl;
else
cout << i << " is not prime" << endl;
}
system("PAUSE");
return 0;
}
// Prime-number function. Test divisors from
// 2 to sqrt of n. Return false if a divisor
// found; otherwise, return true.
bool prime(int n) {
int i;
for (i = 2; i <= sqrt(n); i++) {
if (n % i == 0) // If i divides n evenly,
return false; // n is not prime.
}
return true; // If no divisor found, n is prime.
}
|
ALSO can anyone reccomend me good updated C++ books? Preferably from experience and that's very well written and popular/good.