- #include <iostream>
- #include <vector>
- using namespace std;
- // recursively display and remove the first integers of a vector
- void recursive(vector<int> &arr) {
- //note: the pointer *arr.begin() == arr[0]
- //base case with a vector of 1 int
- if (arr.size() == 1) {
- cout << *arr.begin() << endl;
- //vector of 2 or more int
- } else {
- cout << *arr.begin() << endl;
- //remove first element and recurse
- arr.erase(arr.begin());
- recursive(arr);
- }
- }
- int main() {
- //While guessing game
- srand(time(nullptr));
- const int randomNumber = rand() % 10 + 1;
- int guess = 0;
- int guesses = 0;
- cout << "Guess a number between 1 and 10: " << endl;
- while (guess != randomNumber && guesses < 4) {
- cout << "You have " << 4 - guesses << " guesses left!" << endl;
- cin >> guess;
- guesses++;
- if (guess < randomNumber) {
- cout << "Too low!" << endl;
- } else if (guess > randomNumber) {
- cout << "Too high!" << endl;
- } else {
- cout << "Congratulations! You guessed the number." << endl;
- }
- }
- //wait for input
- system("pause");
- //Do-While-Free-Trial
- char card = '-';
- do {
- if (card == '-') {
- cout << "Thank you for activating your free Netflix trial." << endl;
- }
- cout << "One month of Netflix service used." << endl;
- cout << "Want to pay for another month? y or n" << endl;
- cin >> card;
- } while (card == 'y');
- cout << "No more Netflix for you!" << endl << endl;
- //windows-specific pause
- system("pause");
- cout << "Here's a demonstration of the same counting loop using 7 different loop styles:" << endl;
- system("pause");
- cout << "While loop with manual iteration" << endl;
- //WHILE loop
- int i = 0;
- while (i < 5) {
- cout << i << endl;
- i++;
- }
- system("pause");
- //DO-WHILE loop
- cout << endl << "Using Do-While Loop and manual iteration" << endl;
- int j = 0;
- do {
- cout << j << endl;
- j++;
- } while (j < 5);
- system("pause");
- //FOR loop
- cout << endl << "Using For Loop" << endl;
- for (int k = 0; k < 5; k++) {
- cout << k << endl;
- }
- //for use in recursion and for-each loop
- vector<int> numbers = {0, 1, 2, 3, 4};
- system("pause");
- //FOREACH loop
- cout << endl << "Using For-Each Loop and a vector" << endl;
- //int numbers[] = {0, 1, 2, 3, 4};
- for (const int number: numbers) {
- cout << number << endl;
- }
- system("pause");
- //RECURSIVE function call
- cout << endl << "Using Recursion through a vector" << endl;
- recursive(numbers);
- system("pause");
- //GOTO loop in Do-While style
- cout << endl << "Using post-test Goto Loop with manual iteration" << endl;
- int l = 0;
- doloop:
- cout << l << endl;
- l++;
- if (l < 5) {
- goto doloop;
- }
- system("pause");
- //GOTO loop in While style
- cout << endl << "Using post-test Goto Loop with manual iteration" << endl;
- int m = 0;
- whileloop:
- if (m < 5) {
- cout << m << endl;
- m++;
- goto whileloop;
- }
- system("pause");
- }