Solutions to previous assignments

These are possible solutions to a selected group of exercises found in the lab assignments prepared by Dr. Turner.

Lab 3, Exercise 6: Guess-the-Number Game

#include <iostream> #include <cstdlib> #include <ctime> using namespace std; int main() { int n, guess; srand(time(0)); n = rand() % 1000 + 1; while (cin >> guess) { if (guess < n) { cout << "too small\n"; } else if (guess > n) { cout << "too big\n"; } else { cout << "you got it\n"; return 0; } } }

Lab 3, Exercise 8: Detecting prime numbers

#include <iostream> using namespace std; bool is_prime(int x) { for (int i = 2; i != x; ++i) { if (x % i == 0) return false; } return true; } int main() { int n = 0; cout << "Enter an integer greater than 1: "; cin >> n; if (n <= 1) return 1; if (is_prime(n)) cout << "Prime\n"; else cout << "Not prime\n"; }

Lab 4, Exercise 4: Random integer function

#include <iostream> #include <cstdlib> #include <ctime> using namespace std; int randomInteger(int min, int max) { return rand() % (max - min + 1) + min; } int main() { int min = 0, max = 0; srand(time(0)); cout << "Min: "; cin >> min; cout << "Max: "; cin >> max; cout << randomInteger(min, max) << endl; }