├── .gitignore ├── ArrayFun ├── ArrayFun.cpp ├── ArrayFunctionFun.cpp ├── ArrayLoopingFun.cpp ├── ParallelArrayFun.cpp └── TwoDArrayFun.cpp ├── ConditionalsFun ├── BooleanFun.cpp ├── ConditionalFun.cpp ├── GuessMyNumberFun.cpp ├── GuessMyNumberFun2.cpp ├── GuessMyNumberFun3.cpp └── SwitchFun.cpp ├── CppBasicsFun ├── ArithmeticFun.cpp ├── BasicsFun.cpp ├── ConeVolumeFun.cpp ├── ErrorFun.cpp ├── HelloWorld.cpp └── InputOutputFun.cpp ├── FileIOReviewFun ├── Main.cpp ├── chars.txt └── sentence.txt ├── FilesFun ├── AdvancedFileIOFun │ ├── AdvancedFileIOFun.cpp │ └── students.txt ├── FileIOFun │ ├── FileIOFun.cpp │ └── transactions.txt └── FileIOFun2 │ ├── FileIOFun2.cpp │ ├── avg_transaction.txt │ └── transactions.txt ├── FunctionFun ├── AdvancedPrototypeFun.cpp ├── DoubleInclusionDemo │ ├── Header.h │ ├── Main.cpp │ └── TopLevelHeader.h ├── FunctionFun.cpp ├── GPAFunctionFun.cpp ├── GPAFunctionFun2.cpp ├── PrototypeFun.cpp ├── ReferenceFun │ ├── ReferenceFun.cpp │ └── roll_results.txt ├── ScopeFun.cpp └── ThreeFileFormatFun │ ├── DiceFunctions.cpp │ ├── DiceFunctions.h │ ├── Main.cpp │ └── roll_results.txt ├── InheritanceFun ├── Animal.cpp ├── Animal.h ├── Main.cpp ├── Pet.cpp ├── Pet.h ├── WildAnimal.cpp ├── WildAnimal.h └── a.out ├── LinkedListFun ├── LinkedList.cpp ├── LinkedList.h ├── Main.cpp └── a.out ├── LoopsFun ├── AdvancedLoopFun.cpp ├── AssignmentOperatorFun.cpp ├── DoWhileLoopFun.cpp ├── ForLoopFun.cpp ├── GuessMyNumberFun4.cpp ├── GuessMyNumberFun5.cpp ├── GuessMyNumberFun6.cpp ├── RandomNumberFun.cpp ├── TransactionFun.cpp ├── TransactionFun2.cpp ├── WhileLoopFun.cpp └── WhileLoopFun2.cpp ├── MoreFileIOFun ├── Main.cpp ├── a.out └── words.txt ├── OOPFun ├── Book.cpp ├── Book.h ├── Main.cpp └── a.out ├── PointerFun ├── CStringMain.cpp ├── CommandLineArgsMain.cpp ├── DebuggingFun.cpp ├── DynamicMemoryMain.cpp ├── Main.cpp └── PointerArithmeticMain.cpp ├── QueueFun ├── LinkedList.cpp ├── LinkedList.h ├── Main.cpp ├── PriorityQueue.cpp ├── PriorityQueue.h ├── Queue.cpp ├── Queue.h └── a.out ├── RecursionFun ├── LinkedList.cpp ├── LinkedList.h ├── Main.cpp ├── Recursion.cpp ├── Recursion.h └── a.out ├── SearchingSortingFun ├── Main.cpp └── a.out ├── StackFun ├── LinkedList.cpp ├── LinkedList.h ├── Main.cpp ├── Stack.cpp ├── Stack.h └── a.out ├── StringFun ├── BinaryFun.cpp ├── StringFun.cpp ├── StringFun2.cpp ├── StringStreamFun.cpp └── TokenizingFun │ ├── StringTokenizingFun.cpp │ └── student_info.csv ├── StructsFun ├── Main.cpp ├── Makefile ├── Structs.cpp └── Structs.h ├── TemplatedLinkedListFun ├── LinkedList.h └── Main.cpp └── VectorFun ├── SortingFun.cpp ├── VectorFun.cpp └── VectorFun2.cpp /.gitignore: -------------------------------------------------------------------------------- 1 | # GS added 2 | .DS_Store 3 | 4 | # Prerequisites 5 | *.d 6 | 7 | # Compiled Object files 8 | *.slo 9 | *.lo 10 | *.o 11 | *.obj 12 | 13 | # Precompiled Headers 14 | *.gch 15 | *.pch 16 | 17 | # Compiled Dynamic libraries 18 | *.so 19 | *.dylib 20 | *.dll 21 | 22 | # Fortran module files 23 | *.mod 24 | *.smod 25 | 26 | # Compiled Static libraries 27 | *.lai 28 | *.la 29 | *.a 30 | *.lib 31 | 32 | # Executables 33 | *.exe 34 | *.out 35 | *.app 36 | -------------------------------------------------------------------------------- /ArrayFun/ArrayFun.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | int main() { 7 | int x = 0; 8 | int numbers[10]; // 10 uninitialized integers in the array called numbers 9 | 10 | string words[] = {"hello", "hi", "bye"}; // 3 initialized strings in the array called words 11 | 12 | // 0 1 2 13 | string words2[20] = {"hello", "hi", "bye"}; // 20 total strings in the array called words2 (3 are initialized, the rest are empty) 14 | int words2Size = 3; 15 | const int WORDS2_TOTAL_SIZE = 20; 16 | 17 | double myDoubles[] = {1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0}; 18 | double temp = 0.0; 19 | const int myDoublesSize = 10; 20 | 21 | cout << words[0] << endl; 22 | cout << words2[5] << endl; 23 | // task: print out the "bye" of words2 24 | cout << words2[2] << endl; 25 | 26 | // change "hello" of words to be "HELLO" 27 | words[0] = "HELLO"; 28 | cout << words[0] << endl; 29 | 30 | words[x + 1] = "HI"; 31 | cout << words[x + 1] << endl; 32 | cout << words[++x] << endl; 33 | 34 | numbers[x] = 5; 35 | cout << numbers[x] << endl; 36 | numbers[x++] += 100; 37 | cout << numbers[x - 1] << endl; 38 | cout << numbers[x] << endl; 39 | 40 | cout << myDoubles[0] << " " << myDoubles[9] << endl; 41 | // do the swap 42 | temp = myDoubles[0]; 43 | myDoubles[0] = myDoubles[9]; 44 | myDoubles[9] = temp; 45 | cout << myDoubles[0] << " " << myDoubles[9] << endl; 46 | 47 | //sizeof() operator tells the you the total number of bytes allocated for a variable 48 | cout << sizeof(myDoublesSize) << endl; 49 | cout << sizeof(double) << endl; 50 | cout << sizeof(myDoubles) << endl; 51 | cout << (sizeof(myDoubles) / sizeof(double)) << endl; 52 | 53 | 54 | return 0; 55 | } 56 | -------------------------------------------------------------------------------- /ArrayFun/ArrayFunctionFun.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | const int SIZE = 7; 6 | 7 | void displayArray(const int[], int); 8 | void multiplyByTwo(int[], int); 9 | 10 | int main() { 11 | int numbers[] = {3, 6, 4, 8, -1, 3, -2}; 12 | 13 | // call a function that prints the array 14 | displayArray(numbers, SIZE); 15 | // call a function that modifies the array 16 | multiplyByTwo(numbers, SIZE); 17 | // call a function that prints the array 18 | displayArray(numbers, SIZE); 19 | 20 | return 0; 21 | } 22 | 23 | void multiplyByTwo(int arr[], int size) { 24 | // arr is a reference to the numbers array in main 25 | int i = 0; 26 | 27 | for (i = 0; i < size; i++) { 28 | arr[i] *= 2; 29 | } 30 | } 31 | 32 | void displayArray(const int arr[], int size) { 33 | // arr is a reference to the numbers array in main 34 | int i = 0; 35 | 36 | for (i = 0; i < size; i++) { 37 | cout << arr[i] << " "; 38 | } 39 | cout << endl; 40 | } 41 | -------------------------------------------------------------------------------- /ArrayFun/ArrayLoopingFun.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | const int NUMBERS_SIZE = 5; 7 | 8 | int main() { 9 | // task: declare an array of 5 integers, just set each integer to any number 10 | int numbers[NUMBERS_SIZE] = {4, 2, 7, 5, -2}; 11 | int i = 0; 12 | int min = 0, max = 0, total = 0; 13 | int target = 5; 14 | double avg = 0.0; 15 | bool found = false; 16 | 17 | // prints the memory address of the first element in the array 18 | cout << numbers << endl; 19 | 20 | // how do we see each element though!??!?! 21 | // print each element out one at a time 22 | // USE A LOOP! 23 | for (i = 0; i < NUMBERS_SIZE; i++) { 24 | cout << "numbers[" << i << "]: " << numbers[i] << endl; 25 | } 26 | // task: re-solve the for loop using a while loop 27 | i = 0; 28 | while (i < NUMBERS_SIZE) { 29 | cout << "numbers[" << i << "]: " << numbers[i] << endl; 30 | i++; 31 | } 32 | // for each loop (AKA range based for loop) 33 | // for iterating over items in a collection 34 | // for each integer num in numbers 35 | // : represents in 36 | for (int num : numbers) { 37 | cout << num << endl; 38 | } 39 | cout << "Adding one..." << endl; 40 | for (int num : numbers) { 41 | cout << num << endl; 42 | num += 1; // doesn't change the actual value in the array 43 | // num is a copy, not a reference variable 44 | } 45 | for (int& num : numbers) { 46 | cout << num << endl; 47 | num += 1; 48 | } 49 | cout << "After adding one..." << endl; 50 | for (int num : numbers) { 51 | cout << num << endl; 52 | } 53 | 54 | // compute the average, min, and max for the values in numbers 55 | // task: try this out! 56 | // min and max are the first element in the array 57 | // until proven otherwise by comparing the rest of the elements 58 | min = max = numbers[0]; 59 | for (i = 0; i < NUMBERS_SIZE; i++) { 60 | total += numbers[i]; 61 | if (numbers[i] < min) { 62 | // we have a new min 63 | min = numbers[i]; 64 | } 65 | if (numbers[i] > max) { 66 | // we have a new max 67 | max = numbers[i]; 68 | } 69 | } 70 | avg = static_cast(total) / NUMBERS_SIZE; 71 | cout << "Avg: " << avg << endl; 72 | cout << "Min: " << min << endl; 73 | cout << "Max: " << max << endl; 74 | 75 | // given a target value, find out where the target value is in the array, if it is in there at all 76 | // search problem: find a target value 77 | target = 11; 78 | for (i = 0; i < NUMBERS_SIZE; i++) { 79 | // is numbers[i] the target? 80 | if (numbers[i] == target) { 81 | cout << "Found it at " << i << "!" << endl; 82 | found = true; 83 | break; 84 | } 85 | } 86 | // task: give feedback to the user if the number is not in the array 87 | if (!found) 88 | cout << target << " is not in the array." << endl; 89 | 90 | return 0; 91 | } 92 | -------------------------------------------------------------------------------- /ArrayFun/ParallelArrayFun.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | const int NUM_STUDENTS = 100; // larger than we need, but leaves room to grow our file 8 | 9 | void printStudentInfo(string[], string[], double[], int); 10 | 11 | int main() { 12 | // task: read each line from the file as a string and display it to the console 13 | string name = "", classStanding = "", tempString = ""; 14 | double gpa = 0.0; 15 | string studentNames[NUM_STUDENTS]; 16 | string studentClassStandings[NUM_STUDENTS]; 17 | double studentGPAs[NUM_STUDENTS]; 18 | ifstream inputFile; 19 | int i = 0; 20 | 21 | inputFile.open("AdvancedFileIOFun/students.txt"); 22 | if (inputFile.fail()) { 23 | cout << "Failed to open the input file." << endl; 24 | exit(-1); 25 | } 26 | 27 | while (!inputFile.eof()) { 28 | // each iteration of loop, read in all of a single students info 29 | // name, class standing, gpa 30 | getline(inputFile, name); 31 | if (inputFile.good()) { 32 | studentNames[i] = name; 33 | } 34 | getline(inputFile, classStanding); 35 | if (inputFile.good()) { 36 | studentClassStandings[i] = classStanding; 37 | } 38 | inputFile >> gpa; 39 | if (inputFile.good()) { 40 | studentGPAs[i] = gpa; 41 | } 42 | // get rid of the newline character after the gpa 43 | getline(inputFile, tempString); 44 | // get rid of the newline character that separates groups of information 45 | getline(inputFile, tempString); 46 | i++; 47 | } 48 | 49 | // task: write a function that prints the student information stored in the parallel arrays 50 | printStudentInfo(studentNames, studentClassStandings, studentGPAs, i); 51 | 52 | inputFile.close(); 53 | 54 | 55 | return 0; 56 | } 57 | 58 | void printStudentInfo(string names[], string standings[], double gpas[], int numStudents) { 59 | int i = 0; 60 | 61 | for (i = 0; i < numStudents; i++) { 62 | cout << names[i] << " is a " << standings[i] << " with a GPA of " << gpas[i] << endl; 63 | } 64 | 65 | } 66 | 67 | // task: write functions that do the following: 68 | // 1. compute the average GPA 69 | // 2. count the number of each class standing 70 | // 3. find the most commonly used first letter of the first name 71 | 72 | 73 | -------------------------------------------------------------------------------- /ArrayFun/TwoDArrayFun.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | const int ROWS = 2; 6 | const int COLS = 3; 7 | const int TTT_SIZE = 3; 8 | 9 | // the compiler needs to know the size of all dimensions except the first 10 | void printArray(const int[][COLS], int, int); 11 | void printArray(const char[][COLS], int, int); 12 | void initializeBoard(char [][TTT_SIZE], int = TTT_SIZE, int = TTT_SIZE); //note that rows and columns are optional 13 | 14 | int main() { 15 | int myInts[ROWS][COLS] = {{1, 2, 3}, {4, 5, 6}}; 16 | char board[TTT_SIZE][TTT_SIZE]; 17 | int userRow = 0, userCol = 0; 18 | 19 | // task: write a function that initializes the TTT board to all blanks 'B' 20 | initializeBoard(board); 21 | // task: write a function that prints the TTT board 22 | // overload printArray() to do this 23 | printArray(board, TTT_SIZE, TTT_SIZE); 24 | 25 | // task: prompt the user for a row and col coordinate pair that represents where they would like to place an 'X' 26 | cout << "Please enter a row and column to place your symbol: "; 27 | cin >> userRow >> userCol; 28 | board[userRow][userCol] = 'X'; 29 | printArray(board, TTT_SIZE, TTT_SIZE); 30 | 31 | printArray(myInts, ROWS, COLS); 32 | 33 | return 0; 34 | } 35 | 36 | void initializeBoard(char arr[][TTT_SIZE], int rows, int cols) { 37 | int i = 0, j = 0; 38 | 39 | for (i = 0; i < rows; i++) { 40 | for (j = 0; j < cols; j++) { 41 | arr[i][j] = 'B'; 42 | } 43 | } 44 | 45 | } 46 | 47 | void printArray(const char arr[][COLS], int rows, int cols) { 48 | int i = 0, j = 0; 49 | // i is used as the row index 50 | // j is used as the column index 51 | 52 | // task: change the nested for loop so that it prints the output in a grid like structure 53 | 54 | for (i = 0; i < rows; i++) { 55 | for (j = 0; j < cols; j++) { 56 | cout << arr[i][j] << " "; // index twice because it is 2D 57 | } 58 | cout << endl; 59 | } 60 | cout << endl; 61 | 62 | } 63 | 64 | void printArray(const int arr[][COLS], int rows, int cols) { 65 | int i = 0, j = 0; 66 | // i is used as the row index 67 | // j is used as the column index 68 | 69 | // task: change the nested for loop so that it prints the output in a grid like structure 70 | 71 | for (i = 0; i < rows; i++) { 72 | for (j = 0; j < cols; j++) { 73 | cout << arr[i][j] << " "; // index twice because it is 2D 74 | } 75 | cout << endl; 76 | } 77 | cout << endl; 78 | 79 | } 80 | -------------------------------------------------------------------------------- /ConditionalsFun/BooleanFun.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | int main() { 6 | // Boolean is either true or false 7 | // Boolean expression (Boolean condition): an expression that evaluates to true or false 8 | bool isSunny = true; 9 | // true, false are reserved words 10 | // integer 0 is false 11 | // anything other than 0 is true 12 | // typically 1 is used for true 13 | 14 | int x = 3, y = 4, max = 100, min = 0; 15 | char ch = 'c'; 16 | 17 | 18 | cout << isSunny << endl; 19 | 20 | 21 | isSunny = false; 22 | 23 | cout << isSunny << endl; 24 | 25 | cout << (x <= 0) << endl; // F 26 | cout << (x == y) << endl; // F 27 | cout << (max >= min) << endl; // T 28 | cout << (ch < 'a') << endl; // F 29 | cout << (max) << endl; // T 30 | cout << (min != 0) << endl; // F 31 | cout << (max == 99 + 1) << endl; // T 32 | cout << (min - 50 < 0) << endl; // T 33 | 34 | 35 | return 0; 36 | } 37 | -------------------------------------------------------------------------------- /ConditionalsFun/ConditionalFun.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | int main() { 6 | bool isSunny = true; 7 | int temperature = 0; 8 | 9 | if (isSunny) { 10 | cout << "It is sunny outside :)" << endl; 11 | 12 | } 13 | else { // executes when !isSunny evaluates to true 14 | cout << "It is not sunny outside :(" << endl; 15 | 16 | } 17 | 18 | cout << "Outside of the if statement" << endl; 19 | 20 | // task: code up the flowchart from the notes 21 | // get the temperature value from the user 22 | cout << "Please enter the temperature: "; 23 | cin >> temperature; 24 | 25 | if (temperature > 32) { 26 | cout << "It is warm out" << endl; 27 | } 28 | else { // !(temperature > 32) -> temperature <= 32 29 | cout << "It is freezing out" << endl; 30 | } 31 | 32 | // task: add an else with a one line comment that shows the BC for the else 33 | if (temperature > 32 && isSunny == false) { 34 | 35 | } 36 | 37 | 38 | 39 | return 0; 40 | } 41 | -------------------------------------------------------------------------------- /ConditionalsFun/GuessMyNumberFun.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | int main() { 6 | // let's fix our secret number to be [1, 10] 7 | int secretNum = 4; // this is the number the user is trying to guess 8 | int userGuess = 0; // this is the users guess 9 | 10 | 11 | cout << "Welcome to the great guess my number game! Guess an integer in [1, 10]: "; 12 | cin >> userGuess; 13 | 14 | //cout << "You entered " << userGuess << endl; 15 | // task: using an if statement, tell the user if they guessed the number correctly or not 16 | 17 | if (userGuess == secretNum) { 18 | cout << "You guessed it! Nice work!" << endl; 19 | } 20 | else { // !(userGuess == secretNum) -> userGuess != secretNum 21 | cout << "You are wrong, nice try." << endl; 22 | } 23 | 24 | // task: give the user a hint, are they too high or are they too low 25 | if (userGuess < secretNum) { 26 | cout << "You are too low" << endl; 27 | } 28 | 29 | if (userGuess > secretNum) { 30 | cout << "You are too high" << endl; 31 | } 32 | 33 | // here 34 | return 0; 35 | } 36 | -------------------------------------------------------------------------------- /ConditionalsFun/GuessMyNumberFun2.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | int main() { 6 | // let's fix our secret number to be [1, 10] 7 | int secretNum = 4; // this is the number the user is trying to guess 8 | int userGuess = 0; // this is the users guess 9 | 10 | 11 | cout << "Welcome to the great guess my number game! Guess an integer in [1, 10]: "; 12 | cin >> userGuess; 13 | 14 | //cout << "You entered " << userGuess << endl; 15 | // task: using an if statement, tell the user if they guessed the number correctly or not 16 | 17 | if (userGuess == secretNum) { 18 | cout << "You guessed it! Nice work!" << endl; 19 | } 20 | else { 21 | cout << "You are wrong, but I'll give you a hint..." << endl; 22 | if (userGuess < secretNum) { 23 | cout << "You are too low" << endl; 24 | } 25 | if (userGuess > secretNum) { 26 | cout << "You are too high" << endl; 27 | } 28 | } 29 | 30 | // here 31 | return 0; 32 | } 33 | -------------------------------------------------------------------------------- /ConditionalsFun/GuessMyNumberFun3.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | int main() { 6 | // let's fix our secret number to be [1, 10] 7 | int secretNum = 4; // this is the number the user is trying to guess 8 | int userGuess = 0; // this is the users guess 9 | 10 | 11 | cout << "Welcome to the great guess my number game! Guess an integer in [1, 10]: "; 12 | cin >> userGuess; 13 | 14 | //cout << "You entered " << userGuess << endl; 15 | // task: using an if statement, tell the user if they guessed the number correctly or not 16 | // alternatives (BCs) are tested from top to bottom 17 | // as soon as one evaluates to true, that body is executed and no other BCs are tested 18 | // like skipping to the next executable statement after the multiple alternative if statement 19 | // each body is mutually exclusive 20 | // you can have as many else ifs as you want 21 | // only one if and it has to be first 22 | // only one else, it is optional, has to be the last body, at the end of the multiple alternative if statement 23 | 24 | if (userGuess == secretNum) { // BC1 25 | cout << "You guessed it! Nice work!" << endl; 26 | } 27 | else if (userGuess < secretNum) { // BC2 userGuess != secretNum (complement of BC1) 28 | cout << "You are too low" << endl; 29 | } 30 | else { // (userGuess != secretNum) && (userGuess >= secretNum) 31 | cout << "You are too high" << endl; 32 | } 33 | 34 | // here 35 | return 0; 36 | } 37 | -------------------------------------------------------------------------------- /ConditionalsFun/SwitchFun.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | int main() { 6 | /*A high school baseball team awards merit points to players based on their offensive performance. A single (encoded 's') is worth 1 point, a double (encoded 'd') is worth 2 points, a triple (encoded 't') is worth 3 points, and a home run (encoded 'h') is worth 4 points. Any at-bat that leads to an out (encoded 'o') worth 0 points. 7 | 8 | Task 1: Write a C++ if statement that, given an at-bat character from the user, properly awards points. */ 9 | 10 | char atBat = 'o', classStanding = 'f'; 11 | int points = 0; 12 | 13 | cout << "Please enter the at bat code: "; 14 | cin >> atBat; 15 | cout << "Please enter the class standing: "; 16 | cin >> classStanding; 17 | 18 | //cout << atBat << endl; 19 | /*if (atBat == 's') { 20 | points = 1; 21 | } 22 | else if (atBat == 'd') { 23 | points = 2; 24 | } 25 | else if (atBat == 't') { 26 | points = 3; 27 | } 28 | else if (atBat == 'h') { 29 | points = 4; 30 | } 31 | else if (atBat == 'o') { 32 | points = 0; 33 | } 34 | else { 35 | cout << "Unrecognize at bat code." << endl; 36 | }*/ 37 | 38 | /*if (atBat == 's') { 39 | points = 1; 40 | } 41 | else { 42 | if (atBat == 'd') { 43 | points = 2; 44 | } 45 | else { 46 | if (atBat == 't') { 47 | points = 3; 48 | } 49 | else { 50 | if (atBat == 'h') { 51 | points = 4; 52 | } 53 | else { 54 | if (atBat == 'o') { 55 | points = 0; 56 | } 57 | else { 58 | cout << "Unrecognize at bat code." << endl; 59 | } 60 | } 61 | } 62 | } 63 | }*/ 64 | 65 | // switch statement solution 66 | /*switch (atBat) { 67 | case 'S': 68 | case 's': 69 | points = 1; 70 | break; // causes an exit from the switch structure 71 | // without break, execution "falls" through to the next case 72 | case 'D': 73 | case 'd': 74 | points = 2; 75 | break; 76 | case 't': 77 | points = 3; 78 | break; 79 | case 'h': 80 | points = 4; 81 | break; 82 | case 'o': 83 | points = 0; 84 | break; 85 | default: 86 | cout << "Unrecognized character code." << endl; 87 | break; // break for default is optional 88 | 89 | }*/ 90 | 91 | /*A high school baseball team awards merit points to players based on their offensive performance and the class standing ('f' = freshman, 'o' = sophomore, 'j' = junior, and 's' = senior). In particular, freshmen and sophomores earn an extra point for home runs, whereas juniors and seniors do not earn any points for singles. Write a C++ if-statement that, given an at-bat character and a class standing character, properly awards points. 92 | 93 | */ 94 | 95 | if (atBat == 's') { 96 | points = 1; 97 | if (classStanding == 'j' || classStanding == 's') { 98 | // no points for singles 99 | points = 0; 100 | } 101 | } 102 | else if (atBat == 'd') { 103 | points = 2; 104 | } 105 | else if (atBat == 't') { 106 | points = 3; 107 | } 108 | else if (atBat == 'h') { 109 | points = 4; 110 | if (classStanding == 'f' || classStanding == 'o') { 111 | // extra point for homeruns 112 | points = points + 1; // 5 113 | } 114 | } 115 | else if (atBat == 'o') { 116 | points = 0; 117 | } 118 | else { 119 | cout << "Unrecognize at bat code." << endl; 120 | } 121 | 122 | cout << "Number of points awarded: " << points << endl; 123 | 124 | // task 2: re-solve the above multiple alternative if statement to use nested if statements (no else ifs) 125 | 126 | return 0; 127 | } 128 | -------------------------------------------------------------------------------- /CppBasicsFun/ArithmeticFun.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | int main() { 6 | int x = 5; 7 | int y = 0; 8 | double z = 5.0; 9 | 10 | x = x + 2; 11 | cout << "x: " << x << endl; 12 | cout << "y - 2: " << (y - 2) << endl; 13 | x = x - y / z; 14 | // order of precendence, how is this evaluated? 15 | //(x - y) / z or x - (y / z) 16 | 17 | cout << (13 % 10) << endl; 18 | cout << (1.0 / 3 * 3.14 * 5.0 * 5.0 * 10.0) << endl; 19 | 20 | 21 | return 0; 22 | } 23 | -------------------------------------------------------------------------------- /CppBasicsFun/BasicsFun.cpp: -------------------------------------------------------------------------------- 1 | // this is a single line comment 2 | // comments are not compiled by the compiler, they are ignored! 3 | 4 | // we can also have multi line commments, called comment blocks 5 | /* 6 | 7 | this is 8 | a 9 | 10 | multi 11 | 12 | line comment 13 | 14 | */ 15 | 16 | /* one liner */ 17 | 18 | 19 | // libraries our program needs to include 20 | #include // io stands for input output 21 | // use iostream to get access to cin and cout for user input and output 22 | 23 | // any line that starts with # is called a pre processor directive 24 | 25 | // after preprocessor directives, we have using namespace statements 26 | 27 | using namespace std; // use the standard namespace 28 | // so we don't have to type std::cin or std::cout 29 | 30 | // every program has to have a main() function 31 | // it is the main entry point to execution of your program 32 | int main() { 33 | // good habit to put all variable declarations at the top main() so you can easily find them 34 | // a variable is a location in memory that stores a value 35 | // declare an integer variable called x 36 | int x; 37 | double gasPrice = 3.89; 38 | int gasPriceAsInt; 39 | // good practice to intialize variables when you declare them! 40 | 41 | 42 | cout << gasPriceAsInt << endl; // garbage value! 43 | gasPriceAsInt = gasPrice; // fractional part is truncated 44 | cout << gasPriceAsInt << endl; 45 | cout << static_cast(gasPrice) << endl; 46 | 47 | // initialize x to store 5 48 | x = 5; // read "this is assigned 5" 49 | // = is the assignment operator, not the equality operator 50 | cout << "x stores: " << x << endl; 51 | cout << "gasPrice stores: " << gasPrice << endl; 52 | 53 | cout << "Hello from BasicsFun.cpp :)" << endl; 54 | // use cout to display text to the user via the terminal 55 | // terminal is AKA console 56 | // << is the stream insertion operator 57 | // it inserts whatever is to the right in the "stream" 58 | // to the left (cout) 59 | // anything surrounded by double quotes is a string literal 60 | // a string a sequence of characters 61 | // endl is a newline 62 | 63 | 64 | 65 | 66 | return 0; // always be the last line in our programs 67 | // says this program is done executing 68 | // 0 is the result code, tells the OS this program executed successfully (without error) 69 | } 70 | 71 | 72 | -------------------------------------------------------------------------------- /CppBasicsFun/ConeVolumeFun.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | int main() { 6 | double radius = 0.0; 7 | double height = 0.0; 8 | double volume = 0.0; 9 | const double PI = 3.14159; 10 | // const is short for constant, compiler ensures that const variables are never re-assigned 11 | // name const variables in all caps by convention 12 | 13 | cout << "Please enter the radius: "; 14 | cin >> radius; 15 | cout << "radius: " << radius << endl; 16 | cout << "Please enter the height: "; 17 | cin >> height; 18 | cout << "height: " << height << endl; 19 | 20 | // formula for volume of a cone 21 | // V = 1/3 pi r^2 h 22 | volume = 1.0 / 3.0 * PI * radius * radius * height; 23 | cout << "The volume of a cone with radius " << radius << " and height " << height << " is " << volume << endl; 24 | 25 | //PI = 0.0; // causes compiler error! 26 | // task: in a new file, CircleAreaFun.cpp, code up a solution to computing the area of a circle from user inputted radius 27 | // have fun!! 28 | 29 | return 0; 30 | } 31 | -------------------------------------------------------------------------------- /CppBasicsFun/ErrorFun.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | int main() { 6 | int x = 5; 7 | cout << "Hello there" << endl; 8 | 9 | //x = x / 0; 10 | 11 | cout << "here" << endl; 12 | 13 | return 0; 14 | } 15 | -------------------------------------------------------------------------------- /CppBasicsFun/HelloWorld.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | int main() { 6 | cout << "Hello CPSC 121!! :) :) :0)" << endl; 7 | 8 | return 0; 9 | } 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /CppBasicsFun/InputOutputFun.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | int main() { 7 | string name = ""; // empty string 8 | string lastName = ""; 9 | string place = ""; 10 | string favoriteVacationSpot = ""; 11 | int favoriteNumber = 0; 12 | int year = 0; 13 | // review using cout and << 14 | // learn about using cin and >> 15 | 16 | // every time we get input from the user, we should provide a prompt so the user knows what they are supposed to do 17 | cout << "Please enter your name: "; 18 | cin >> name; 19 | // cin is a stream connected to stanard input (console input) 20 | // the >> is the stream extraction operator and it extracts data from a buffer that stores the text the user typed when they pressed enter 21 | cout << "Hello there, " << name << endl; 22 | 23 | cin >> lastName; 24 | cout << "Last name: " << lastName << endl; 25 | 26 | cout << "Please enter your favorite number: "; 27 | cin >> favoriteNumber; 28 | cout << "Favorite number: " << favoriteNumber << endl; 29 | 30 | // task: prompt the user the year and the place they were born 31 | cout << "Please enter the year you were born: "; 32 | cin >> year; 33 | 34 | cout << "Please enter the state you were born in: "; 35 | cin >> place; 36 | 37 | cout << "You were born in " << place << " in the year " << year << endl; 38 | 39 | cout << "Please enter your favorite vacation spot: "; 40 | getline(cin, favoriteVacationSpot); // gets rid of the newline character, stores the empty string in favoriteVacationSpot, which we ignore! 41 | getline(cin, favoriteVacationSpot); 42 | cout << "Your favorite vacation spot: " << favoriteVacationSpot << endl; 43 | 44 | return 0; 45 | } 46 | -------------------------------------------------------------------------------- /FileIOReviewFun/Main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | void openFile(ifstream&, string); 8 | void processFile(ifstream&); 9 | 10 | int main() { 11 | // 1. open the file 12 | ifstream inFile; 13 | openFile(inFile, "sentence.txt"); 14 | 15 | // 2. process the file 16 | processFile(inFile); 17 | 18 | // 3. close the file 19 | inFile.close(); 20 | 21 | return 0; 22 | } 23 | 24 | void processFile(ifstream& inFile) { 25 | string line, word; 26 | istringstream iss; 27 | 28 | ofstream outFile; 29 | outFile.open("chars.txt"); 30 | 31 | 32 | while (!inFile.eof()) { 33 | // read line by line from the file 34 | getline(inFile, line); 35 | if (inFile.good()) { 36 | //cout << line << endl; 37 | // read word by word from the line 38 | iss.clear(); // clear out state 39 | iss.str(line); 40 | while (iss.good()) { 41 | iss >> word; 42 | //cout << word << endl; 43 | // read char by char from the word 44 | //for (char c : word) { 45 | //cout << c << endl; 46 | //} 47 | for (int i = 0; i < word.length(); i++) { 48 | outFile << word[i] << endl; 49 | } 50 | } 51 | } 52 | } 53 | outFile.close(); 54 | } 55 | 56 | void openFile(ifstream& inFile, string fname) { 57 | inFile.open(fname); 58 | if (inFile.is_open()) { 59 | cout << "Successfully opened file" << endl; 60 | } 61 | else { 62 | cout << "Failed to open file" << endl; 63 | exit(-1); 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /FileIOReviewFun/chars.txt: -------------------------------------------------------------------------------- 1 | t 2 | h 3 | e 4 | q 5 | u 6 | i 7 | c 8 | k 9 | b 10 | r 11 | o 12 | w 13 | n 14 | f 15 | o 16 | x 17 | j 18 | u 19 | m 20 | p 21 | s 22 | o 23 | v 24 | e 25 | r 26 | t 27 | h 28 | e 29 | l 30 | a 31 | z 32 | y 33 | d 34 | o 35 | g 36 | -------------------------------------------------------------------------------- /FileIOReviewFun/sentence.txt: -------------------------------------------------------------------------------- 1 | the quick brown 2 | fox jumps 3 | over the lazy 4 | dog 5 | -------------------------------------------------------------------------------- /FilesFun/AdvancedFileIOFun/AdvancedFileIOFun.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | int main() { 8 | // task: read each line from the file as a string and display it to the console 9 | string name = "", classStanding = "", tempString = ""; 10 | double gpa = 0.0; 11 | ifstream inputFile; 12 | 13 | inputFile.open("students.txt"); 14 | if (inputFile.fail()) { 15 | cout << "Failed to open the input file." << endl; 16 | exit(-1); 17 | } 18 | 19 | while (!inputFile.eof()) { 20 | // each iteration of loop, read in all of a single students info 21 | // name, class standing, gpa 22 | getline(inputFile, name); 23 | if (inputFile.good()) { 24 | cout << "Name: " << name << endl; 25 | } 26 | getline(inputFile, classStanding); 27 | if (inputFile.good()) { 28 | cout << "Class standing: " << classStanding << endl; 29 | } 30 | inputFile >> gpa; 31 | if (inputFile.good()) { 32 | cout << "GPA: " << gpa << endl; 33 | } 34 | // get rid of the newline character after the gpa 35 | getline(inputFile, tempString); 36 | // get rid of the newline character that separates groups of information 37 | getline(inputFile, tempString); 38 | } 39 | 40 | 41 | inputFile.close(); 42 | 43 | 44 | return 0; 45 | } 46 | -------------------------------------------------------------------------------- /FilesFun/AdvancedFileIOFun/students.txt: -------------------------------------------------------------------------------- 1 | Jane Student 2 | Freshman 3 | 3.5 4 | 5 | Joe Schmoe 6 | Senior 7 | 3.7 8 | 9 | Mary Lamb 10 | Sophomore 11 | 2.5 12 | -------------------------------------------------------------------------------- /FilesFun/FileIOFun/FileIOFun.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include // used for ifstream and ofstream data types 3 | 4 | 5 | using namespace std; 6 | 7 | int main() { 8 | // declare a variable to open a file for reading 9 | // ifstream data type is for "input" from a file 10 | // ofstream data type is for "output" to a file 11 | ifstream inputFile; 12 | 13 | // 1. open the file 14 | inputFile.open("transactions.txt"); // pass in a string representing a path to a file to open 15 | 16 | // check if open is successful 17 | if (inputFile.is_open()) { 18 | cout << "Successfully opened the input file." << endl; 19 | } 20 | else { // !inputFile.is_open() 21 | cout << "Failed to open the input file." << endl; 22 | exit(-1); // exit the program 23 | } 24 | cout << "here" << endl; 25 | // 2. process the file 26 | 27 | 28 | // 3. close the file 29 | inputFile.close(); // releases resources 30 | // data written to the file is actually written to the disk 31 | 32 | 33 | return 0; 34 | } 35 | -------------------------------------------------------------------------------- /FilesFun/FileIOFun/transactions.txt: -------------------------------------------------------------------------------- 1 | 12.45 2 | 32.56 3 | 67.43 4 | 44.22 5 | 101.10 6 | 300.03 7 | -------------------------------------------------------------------------------- /FilesFun/FileIOFun2/FileIOFun2.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include // used for ifstream and ofstream data types 3 | 4 | 5 | using namespace std; 6 | 7 | int main() { 8 | // declare a variable to open a file for reading 9 | // ifstream data type is for "input" from a file 10 | // ofstream data type is for "output" to a file 11 | ifstream inputFile; 12 | ofstream outputFile; 13 | double transaction = 0.0, totalTransaction = 0.0, avgTransaction = 0.0; 14 | int i = 0, numTransactions = 0; 15 | 16 | // 1. open the file 17 | inputFile.open("transactions.txt"); // pass in a string representing a path to a file to open 18 | 19 | // check if open is successful 20 | if (inputFile.is_open()) { 21 | cout << "Successfully opened the input file." << endl; 22 | } 23 | else { // !inputFile.is_open() 24 | cout << "Failed to open the input file." << endl; 25 | exit(-1); // exit the program 26 | } 27 | outputFile.open("avg_transaction.txt"); 28 | 29 | // 2. process the file 30 | // read a single transaction from the file 31 | // reading always starts from the beginning of the file 32 | 33 | // task: read the rest of the values from the file 34 | while (!inputFile.eof()) { 35 | inputFile >> transaction; 36 | // the above code fails when it tries to read a value and there are no more values to read (e.g. at the end of file) 37 | // in this case, transaction is not overwritten with a new value, so it appears the last value is printed twice 38 | // fix: check to see if the >> operation succeeded or not 39 | // inputFile.good() checks only the most recent stream operation for success or failure. typically put it right after you do something with the file 40 | if (inputFile.good()) { 41 | cout << "Read: " << transaction << endl; 42 | totalTransaction += transaction; 43 | numTransactions++; 44 | } 45 | else { 46 | cout << "Failed to read a transaction." << endl; 47 | } 48 | } 49 | 50 | // task: compute the average transaction 51 | avgTransaction = totalTransaction / numTransactions; 52 | outputFile << avgTransaction << endl; 53 | 54 | // 3. close the file 55 | inputFile.close(); // releases resources 56 | outputFile.close(); 57 | // data written to the file is actually written to the disk 58 | 59 | 60 | return 0; 61 | } 62 | -------------------------------------------------------------------------------- /FilesFun/FileIOFun2/avg_transaction.txt: -------------------------------------------------------------------------------- 1 | 92.965 2 | -------------------------------------------------------------------------------- /FilesFun/FileIOFun2/transactions.txt: -------------------------------------------------------------------------------- 1 | 12.45 2 | 32.56 3 | 67.43 4 | 44.22 5 | 101.10 6 | 300.03 7 | -------------------------------------------------------------------------------- /FunctionFun/AdvancedPrototypeFun.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | const int SIX_SIDES = 6; 8 | const int TEN_SIDES = 10; 9 | 10 | // default argument: when an argument is not specified for numSides, it will be 6 11 | int rollDie(int = SIX_SIDES); 12 | void displayRollResult(int); 13 | // overload displayRollResult() so it accepts a 2nd argument, the number of sides of the die rolled 14 | void displayRollResult(int, int); 15 | 16 | int main() { 17 | int roll = 0; 18 | 19 | srand(time(0)); 20 | 21 | roll = rollDie(); 22 | displayRollResult(roll); 23 | 24 | roll = rollDie(TEN_SIDES); 25 | displayRollResult(roll); 26 | 27 | roll = rollDie(TEN_SIDES); 28 | displayRollResult(roll, TEN_SIDES); 29 | 30 | 31 | return 0; 32 | } 33 | 34 | void displayRollResult(int result, int numSides) { 35 | cout << "You just rolled a " << numSides << "-sided die and a got a " << result << "!" << endl; 36 | } 37 | 38 | void displayRollResult(int result) { 39 | cout << "You just rolled a " << result << "!" << endl; 40 | } 41 | 42 | int rollDie(int numSides) { 43 | int roll = 0; 44 | 45 | roll = rand() % numSides + 1; 46 | 47 | return roll; 48 | 49 | } 50 | -------------------------------------------------------------------------------- /FunctionFun/DoubleInclusionDemo/Header.h: -------------------------------------------------------------------------------- 1 | #ifndef HEADER_H 2 | #define HEADER_H 3 | 4 | #include "TopLevelHeader.h" 5 | 6 | #endif 7 | -------------------------------------------------------------------------------- /FunctionFun/DoubleInclusionDemo/Main.cpp: -------------------------------------------------------------------------------- 1 | #include "Header.h" 2 | #include "TopLevelHeader.h" 3 | 4 | int main() { 5 | 6 | 7 | } 8 | -------------------------------------------------------------------------------- /FunctionFun/DoubleInclusionDemo/TopLevelHeader.h: -------------------------------------------------------------------------------- 1 | // header file guard code fixes the problem of redefinition of 'const double PI' we get from the compiler 2 | 3 | #ifndef TOP_LEVEL_HEADER_H 4 | #define TOP_LEVEL_HEADER_H 5 | 6 | const double PI = 3.14; 7 | 8 | #endif 9 | -------------------------------------------------------------------------------- /FunctionFun/FunctionFun.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | // put function definitions before any code that calls the function 7 | // compiler needs to know about the function before it can execute it when it encounters a function call 8 | 9 | int f(int x) { 10 | int y; 11 | 12 | y = pow(x, 2.0) - 4 * x + 4; 13 | return y; 14 | } 15 | 16 | bool checkIfEven(int num) { 17 | if (num % 2 == 0) { 18 | return true; 19 | } 20 | else { 21 | return false; 22 | } 23 | } 24 | 25 | int main() { 26 | int result = 0; 27 | 28 | result = f(1); 29 | cout << result << endl; 30 | 31 | result = f(2); 32 | cout << result << endl; 33 | 34 | result = f(3); 35 | cout << result << endl; 36 | 37 | cout << checkIfEven(3) << endl; 38 | cout << checkIfEven(10) << endl; 39 | 40 | return 0; 41 | } 42 | -------------------------------------------------------------------------------- /FunctionFun/GPAFunctionFun.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | int main() { 6 | double gp1, gp2, gp3, weightedCredits, gpa; 7 | int numCredits1, numCredits2, numCredits3, totalNumCredits; 8 | 9 | // get grade point and credit hours for each class 10 | cout << "Please enter the grade point for your computer science course: " << endl; 11 | cin >> gp1; 12 | cout << "Please enter number of credits for your computer science course: " << endl; 13 | cin >> numCredits1; 14 | 15 | cout << "Please enter the grade point for your math course: " << endl; 16 | cin >> gp2; 17 | cout << "Please enter number of credits for your math course: " << endl; 18 | cin >> numCredits2; 19 | 20 | cout << "Please enter the grade point for your karate course: " << endl; 21 | cin >> gp3; 22 | cout << "Please enter number of credits for your karate course: " << endl; 23 | cin >> numCredits3; 24 | 25 | // compute the weighted credit hours earned 26 | weightedCredits = (numCredits1 * gp1) + (numCredits2 * gp2) + (numCredits3 * gp3); 27 | 28 | // compute the total number of credits earned 29 | totalNumCredits = numCredits1 + numCredits2 + numCredits3; 30 | 31 | // compute the average of the grade points 32 | gpa = weightedCredits / totalNumCredits; 33 | 34 | // display the results to the user 35 | cout << "Your GPA is: " << gpa << endl; 36 | } 37 | 38 | -------------------------------------------------------------------------------- /FunctionFun/GPAFunctionFun2.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | double getGradePoint(string courseName) { 6 | double gp = 0.0; 7 | cout << "Please enter the grade point for your " << courseName << " course: " << endl; 8 | cin >> gp; 9 | return gp; 10 | } 11 | 12 | // task: define and call the getNumberCredits() function 13 | int getNumberCredits(string courseName) { 14 | int numCredits = 0; 15 | 16 | cout << "Please enter number of credits for your " << courseName << " course: " << endl; 17 | cin >> numCredits; 18 | return numCredits; 19 | } 20 | 21 | double computeWeightedCredits(double gp1, double gp2, double gp3, int numCredits1, int numCredits2, int numCredits3) { 22 | double weightedCredits = 0.0; 23 | 24 | weightedCredits = (numCredits1 * gp1) + (numCredits2 * gp2) + (numCredits3 * gp3); 25 | 26 | return weightedCredits; 27 | 28 | } 29 | 30 | int computeTotalCredits(int nc1, int nc2, int nc3) { 31 | int totalCredits = 0; 32 | 33 | totalCredits = nc1 + nc2 + nc3; 34 | 35 | return totalCredits; 36 | } 37 | 38 | double computeGPA(double weightedCredits, int totalCredits) { 39 | return (weightedCredits / totalCredits); 40 | } 41 | 42 | void displayGPA(double gpa) { 43 | cout << "Your GPA is: " << gpa << endl; 44 | } 45 | 46 | int main() { 47 | double gp1, gp2, gp3, weightedCredits, gpa; 48 | int numCredits1, numCredits2, numCredits3, totalNumCredits; 49 | 50 | // get grade point and credit hours for each class 51 | gp1 = getGradePoint("computer science"); 52 | numCredits1 = getNumberCredits("computer science"); 53 | 54 | gp2 = getGradePoint("math"); 55 | numCredits2 = getNumberCredits("math"); 56 | 57 | gp3 = getGradePoint("karate"); 58 | numCredits3 = getNumberCredits("karate"); 59 | 60 | // compute the weighted credit hours earned 61 | weightedCredits = computeWeightedCredits(gp1, gp2, gp3, numCredits1, numCredits2, numCredits3); 62 | 63 | // compute the total number of credits earned 64 | totalNumCredits = computeTotalCredits(numCredits1, numCredits2, numCredits3); 65 | 66 | // compute the average of the grade points 67 | gpa = computeGPA(weightedCredits, totalNumCredits); 68 | 69 | // display the results to the user 70 | displayGPA(gpa); 71 | } 72 | 73 | -------------------------------------------------------------------------------- /FunctionFun/PrototypeFun.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | double getGradePoint(string); 6 | int getNumberCredits(string); 7 | double computeWeightedCredits(double, double, double, int, int, int); 8 | int computeTotalCredits(int, int, int); 9 | double computeGPA(double, int); 10 | void displayGPA(double); 11 | 12 | int main() { 13 | double gp1, gp2, gp3, weightedCredits, gpa; 14 | int numCredits1, numCredits2, numCredits3, totalNumCredits; 15 | 16 | // get grade point and credit hours for each class 17 | gp1 = getGradePoint("computer science"); 18 | numCredits1 = getNumberCredits("computer science"); 19 | 20 | gp2 = getGradePoint("math"); 21 | numCredits2 = getNumberCredits("math"); 22 | 23 | gp3 = getGradePoint("karate"); 24 | numCredits3 = getNumberCredits("karate"); 25 | 26 | // compute the weighted credit hours earned 27 | weightedCredits = computeWeightedCredits(gp1, gp2, gp3, numCredits1, numCredits2, numCredits3); 28 | 29 | // compute the total number of credits earned 30 | totalNumCredits = computeTotalCredits(numCredits1, numCredits2, numCredits3); 31 | 32 | // compute the average of the grade points 33 | gpa = computeGPA(weightedCredits, totalNumCredits); 34 | 35 | // display the results to the user 36 | displayGPA(gpa); 37 | } 38 | 39 | 40 | 41 | double getGradePoint(string courseName) { 42 | double gp = 0.0; 43 | cout << "Please enter the grade point for your " << courseName << " course: " << endl; 44 | cin >> gp; 45 | return gp; 46 | } 47 | 48 | // task: define and call the getNumberCredits() function 49 | int getNumberCredits(string courseName) { 50 | int numCredits = 0; 51 | 52 | cout << "Please enter number of credits for your " << courseName << " course: " << endl; 53 | cin >> numCredits; 54 | return numCredits; 55 | } 56 | 57 | double computeWeightedCredits(double gp1, double gp2, double gp3, int numCredits1, int numCredits2, int numCredits3) { 58 | double weightedCredits = 0.0; 59 | 60 | weightedCredits = (numCredits1 * gp1) + (numCredits2 * gp2) + (numCredits3 * gp3); 61 | 62 | return weightedCredits; 63 | 64 | } 65 | 66 | int computeTotalCredits(int nc1, int nc2, int nc3) { 67 | int totalCredits = 0; 68 | 69 | totalCredits = nc1 + nc2 + nc3; 70 | 71 | return totalCredits; 72 | } 73 | 74 | double computeGPA(double weightedCredits, int totalCredits) { 75 | return (weightedCredits / totalCredits); 76 | } 77 | 78 | void displayGPA(double gpa) { 79 | cout << "Your GPA is: " << gpa << endl; 80 | } 81 | 82 | 83 | 84 | -------------------------------------------------------------------------------- /FunctionFun/ReferenceFun/ReferenceFun.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | int rollDie(); 9 | void displayRollResult(int); 10 | // write a function that rolls two dice 11 | // use reference variables to "return" the two dice results 12 | void rollTwoDice(int&, int&); 13 | void writeRollResults(ofstream&, int, int); 14 | 15 | int main() { 16 | int roll = 0, roll2 = 0; 17 | ofstream outputFile; 18 | 19 | srand(time(0)); 20 | 21 | roll = rollDie(); 22 | displayRollResult(roll); 23 | 24 | // roll1 in rollTwoDice() is a reference for roll in main() 25 | // roll2 in rollTwoDice() is a reference for roll2 in main() 26 | rollTwoDice(roll, roll2); 27 | displayRollResult(roll); 28 | displayRollResult(roll2); 29 | 30 | outputFile.open("roll_results.txt"); 31 | writeRollResults(outputFile, roll, roll2); 32 | outputFile.close(); 33 | 34 | return 0; 35 | } 36 | 37 | void writeRollResults(ofstream& outputFile, int roll1, int roll2) { 38 | outputFile << "You rolled a " << roll1 << " and a " << roll2 << "!" << endl; 39 | } 40 | 41 | void rollTwoDice(int& roll1, int& roll2) { 42 | //roll1 = rollDie(); 43 | //roll2 = rollDie(); 44 | roll1 = 100; 45 | roll2 = 500; 46 | // note that there is no return statement 47 | // but main() will be able to use these two roll results 48 | // via the reference variables 49 | // pass by reference 50 | } 51 | 52 | int rollDie() { 53 | int roll = 0; 54 | 55 | roll = rand() % 6 + 1; 56 | return roll; 57 | } 58 | 59 | void displayRollResult(int result) { 60 | cout << "You rolled a " << result << "!" << endl; 61 | } 62 | -------------------------------------------------------------------------------- /FunctionFun/ReferenceFun/roll_results.txt: -------------------------------------------------------------------------------- 1 | You rolled a 100 and a 500! 2 | -------------------------------------------------------------------------------- /FunctionFun/ScopeFun.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | 6 | const int MAX = 950; 7 | 8 | void one(int anarg, double second) { 9 | int oneLocal; 10 | funTwo(1, 'a'); 11 | } 12 | 13 | void funTwo(int one, char anarg) { 14 | int localVar; 15 | } 16 | 17 | const int LIMIT = 200; 18 | 19 | 20 | int main() { 21 | int localVar; 22 | } 23 | -------------------------------------------------------------------------------- /FunctionFun/ThreeFileFormatFun/DiceFunctions.cpp: -------------------------------------------------------------------------------- 1 | #include "DiceFunctions.h" 2 | 3 | 4 | 5 | void writeRollResults(ofstream& outputFile, int roll1, int roll2) { 6 | outputFile << "You rolled a " << roll1 << " and a " << roll2 << "!" << endl; 7 | } 8 | 9 | void rollTwoDice(int& roll1, int& roll2) { 10 | //roll1 = rollDie(); 11 | //roll2 = rollDie(); 12 | roll1 = 100; 13 | roll2 = 500; 14 | // note that there is no return statement 15 | // but main() will be able to use these two roll results 16 | // via the reference variables 17 | // pass by reference 18 | } 19 | 20 | int rollDie() { 21 | int roll = 0; 22 | 23 | roll = rand() % 6 + 1; 24 | return roll; 25 | } 26 | 27 | void displayRollResult(int result) { 28 | cout << "You rolled a " << result << "!" << endl; 29 | } 30 | -------------------------------------------------------------------------------- /FunctionFun/ThreeFileFormatFun/DiceFunctions.h: -------------------------------------------------------------------------------- 1 | #ifndef DICE_FUNCTIONS_H 2 | #define DICE_FUNCTIONS_H 3 | 4 | #include 5 | #include 6 | #include 7 | #include 8 | 9 | using namespace std; 10 | 11 | int rollDie(); 12 | void displayRollResult(int); 13 | // write a function that rolls two dice 14 | // use reference variables to "return" the two dice results 15 | void rollTwoDice(int&, int&); 16 | void writeRollResults(ofstream&, int, int); 17 | 18 | #endif 19 | -------------------------------------------------------------------------------- /FunctionFun/ThreeFileFormatFun/Main.cpp: -------------------------------------------------------------------------------- 1 | #include "DiceFunctions.h" 2 | 3 | int main() { 4 | int roll = 0, roll2 = 0; 5 | ofstream outputFile; 6 | 7 | srand(time(0)); 8 | 9 | roll = rollDie(); 10 | displayRollResult(roll); 11 | 12 | // roll1 in rollTwoDice() is a reference for roll in main() 13 | // roll2 in rollTwoDice() is a reference for roll2 in main() 14 | rollTwoDice(roll, roll2); 15 | displayRollResult(roll); 16 | displayRollResult(roll2); 17 | 18 | outputFile.open("roll_results.txt"); 19 | writeRollResults(outputFile, roll, roll2); 20 | outputFile.close(); 21 | 22 | return 0; 23 | } 24 | 25 | 26 | -------------------------------------------------------------------------------- /FunctionFun/ThreeFileFormatFun/roll_results.txt: -------------------------------------------------------------------------------- 1 | You rolled a 100 and a 500! 2 | -------------------------------------------------------------------------------- /InheritanceFun/Animal.cpp: -------------------------------------------------------------------------------- 1 | #include "Animal.h" 2 | 3 | Animal::Animal() { 4 | cout << "Hello from Animal()" << endl; 5 | species = "default species"; 6 | age = 0; 7 | } 8 | 9 | Animal::Animal(string speciesParam, int ageParam) { 10 | cout << "Hello from Animal(string, int)" << endl; 11 | species = speciesParam; 12 | age = ageParam; 13 | } 14 | 15 | // returns a string representation of the object 16 | string Animal::toString() { 17 | return "a " + to_string(age) + "-year old " + species; 18 | } 19 | -------------------------------------------------------------------------------- /InheritanceFun/Animal.h: -------------------------------------------------------------------------------- 1 | #ifndef ANIMAL_H 2 | #define ANIMAL_H 3 | 4 | #include 5 | using namespace std; 6 | 7 | class Animal { 8 | // access specifiers (AKA modifiers) 9 | // private: accessible within this class only 10 | // public: accessibly anywhere 11 | // protected: accessibly within this class and its subclasses 12 | protected: 13 | string species; 14 | int age; 15 | public: 16 | Animal(); 17 | Animal(string, int); 18 | virtual string toString(); // virtual means use dynamic binding to figure out which toString() to execute at run time (base class toString() or the derived class toString()) 19 | }; 20 | 21 | #endif 22 | -------------------------------------------------------------------------------- /InheritanceFun/Main.cpp: -------------------------------------------------------------------------------- 1 | #include "Animal.h" 2 | #include "Pet.h" 3 | #include "WildAnimal.h" 4 | 5 | int main() { 6 | Animal a; // DV 7 | cout << a.toString() << endl; 8 | Animal d("dog", 4); // EVC 9 | cout << d.toString() << endl; 10 | 11 | // recall... composition is a "has-a" relationship between two classes 12 | // Circle has a Point 13 | // inheritance is a "is-a" relationship between two classes 14 | // inheritance a relationship between two classes where one class includes ("inherits") the state AND the behavior of the the other class 15 | // state: attributes (AKA member variables) 16 | // behavior: member functions (constructors and destructor are not inherited) 17 | // example 18 | // Animal is going to be a base class 19 | // base class AKA parent class AKA super class 20 | // Pet is going to be a derived class 21 | // derived class AKA child class AKA sub class 22 | // then we will come back to main and make a few Pet objects and exercise the inheritance hierarchy 23 | 24 | Pet p1; // DVC 25 | cout << p1.toString() << endl; 26 | Pet myPet("Dog", 7, "Odin"); // EVC 27 | cout << myPet.toString() << endl; 28 | 29 | // let's say we have a pointer to an Animal 30 | Animal * aPtr = &a; 31 | cout << aPtr->toString() << endl; 32 | aPtr = &myPet; 33 | // example of static binding 34 | // at compile time the compiler figures out 35 | // which toString() to execute (Animal toString or the Pet toString()) 36 | cout << aPtr->toString() << endl; 37 | Pet * pPtr = &myPet; 38 | cout << pPtr->toString() << endl; 39 | // dynamic binding 40 | // figure out at runtime which toString() to execute 41 | // need to use the virtual keyword... to do this 42 | 43 | WildAnimal wa; // DVC 44 | cout << wa.toString() << endl; 45 | WildAnimal tiger("Tiger", 2, "Roar"); 46 | cout << tiger.toString() << endl; 47 | 48 | // polymorphism: same code, different behavior 49 | // with a pointer or a reference to an object, we can call a virtual member function to get object specific behavior at run time, even if the pointer or reference is of a more general type (e.g. super class such as Animal) 50 | // example: array of Animal * 51 | // some will point to Animal objects, some will point to Pet objects, some point to WildAnimal objects 52 | // we will call toString() in a loop for each pointer 53 | // with dynamic binding we are going to get different behavior (e.g. Animal, Pet, or WildAnimal specific toString()) with the same code (animalPtr->toString()) 54 | Animal * animalPtrArr[4]; 55 | animalPtrArr[0] = &a; 56 | animalPtrArr[1] = &myPet; 57 | animalPtrArr[2] = &tiger; 58 | animalPtrArr[3] = &d; 59 | for (Animal * animalPtr : animalPtrArr) { 60 | // same code for all objects pointed to 61 | cout << animalPtr->toString() << endl; 62 | } 63 | 64 | 65 | return 0; 66 | } 67 | -------------------------------------------------------------------------------- /InheritanceFun/Pet.cpp: -------------------------------------------------------------------------------- 1 | #include "Pet.h" 2 | 3 | Pet::Pet() : Animal() { 4 | // Pet() is going to first invoke Animal() DVC 5 | cout << "Hello from Pet()" << endl; 6 | // initialize the Pet specific attribute name 7 | name = "default name"; 8 | } 9 | 10 | Pet::Pet(string nameParam) : Animal() { 11 | cout << "Hello from Pet(string)" << endl; 12 | name = nameParam; 13 | } 14 | 15 | Pet::Pet(string speciesParam, int ageParam, string nameParam) : Animal(speciesParam, ageParam) { 16 | cout << "Hello from Pet(string, int, string)" << endl; 17 | name = nameParam; 18 | } 19 | 20 | // redefine more specific behavior for toString() 21 | string Pet::toString() { 22 | return Animal::toString() + " named " + name; 23 | } 24 | -------------------------------------------------------------------------------- /InheritanceFun/Pet.h: -------------------------------------------------------------------------------- 1 | #ifndef PET_H 2 | #define PET_H 3 | 4 | #include 5 | #include "Animal.h" 6 | 7 | using namespace std; 8 | 9 | // access specifier before the name of the base class 10 | // to specify how public attributes of the base class 11 | // are inherited 12 | // public attributes/member functions of Animal 13 | // will be public in Pet 14 | class Pet : public Animal { 15 | // we put Pet specific state and behavior 16 | private: 17 | string name; // e.g. fido, odin, buddy 18 | public: 19 | Pet(); 20 | Pet(string); 21 | Pet(string, int, string); 22 | // redefine more specific behavior for toString() 23 | string toString(); 24 | }; 25 | 26 | 27 | #endif 28 | -------------------------------------------------------------------------------- /InheritanceFun/WildAnimal.cpp: -------------------------------------------------------------------------------- 1 | #include "WildAnimal.h" 2 | 3 | WildAnimal::WildAnimal() : Animal() { 4 | // WildAnimal() is going to first invoke Animal() DVC 5 | cout << "Hello from WildAnimal()" << endl; 6 | // initialize the WildAnimal specific attribute name 7 | ferociousNoise = "default noise"; 8 | } 9 | 10 | WildAnimal::WildAnimal(string noiseParam) : Animal() { 11 | cout << "Hello from WildAnimal(string)" << endl; 12 | ferociousNoise = noiseParam; 13 | } 14 | 15 | WildAnimal::WildAnimal(string speciesParam, int ageParam, string noiseParam) : Animal(speciesParam, ageParam) { 16 | cout << "Hello from WildAnimal(string, int, string)" << endl; 17 | ferociousNoise = noiseParam; 18 | } 19 | 20 | // redefine more specific behavior for toString() 21 | string WildAnimal::toString() { 22 | return Animal::toString() + " that goes " + ferociousNoise; 23 | } 24 | -------------------------------------------------------------------------------- /InheritanceFun/WildAnimal.h: -------------------------------------------------------------------------------- 1 | #ifndef WILDANIMAL_H 2 | #define WILDANIMAL_H 3 | 4 | #include 5 | #include "Animal.h" 6 | 7 | using namespace std; 8 | 9 | // access specifier before the name of the base class 10 | // to specify how public attributes of the base class 11 | // are inherited 12 | // public attributes/member functions of Animal 13 | // will be public in Pet 14 | class WildAnimal : public Animal { 15 | // we put Pet specific state and behavior 16 | private: 17 | string ferociousNoise; // e.g. "roar", "grr", "hiss" 18 | public: 19 | WildAnimal(); 20 | WildAnimal(string); 21 | WildAnimal(string, int, string); 22 | // redefine more specific behavior for toString() 23 | string toString(); 24 | }; 25 | 26 | 27 | #endif 28 | -------------------------------------------------------------------------------- /InheritanceFun/a.out: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gsprint23/Cpp-Crash-Course/a864cbdf6775e16b2823143b03b04ef7cf6a8558/InheritanceFun/a.out -------------------------------------------------------------------------------- /LinkedListFun/LinkedList.cpp: -------------------------------------------------------------------------------- 1 | #include "LinkedList.h" 2 | 3 | LinkedList::LinkedList() { 4 | head = NULL; 5 | cout << sizeof(Node) << endl; 6 | } 7 | 8 | LinkedList::~LinkedList() { 9 | // TODO: free each Node's memory in the list 10 | Node * currNode = head; 11 | Node * nextNode = NULL; 12 | 13 | while (currNode != NULL) { 14 | // save the link to the next node 15 | nextNode = currNode->next; 16 | // can safely delete currNode 17 | delete currNode; 18 | currNode = nextNode; 19 | } 20 | head = NULL; // for good practice 21 | } 22 | 23 | void LinkedList::insertAtFront(int newValue) { 24 | // make a new Node 25 | Node * newNode = new Node; 26 | newNode->value = newValue; 27 | newNode->next = NULL; 28 | 29 | // 2 cases 30 | if (head == NULL) { 31 | head = newNode; 32 | } 33 | else { 34 | // list is not empty 35 | newNode->next = head; 36 | head = newNode; 37 | } 38 | } 39 | 40 | void LinkedList::displayList() { 41 | Node * currNode = head; 42 | 43 | cout << "head->"; 44 | while (currNode != NULL) { 45 | cout << currNode->value << "->"; 46 | // progress towards BC being false 47 | currNode = currNode->next; 48 | } 49 | cout << "NULL" << endl; 50 | } 51 | 52 | void LinkedList::appendNode(int newValue) { 53 | // make a new Node 54 | Node * newNode = new Node; 55 | newNode->value = newValue; 56 | newNode->next = NULL; 57 | 58 | // 2 cases 59 | if (head == NULL) { 60 | head = newNode; 61 | } 62 | else { 63 | // list is not empty 64 | // need to traverse list, stopping at the last node 65 | Node * currNode = head; 66 | while (currNode->next != NULL) { 67 | currNode = currNode->next; 68 | } 69 | // currNode points to the last node in the list 70 | currNode->next = newNode; 71 | } 72 | } 73 | 74 | void LinkedList::insertInOrder(int newValue) { 75 | // make a new Node 76 | Node * newNode = new Node; 77 | newNode->value = newValue; 78 | newNode->next = NULL; 79 | 80 | // 2 cases 81 | if (head == NULL) { 82 | head = newNode; 83 | } 84 | else { 85 | // list is not empty 86 | Node * currNode = head; 87 | Node * prevNode = NULL; 88 | 89 | while (currNode != NULL && currNode->value < newValue) { 90 | prevNode = currNode; 91 | currNode = currNode->next; 92 | } 93 | 94 | // 2 cases to check 95 | // 1) inserting at head... so we didn't advance currNode (therefore prevNode is NULL) 96 | // 2) inserting somewhere other than the head, need to the splicing 97 | if (prevNode == NULL) { 98 | head = newNode; 99 | newNode->next = currNode; 100 | } 101 | else { 102 | prevNode->next = newNode; 103 | newNode->next = currNode; 104 | } 105 | } 106 | } 107 | 108 | void LinkedList::deleteAtFront() { 109 | // check to make sure there is something to delete 110 | if (head != NULL) { 111 | Node * nodeToDelete = head; 112 | head = head->next; 113 | delete nodeToDelete; 114 | } 115 | } 116 | 117 | void LinkedList::deleteAtEnd() { 118 | if (head != NULL) { 119 | // list is not empty 120 | // need to traverse list, stopping at the last node 121 | Node * currNode = head; 122 | Node * prevNode = NULL; 123 | while (currNode->next != NULL) { 124 | prevNode = currNode; 125 | currNode = currNode->next; 126 | } 127 | if (prevNode == NULL) { 128 | // deleting at head... only one Node in the list 129 | delete head; 130 | head = NULL; // we now have an empty list 131 | } 132 | else { 133 | delete currNode; 134 | prevNode->next = NULL; 135 | } 136 | } 137 | } 138 | 139 | void LinkedList::deleteNode(int targetValue) { 140 | // check case 1 141 | if (head != NULL) { 142 | // list is not empty 143 | // need to traverse list, stopping at the last node 144 | Node * currNode = head; 145 | // check case 2... the node to delete is the first node 146 | if (head->value == targetValue) { 147 | head = head->next; 148 | delete currNode; 149 | } 150 | else { // case 3... the node to delete is not the first node, but might not even be in the list 151 | Node * prevNode = NULL; 152 | while (currNode != NULL && currNode->value != targetValue) { 153 | prevNode = currNode; 154 | currNode = currNode->next; 155 | } 156 | // check if we found targetValue 157 | if (currNode != NULL) { 158 | // did find it 159 | prevNode->next = currNode->next; 160 | delete currNode; 161 | } 162 | } 163 | } 164 | } 165 | -------------------------------------------------------------------------------- /LinkedListFun/LinkedList.h: -------------------------------------------------------------------------------- 1 | #ifndef LINKEDLIST_H 2 | #define LINKEDLIST_H 3 | 4 | #include 5 | 6 | using namespace std; 7 | 8 | // a linked list of Nodes 9 | // each Node stores a single integer value 10 | // can be expanded to store multiple values 11 | // or templated to store any value type 12 | class LinkedList { 13 | private: 14 | // self referential 15 | struct Node { 16 | int value; // data value Node stores 17 | struct Node * next; // points to next Node in list 18 | }; 19 | 20 | Node * head; // list head pointer 21 | 22 | public: 23 | LinkedList(); // DVC 24 | ~LinkedList(); // destructor 25 | 26 | // common linked list operations 27 | void insertAtFront(int); 28 | void displayList(); 29 | void appendNode(int); // insert at end 30 | void insertInOrder(int); 31 | void deleteAtFront(); 32 | void deleteAtEnd(); 33 | void deleteNode(int); 34 | }; 35 | 36 | #endif 37 | -------------------------------------------------------------------------------- /LinkedListFun/Main.cpp: -------------------------------------------------------------------------------- 1 | #include "LinkedList.h" 2 | 3 | int main() { 4 | LinkedList list; // start out empty list 5 | 6 | list.insertAtFront(12); 7 | list.insertAtFront(5); 8 | list.insertAtFront(3); 9 | 10 | list.displayList(); 11 | /*list.deleteNode(3); // delete first node 12 | list.displayList(); 13 | list.deleteNode(5); 14 | list.displayList(); 15 | list.deleteNode(12); 16 | list.displayList(); 17 | list.deleteNode(4); 18 | list.displayList();*/ 19 | 20 | 21 | /*list.deleteAtEnd(); 22 | list.displayList(); 23 | list.deleteAtEnd(); 24 | list.displayList(); 25 | list.deleteAtEnd(); 26 | list.displayList(); 27 | list.deleteAtEnd(); 28 | list.displayList();*/ 29 | 30 | /*list.deleteAtFront(); 31 | list.displayList(); 32 | list.deleteAtFront(); 33 | list.displayList(); 34 | list.deleteAtFront(); 35 | list.displayList(); 36 | list.deleteAtFront(); 37 | list.displayList(); 38 | */ 39 | 40 | //list.appendNode(15); 41 | /*list.displayList(); 42 | list.insertInOrder(7); 43 | list.displayList(); 44 | list.insertInOrder(2); 45 | list.displayList(); 46 | list.insertInOrder(15); 47 | list.displayList();*/ 48 | 49 | return 0; 50 | } 51 | -------------------------------------------------------------------------------- /LinkedListFun/a.out: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gsprint23/Cpp-Crash-Course/a864cbdf6775e16b2823143b03b04ef7cf6a8558/LinkedListFun/a.out -------------------------------------------------------------------------------- /LoopsFun/AdvancedLoopFun.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | int main() { 7 | string word = ""; 8 | // prompt the user for words until the user enter the word "stop" 9 | // we will make an infinite loop to do this, then break out of the loop 10 | 11 | while (true) { 12 | // infinite loop 13 | cout << "Enter a word (\"stop\" to exit): "; 14 | cin >> word; 15 | if (word == "stop") { 16 | break; // exit this loop 17 | } 18 | } 19 | 20 | for (int i = 0; i < 5; i++) { 21 | cout << i << "*"; 22 | for (int j = 0; j < i; j++) { 23 | cout << j << " "; 24 | } 25 | cout << endl; 26 | } 27 | cout << endl; 28 | 29 | return 0; 30 | } 31 | -------------------------------------------------------------------------------- /LoopsFun/AssignmentOperatorFun.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | int main() { 6 | int x = 2; 7 | int i = 0, j = 0, k = 0; 8 | 9 | cout << x << endl; 10 | //x = x + 5; 11 | x += 5; 12 | cout << x << endl; 13 | 14 | // task: try out the shorthand assignment operators 15 | // -= *= /= %= 16 | 17 | cout << i << " " << j << " " << k << endl; 18 | i = 2; 19 | cout << i << " " << j << " " << k << endl; 20 | j = 3 + i++; 21 | cout << i << " " << j << " " << k << endl; 22 | k = 3 + ++i; 23 | cout << i << " " << j << " " << k << endl; 24 | i *= ++k + j--; // i = i * (++k + j--); 25 | cout << i << " " << j << " " << k << endl; 26 | i /= k-- + ++j; // i = i / (k-- + ++j); 27 | cout << i << " " << j << " " << k << endl; 28 | 29 | 30 | 31 | return 0; 32 | } 33 | -------------------------------------------------------------------------------- /LoopsFun/DoWhileLoopFun.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | int main() { 6 | // input validation loop 7 | // we want to prompt the user for a positive number 8 | // we want to ensure they enter a positive number 9 | // reprompting until they enter a positive number 10 | 11 | int num = 0, i = 0; 12 | bool receivedPositiveNumber = false; 13 | 14 | do { 15 | cout << "Please enter a positive integer (> 0): "; 16 | cin >> num; 17 | 18 | if (num > 0) { 19 | cout << "Great thanks!" << endl; 20 | // progress 21 | receivedPositiveNumber = true; 22 | } 23 | else { // num <= 0 24 | cout << num << " is not > 0. Please try again." << endl; 25 | } 26 | 27 | } while (!receivedPositiveNumber); 28 | // to get here, we have to have a positive number in num 29 | 30 | // task: re-write the above input validation loop without using a do-while 31 | receivedPositiveNumber = false; 32 | while (!receivedPositiveNumber) { 33 | cout << "Please enter a positive integer (> 0): "; 34 | cin >> num; 35 | 36 | if (num > 0) { 37 | cout << "Great thanks!" << endl; 38 | // progress 39 | receivedPositiveNumber = true; 40 | } 41 | else { // num <= 0 42 | cout << num << " is not > 0. Please try again." << endl; 43 | } 44 | } 45 | 46 | // task: re-write our print stars to use a do while loop 47 | num = 5; 48 | do { 49 | cout << "*"; 50 | i++; 51 | } while (i < num); 52 | cout << endl; 53 | 54 | return 0; 55 | } 56 | -------------------------------------------------------------------------------- /LoopsFun/ForLoopFun.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | int main() { 6 | int i; 7 | int numStars = 5; 8 | 9 | for (i = 0; i < numStars; i++) { 10 | cout << "*"; 11 | } 12 | cout << endl; 13 | 14 | // task: first 20 even numbers with for loop 15 | for (i = 2; i <= 40; i += 2) { 16 | cout << i << " "; 17 | } 18 | cout << endl; 19 | 20 | for (i = 2; i <= 40; i++) { 21 | if (i % 2 == 0) 22 | cout << i << " "; 23 | } 24 | cout << endl; 25 | 26 | for (i = 1; i <= 20; i++) { 27 | cout << (i * 2) << " "; 28 | } 29 | cout << endl; 30 | 31 | return 0; 32 | } 33 | -------------------------------------------------------------------------------- /LoopsFun/GuessMyNumberFun4.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | int main() { 6 | // let's fix our secret number to be [1, 10] 7 | int secretNum = 4; // this is the number the user is trying to guess 8 | int userGuess = 0; // this is the users guess 9 | bool guessedCorrectly = false; // flag variable 10 | 11 | while (!guessedCorrectly) { 12 | cout << "Welcome to the great guess my number game! Guess an integer in [1, 10]: "; 13 | cin >> userGuess; 14 | 15 | //cout << "You entered " << userGuess << endl; 16 | // task: using an if statement, tell the user if they guessed the number correctly or not 17 | // alternatives (BCs) are tested from top to bottom 18 | // as soon as one evaluates to true, that body is executed and no other BCs are tested 19 | // like skipping to the next executable statement after the multiple alternative if statement 20 | // each body is mutually exclusive 21 | // you can have as many else ifs as you want 22 | // only one if and it has to be first 23 | // only one else, it is optional, has to be the last body, at the end of the multiple alternative if statement 24 | 25 | if (userGuess == secretNum) { // BC1 26 | cout << "You guessed it! Nice work!" << endl; 27 | guessedCorrectly = true; 28 | } 29 | else if (userGuess < secretNum) { // BC2 userGuess != secretNum (complement of BC1) 30 | cout << "You are too low" << endl; 31 | } 32 | else { // (userGuess != secretNum) && (userGuess >= secretNum) 33 | cout << "You are too high" << endl; 34 | } 35 | } 36 | 37 | // here 38 | return 0; 39 | } 40 | -------------------------------------------------------------------------------- /LoopsFun/GuessMyNumberFun5.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | int main() { 8 | // let's fix our secret number to be [1, 10] 9 | int secretNum = 0; // this is the number the user is trying to guess 10 | int userGuess = 0; // this is the users guess 11 | bool guessedCorrectly = false; // flag variable 12 | 13 | // only seed the random number generator one time 14 | srand(time(0)); // always right after variable declarations in main() 15 | secretNum = rand() % 10 + 1; 16 | 17 | while (!guessedCorrectly) { 18 | cout << "Welcome to the great guess my number game! Guess an integer in [1, 10]: "; 19 | cin >> userGuess; 20 | 21 | //cout << "You entered " << userGuess << endl; 22 | // task: using an if statement, tell the user if they guessed the number correctly or not 23 | // alternatives (BCs) are tested from top to bottom 24 | // as soon as one evaluates to true, that body is executed and no other BCs are tested 25 | // like skipping to the next executable statement after the multiple alternative if statement 26 | // each body is mutually exclusive 27 | // you can have as many else ifs as you want 28 | // only one if and it has to be first 29 | // only one else, it is optional, has to be the last body, at the end of the multiple alternative if statement 30 | 31 | if (userGuess == secretNum) { // BC1 32 | cout << "You guessed it! Nice work!" << endl; 33 | guessedCorrectly = true; 34 | } 35 | else if (userGuess < secretNum) { // BC2 userGuess != secretNum (complement of BC1) 36 | cout << "You are too low" << endl; 37 | } 38 | else { // (userGuess != secretNum) && (userGuess >= secretNum) 39 | cout << "You are too high" << endl; 40 | } 41 | } 42 | 43 | // here 44 | return 0; 45 | } 46 | -------------------------------------------------------------------------------- /LoopsFun/GuessMyNumberFun6.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | int main() { 8 | // let's fix our secret number to be [1, 10] 9 | int secretNum = 0; // this is the number the user is trying to guess 10 | int userGuess = 0; // this is the users guess 11 | bool guessedCorrectly = false; // flag variable 12 | char userChoice = 'y'; 13 | 14 | // only seed the random number generator one time 15 | srand(time(0)); // always right after variable declarations in main() 16 | 17 | do { 18 | secretNum = rand() % 10 + 1; 19 | guessedCorrectly = false; 20 | while (!guessedCorrectly) { 21 | cout << "Welcome to the great guess my number game! Guess an integer in [1, 10]: "; 22 | cin >> userGuess; 23 | 24 | if (userGuess == secretNum) { // BC1 25 | cout << "You guessed it! Nice work!" << endl; 26 | guessedCorrectly = true; 27 | } 28 | else if (userGuess < secretNum) { // BC2 userGuess != secretNum (complement of BC1) 29 | cout << "You are too low" << endl; 30 | } 31 | else { // (userGuess != secretNum) && (userGuess >= secretNum) 32 | cout << "You are too high" << endl; 33 | } 34 | } 35 | // the game is over, ask if they want to play again 36 | cout << "Do you want to play again (y or n): "; 37 | cin >> userChoice; 38 | 39 | } while(userChoice != 'n'); 40 | 41 | // here 42 | return 0; 43 | } 44 | -------------------------------------------------------------------------------- /LoopsFun/RandomNumberFun.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | int main() { 8 | int randNum = 0; 9 | int i = 0; 10 | 11 | //cout << time(0) << endl; 12 | srand(time(0)); 13 | 14 | randNum = rand() % 10 + 1; 15 | cout << randNum << endl; 16 | 17 | randNum = rand() % 10 + 1; 18 | cout << randNum << endl; 19 | 20 | randNum = rand() % 10 + 1; 21 | cout << randNum << endl; 22 | 23 | // task: assign to randNum a value in the range [7, 10] 24 | //randNum = rand() % 4 + 7; 25 | 26 | /*cout << rand() << endl; 27 | cout << rand() << endl; 28 | cout << rand() << endl; 29 | cout << rand() << endl; 30 | cout << rand() << endl;*/ 31 | 32 | // task: print out 20 6-sided die throws 33 | while (i < 20) { 34 | randNum = rand() % 6 + 1; 35 | cout << "Roll #" << (i + 1) << ": " << randNum << endl; 36 | i += 1; 37 | } 38 | 39 | // task: start the roll numbers at 1 40 | 41 | return 0; 42 | } 43 | -------------------------------------------------------------------------------- /LoopsFun/TransactionFun.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | int main() { 6 | // write a program that prompts the user for 5 credit card transaction amounts 7 | // tell the user the total spent on the credit card 8 | // and the average spent per transaction 9 | 10 | // task: solve this! 11 | double transaction = 0.0; 12 | double totalTransaction = 0.0; 13 | double avgTransaction = 0.0; 14 | const int NUM_TRANSACTIONS = 5; 15 | 16 | cout << "Please enter a transaction amount $"; 17 | cin >> transaction; 18 | totalTransaction = totalTransaction + transaction; 19 | 20 | cout << "Please enter a transaction amount $"; 21 | cin >> transaction; 22 | totalTransaction = totalTransaction + transaction; 23 | 24 | cout << "Please enter a transaction amount $"; 25 | cin >> transaction; 26 | totalTransaction = totalTransaction + transaction; 27 | 28 | cout << "Please enter a transaction amount $"; 29 | cin >> transaction; 30 | totalTransaction = totalTransaction + transaction; 31 | 32 | cout << "Please enter a transaction amount $"; 33 | cin >> transaction; 34 | totalTransaction = totalTransaction + transaction; 35 | 36 | 37 | avgTransaction = totalTransaction / NUM_TRANSACTIONS; 38 | cout << "Total spent: $" << totalTransaction << endl << "Average transaction: $" << avgTransaction << endl; 39 | 40 | return 0; 41 | } 42 | -------------------------------------------------------------------------------- /LoopsFun/TransactionFun2.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | int main() { 6 | // write a program that prompts the user for 5 credit card transaction amounts 7 | // tell the user the total spent on the credit card 8 | // and the average spent per transaction 9 | 10 | // task: solve this! 11 | double transaction = 0.0; 12 | double totalTransaction = 0.0; 13 | double avgTransaction = 0.0; 14 | //const int NUM_TRANSACTIONS = 5; 15 | int numTransactions = 0; 16 | int i = 0; 17 | 18 | cout << "How many transactions do you want to enter: "; 19 | cin >> numTransactions; 20 | 21 | while (i < numTransactions) { 22 | cout << "Please enter a transaction amount $"; 23 | cin >> transaction; 24 | totalTransaction = totalTransaction + transaction; 25 | i += 1; 26 | } 27 | 28 | avgTransaction = totalTransaction / numTransactions; 29 | cout << "Total spent: $" << totalTransaction << endl << "Average transaction: $" << avgTransaction << endl; 30 | 31 | return 0; 32 | } 33 | -------------------------------------------------------------------------------- /LoopsFun/WhileLoopFun.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | int main() { 6 | int numStars = 5; 7 | int i = numStars; 8 | 9 | /*while (i < numStars) { 10 | cout << "*"; 11 | i++; 12 | } 13 | cout << endl;*/ 14 | 15 | while (i >= 1) { 16 | cout << "*"; 17 | i--; 18 | } 19 | cout << endl; 20 | 21 | 22 | return 0; 23 | } 24 | -------------------------------------------------------------------------------- /LoopsFun/WhileLoopFun2.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | int main() { 6 | int numStars = 5; 7 | int i = numStars; 8 | int choice = 0; 9 | bool keepPlaying = true; 10 | 11 | i = 1; 12 | while (i <= numStars) { 13 | cout << "*"; 14 | i++; 15 | } 16 | cout << endl; 17 | 18 | 19 | i = numStars; 20 | while (i >= 1) { 21 | cout << "*"; 22 | i--; 23 | } 24 | cout << endl; 25 | 26 | // first 20 even numbers 27 | i = 2; 28 | while (i <= 40) { 29 | cout << i << " "; 30 | i += 2; 31 | } 32 | cout << endl; 33 | 34 | i = 2; 35 | while (i <= 40) { 36 | if (i % 2 == 0) 37 | cout << i << " "; 38 | 39 | i += 1; 40 | } 41 | cout << endl; 42 | 43 | i = 1; 44 | while (i <= 20) { 45 | cout << (i * 2) << " "; 46 | i++; 47 | } 48 | cout << endl; 49 | 50 | while (keepPlaying) { 51 | cout << "\nWelcome to my game!" << endl; 52 | cout << "Please choose from the following: " << endl; 53 | cout << "1. View the game rules" << endl; 54 | cout << "2. Play the game" << endl; 55 | cout << "3. View the high score" << endl; 56 | cout << "4. Quit" << endl; 57 | cout << "Choice: "; 58 | cin >> choice; 59 | 60 | if (choice == 1) { 61 | cout << "Add code later to show the game rules..." << endl; 62 | } 63 | else if (choice == 2) { 64 | cout << "Add code later to play the game..." << endl; 65 | } 66 | else if (choice == 3) { 67 | cout << "Add code later to show the high score..." << endl; 68 | } 69 | else if (choice == 4) { 70 | cout << "Thanks for playing, see you later..." << endl; 71 | keepPlaying = false; 72 | } 73 | else { 74 | cout << "Unrecognized menu option. Please try again." << endl; 75 | } 76 | } 77 | 78 | 79 | return 0; 80 | } 81 | -------------------------------------------------------------------------------- /MoreFileIOFun/Main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | int main() { 7 | // ifstream input file 8 | // ofstream output file 9 | // fstream open files in more modes!! 10 | // ios::in reading 11 | // ios::out writing 12 | // ios::app appending 13 | // ios::ate add at end of file 14 | // ios::binary 15 | 16 | string line; 17 | 18 | // open a file for writing 19 | fstream file; 20 | file.open("words.txt", ios::out); 21 | file << "hello" << endl; 22 | // wrote 6 bytes to words.txt 23 | long position = file.tellp(); // tellp is for putting (outfiles, write position) 24 | // tellg is for getting (infiles, read position) 25 | cout << "position: " << position << endl; 26 | file.close(); 27 | 28 | file.open("words.txt", ios::in | ios::out); // both reading and writing 29 | while (!file.eof()) { 30 | // read a line 31 | getline(file, line); 32 | if (file.good()) { 33 | cout << "Read: " << line << endl; 34 | } 35 | } 36 | // move the cursor back to the beginning of the file (without closing the file) 37 | // overwrite the hello with goodbye 38 | file.clear(); // clear the EOF bit 39 | file.seekp(0, ios::beg); // moves to beginning of the file 40 | // ios::beg beginning of file 41 | // ios::end end of the file 42 | // ios::cur current position 43 | file << "goodbye" << endl; 44 | cout << file.tellp() << endl; 45 | cout << file.tellg() << endl; 46 | 47 | file.close(); 48 | 49 | return 0; 50 | } 51 | -------------------------------------------------------------------------------- /MoreFileIOFun/a.out: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gsprint23/Cpp-Crash-Course/a864cbdf6775e16b2823143b03b04ef7cf6a8558/MoreFileIOFun/a.out -------------------------------------------------------------------------------- /MoreFileIOFun/words.txt: -------------------------------------------------------------------------------- 1 | goodbye 2 | -------------------------------------------------------------------------------- /OOPFun/Book.cpp: -------------------------------------------------------------------------------- 1 | #include "Book.h" 2 | 3 | // DVC 4 | Book::Book() { 5 | // initialize attributes to logical zero values 6 | title = "DEFAULT TITLE"; 7 | author = "DEFAULT AUTHOR"; 8 | numPages = new int; 9 | *numPages = 0; 10 | } 11 | 12 | // EVC 13 | Book::Book(string t, string a, int n) { 14 | title = t; 15 | author = a; 16 | numPages = new int; 17 | *numPages = n; 18 | } 19 | 20 | // copy constructor 21 | Book::Book(const Book& otherBook) { 22 | cout << "Hello from copy constructor" << endl; 23 | title = otherBook.title; 24 | author = otherBook.author; 25 | // need to allocate this new book's own memory for numPages 26 | numPages = new int; 27 | *numPages = *(otherBook.numPages); 28 | } 29 | 30 | Book::~Book() { 31 | cout << "Hello from Book destructor... title: " << title << endl; 32 | // should release resources like dyn alloc mem 33 | delete numPages; 34 | } 35 | 36 | // :: scope resolution operator 37 | // increases the scope of getTitle to include the Book class 38 | string Book::getTitle() { 39 | return title; 40 | } 41 | 42 | string Book::getAuthor() { 43 | return author; 44 | } 45 | int Book::getNumPages(){ 46 | return *numPages; 47 | } 48 | 49 | void Book::setTitle(string newTitle) { 50 | title = newTitle; 51 | } 52 | 53 | void Book::setAuthor(string newAuthor) { 54 | author = newAuthor; 55 | } 56 | 57 | void Book::setNumPages(int newNumPages) { 58 | *numPages = newNumPages; 59 | } 60 | 61 | void Book::display() { 62 | // need an object of type Book in order to invoke a member function 63 | // inside that member function body, we can access the state of the invoking object 64 | // what ever object is before the .display() 65 | cout << "Title: " << title << endl; 66 | cout << "Author: " << author << endl; 67 | cout << "Number of pages: " << *numPages << endl; 68 | } 69 | 70 | const Book & Book::operator=(const Book & right) { 71 | // hp3 = hp2; 72 | // hp2 is the right side of the = 73 | // hp3 is the left side of the = 74 | // hp2 is the parameter 75 | // hp3 is the inovking object 76 | // this is a reserved word that is a pointer to the invoking object 77 | // this is passed as a hidden argument to all non-static member function 78 | // good practice to check that we aren't doing self assignment 79 | // hp3 = hp3 80 | if (this != &right) { 81 | title = right.title; 82 | author = right.author; 83 | *numPages = *(right.numPages); // copy integers, not addresses 84 | // copy the indirect values, not the pointers (no addresses are copied)! 85 | } 86 | // think about this 87 | // hp3 = hp2 = hp1; 88 | return *this; 89 | } 90 | 91 | -------------------------------------------------------------------------------- /OOPFun/Book.h: -------------------------------------------------------------------------------- 1 | #ifndef BOOK_H 2 | #define BOOK_H 3 | 4 | #include 5 | 6 | using namespace std; 7 | 8 | // OOP object oriented programming 9 | // object is an instance of a class 10 | // class is a collection of STATE and BEHAVIOR that completely describes something 11 | // state: attributes (AKA member variables) 12 | // behavior: member functions (AKA methods) that operate on the state of an object (attributes) 13 | // classes are like struct definitions, with the addition of a few things... 14 | 15 | // class definition should go in a header file of the same name 16 | class Book { 17 | // access modifiers (specifiers) that define the visibility for a member 18 | // public and private 19 | // by default all members of a class are private 20 | // private only accessible within this class 21 | // public accessible anywhere 22 | private: 23 | // declare members of the Book class 24 | // attributes 25 | string title; 26 | string author; 27 | int * numPages; 28 | public: 29 | // a constructor is a special member function that creates objects by initializing their attribute values 30 | // c++ always has a default constructor that is automatically called everytime a Book object is made... this default constructor does nothing 31 | // we want to override the default constructor in order to properly initialize Books 32 | // constructors have no return type 33 | // we can overload constructors 34 | // 0 or more parameters 35 | // default value constructor (DVC) has no arguments 36 | Book(); // DVC prototype 37 | // explicit value constructor (EVC) accpets arguments to intialize attribute values to 38 | Book(string, string, int); // EVC prototype 39 | // same rules for function overloading apply to constructor overloading 40 | // a copy constructor is a constructor that is called when a new object is initialized with another object's data 41 | // called in one of two cases 42 | // 1) Book b(otherBook); // where otherBook is a Book object 43 | // 2) Book b = otherBook; // where otherBook is a Book object 44 | // NOT called with 45 | // b = otherBook; 46 | // because this is not object creation since b already exists, this is memberwise copy assignment 47 | Book(const Book&); // copy constructor 48 | 49 | // destructor is a special member function that is called automatically when an object is about to be destroyed (AKA destructed AKA deallocated) 50 | // what should a destructor do? 51 | // free/release any resources (e.g. close files) 52 | // free/release any dynamically allocated memory 53 | // no return type, no arguments 54 | // there is only one destructor 55 | ~Book(); // destructor prototype 56 | 57 | 58 | // getters (AKA accessors) 59 | // member functions that get the values of private attributes 60 | string getTitle(); 61 | string getAuthor(); 62 | int getNumPages(); 63 | // setters (AKA mutators) 64 | // that set values of private attributes 65 | void setTitle(string); 66 | void setAuthor(string); 67 | void setNumPages(int); 68 | 69 | void display(); 70 | 71 | // operator overloading 72 | const Book & operator=(const Book &); 73 | 74 | }; 75 | 76 | #endif 77 | -------------------------------------------------------------------------------- /OOPFun/Main.cpp: -------------------------------------------------------------------------------- 1 | #include "Book.h" 2 | 3 | int main() { 4 | // make Book object 5 | // actually memory is allocated when an object is created 6 | Book hp1; // invokes DVC 7 | hp1.setTitle("Sorcerer's Stone"); 8 | hp1.setAuthor("JK Rowling"); 9 | hp1.setNumPages(202); 10 | 11 | cout << hp1.getTitle() << endl; 12 | 13 | hp1.display(); // hp1 is an "invoking" object... so in display() it is hp1's title, author, numPages that are accessed 14 | // this is the syntax for calling a member function 15 | // .() 16 | 17 | Book hp2; // invokes DVC 18 | hp2.setTitle("Chamber of Secrets"); 19 | hp2.setAuthor("JKR"); 20 | hp2.setNumPages(300); 21 | hp2.display(); 22 | 23 | // other member functions 24 | // myString.size() myString.at(0) 25 | 26 | // we can have pointers to objects 27 | Book hp3 = hp2; // copy of hp2... invokes the copy constructor if one exists, if one doesn't exist then performs memberwise copy assignment 28 | hp3.setTitle("Prisoner of Azkaban"); 29 | Book * bookPtr = &hp3; 30 | // can use -> 31 | bookPtr->display(); 32 | // PROBLEM when numPages is dyn allocated 33 | // why? the mem address of numPages in hp2 is copied to numPages in hp3 34 | // hp3 is freed before hp2 35 | // so we get a double free detected when we destruct hp2 and call delete numPages 36 | // SOLUTION? define a copy constructor 37 | // where we allocate new member for numPages in hp3 38 | 39 | Book hp4("Goblet of Fire", "JKR", 450); // invokes EVC 40 | hp4.display(); 41 | 42 | // 2 distinct implementations of "dyn mem alloc and objects" 43 | // 1) dyn allocate a Book object 44 | Book * hp5Ptr = new Book("Order of the Phoenix", "JKR", 600); // EVC 45 | hp5Ptr->display(); 46 | delete hp5Ptr; 47 | // 2) dyn allocate attributes of a Book object 48 | 49 | // rule of three 50 | // if you define any of the following, then you should define all three 51 | // 1) destructor 52 | // 2) copy constructor 53 | // Book hp3 = hp2; 54 | // 3) memberwise copy assignment operator (operator overloading) 55 | hp3 = hp2; 56 | 57 | return 0; 58 | } 59 | -------------------------------------------------------------------------------- /OOPFun/a.out: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gsprint23/Cpp-Crash-Course/a864cbdf6775e16b2823143b03b04ef7cf6a8558/OOPFun/a.out -------------------------------------------------------------------------------- /PointerFun/CStringMain.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | 7 | int main() { 8 | // pointer: a variable that stores as its contents the memory address of another variable 9 | // an array stores the memory address of the first element of the array 10 | 11 | // generally what is a string? 12 | // a string is a sequence of characters 13 | // "winter" 14 | // C++ we use the string type 15 | string season = "winter"; 16 | cout << season << endl; 17 | // C we use C-strings 18 | // C-string is a null terminated char array 19 | // \0 is the null terminator 20 | // 0 1 2 3 4 5 6 21 | // w i n t e r \0 22 | // size + 1 for the \0 23 | char season2[] = {'w', 'i', 'n', 't', 'e', 'r', '\0'}; // C-string is mutable 24 | // can be changed 25 | cout << season2 << endl; 26 | season2[0] = 'W'; 27 | cout << season2 << endl; 28 | const char * season3 = "winter"; // immutable 29 | cout << season3 << endl; 30 | 31 | char season4[20]; 32 | // use functions for C-string in cstring 33 | strcpy(season4, season2); 34 | cout << season4 << endl; 35 | 36 | // "winter" < "fall" 37 | cout << strcmp(season3, "fall") << endl; 38 | // < 0 means arg1 is before arg2 39 | // > 0 arg2 is before arg1 40 | // == 0 arg1 is the same as arg2 41 | 42 | cout << strlen(season2) << endl; 43 | cout << sizeof(season2) << endl; 44 | 45 | return 0; 46 | } 47 | 48 | -------------------------------------------------------------------------------- /PointerFun/CommandLineArgsMain.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | void printArray(char * arr, int size); 7 | 8 | // argc stores the count of how many args 9 | // plus one for the name program 10 | // argv is an array of C-strings 11 | // each argument is stored in argv 12 | // as a C-string 13 | int main(int argc, char * argv[]) { 14 | // pointer: a variable that stores as its contents the memory address of another variable 15 | // an array stores the memory address of the first element of the array 16 | 17 | // string: is a sequence of characters 18 | // in C++ we use the string type 19 | string name = "gina"; // C++ string 20 | // C-string: an array of chars that is null terminated 21 | // the last character in the array is \0 22 | // store "hello" in a C-string 23 | // number of chars + 1 (for \0) is the size of your char array to store this C-string 24 | 25 | // reading the command line args 26 | cout << "argc: " << argc << endl; 27 | cout << "argv[0]: " << argv[0] << endl; 28 | int i; 29 | for (i = 0; i < argc; i++) { 30 | cout << "i: " << i << endl; 31 | cout << "argv[i]: " << argv[i] << endl; 32 | printArray(argv[i], strlen(argv[i])); 33 | } 34 | 35 | return 0; 36 | } 37 | 38 | void printArray(char * arr, int size) { 39 | int i; 40 | for (i = 0; i < size; i++) { 41 | cout << *(arr + i) << " "; 42 | } 43 | cout << endl; 44 | } 45 | 46 | -------------------------------------------------------------------------------- /PointerFun/DebuggingFun.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | int * doBadThings() { 6 | int localVar = 5; // resides in the stack 7 | // NEVER want to return the mem addr of a local variable 8 | // when function exits, local vars in stack are deallocated 9 | return &localVar; 10 | } 11 | 12 | int main() { 13 | int * intPtr = new int[10]; 14 | *intPtr = 7; 15 | cout << *intPtr << endl; 16 | 17 | // done with what intPtr points to... 18 | // forget to free it!! 19 | delete [] intPtr; 20 | intPtr = NULL; 21 | 22 | int * badPtr = NULL; 23 | badPtr = doBadThings(); 24 | cout << *badPtr << endl; 25 | 26 | return 0; 27 | } 28 | -------------------------------------------------------------------------------- /PointerFun/DynamicMemoryMain.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | void printArray(int * arr, int size); 6 | int * createRandomArray(int size); 7 | 8 | int main() { 9 | // pointer: a variable that stores as its contents the memory address of another variable 10 | // an array stores the memory address of the first element of the array 11 | 12 | // local variables are allocated in a region of memory called the "stack" 13 | // when a function exits, the stack area that was used by the function is deallocated 14 | // NEVER return the memory address of a local variable 15 | // goal of dynamic memory is to return the memory address of memory in the "heap" 16 | // "heap" area is not deallocated when a function exits 17 | // deallocated when you (the programmer) deallocated it (freeing memory) 18 | 19 | // we want a function to allocate memory for an array of random numbers 20 | // we use the new and delete keywords to dynamically allocate memory 21 | // we will use these in the function to allocate memory on the heap 22 | int * randArr = NULL; 23 | randArr = createRandomArray(10); // size 24 | printArray(randArr, 10); 25 | // note: we need to free AKA deallocate 26 | // randArr when we are done with it 27 | // memory leak unless we free randArr's memory on the heap 28 | delete [] randArr; 29 | // good practice to set the pointer to NULL or to nullptr 30 | randArr = NULL; 31 | 32 | return 0; 33 | } 34 | 35 | int * createRandomArray(int size) { 36 | int i; 37 | int * arr = new int[size]; // on heap 38 | for (i = 0; i < size; i++) { 39 | *(arr + i) = rand() % size; 40 | } 41 | return arr; // note: it is the calling 42 | // code's responsibility to free this memory 43 | } 44 | 45 | void printArray(int * arr, int size) { 46 | int i; 47 | for (i = 0; i < size; i++) { 48 | cout << *(arr + i) << " "; 49 | } 50 | cout << endl; 51 | } 52 | 53 | -------------------------------------------------------------------------------- /PointerFun/Main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | void divide(int num, int den, int * res, int * rem); 6 | 7 | int main() { 8 | // pointer: a variable that stores as its contents the memory address of another variable 9 | 10 | // example 11 | /* 12 | NAME TYPE MEM ADDR CONTENTS 13 | x int 0xd48c 5->7->10 14 | xPtr int * 0x2004 NULL->0xd48c 15 | */ 16 | 17 | int x = 5; // "x is assigned 5" 18 | // declare a pointer to an int 19 | int * xPtr = NULL; // NULL is like 20 | // initializing the pointer to 0 21 | // it's invalid 22 | // "the pointer to int xPtr is assigned null" 23 | 24 | // 2 ways to modify the contents of x 25 | // 1) directly via x 26 | x = 7; 27 | // 2) indirectly via xPtr 28 | // we want xPtr to point to x 29 | // so we have xPtr store the 30 | // mem addr of x 31 | xPtr = &x; // & address of operator 32 | // xPtr is assigned the address of x" 33 | // follow the xPtr to x 34 | *xPtr = 10; 35 | // "the contents of what xPtr points to 36 | // is assigned 10 37 | // "follow the pointer and assign 10" 38 | // * here is the unary indirection operator 39 | // and it "dereferences" a pointer 40 | cout << "x: " << x << endl; 41 | cout << "*xPtr: " << *xPtr << endl; 42 | cout << "&x: " << &x << endl; 43 | cout << "xPtr: " << xPtr << endl; 44 | 45 | // char * 46 | // double * 47 | // string * 48 | 49 | // 3 different uses of the * in C/C++ 50 | // 1) multiplication operator 51 | // e.g. x * 2 52 | // 2) pointer type 53 | // e.g. int * xPtr 54 | // 3) unary indirection operator 55 | // e.g. *xPtr = 5; 56 | 57 | // 2 different uses of the & in C/C++ 58 | // 1) declaration of a reference variable 59 | // int & xRef = x; // makes an alias 60 | // 2) address of operator 61 | // e.g. char * charPtr = &myChar; 62 | 63 | // OUTPUT PARAMETERS 64 | // with the return statment, a function 65 | // can return a value 66 | // output parameter is a parameter that 67 | // "returns a value" from the function 68 | // 2 ways to do this 69 | // 1) via a pass by reference variable 70 | // int & result 71 | // **2) via a pointer variable 72 | 73 | // example 74 | // a function called divide() 75 | // accepts two ints, and returns 76 | // their result of division and remainder 77 | int result, remainder; 78 | // what is in scope of main()? 79 | // int result CONTENTS ?->1 ADDR 0x2000 80 | // int remainder CONTENTS ?->2 ADDR 0x3000 81 | divide(13, 11, &result, &remainder); 82 | cout << "result: " << result << endl; 83 | cout << "remainder: " << remainder << endl; 84 | 85 | return 0; 86 | } 87 | 88 | void divide(int num, int den, int * res, int * rem) { 89 | *res = num / den; // int div 90 | // "the contents of what res points to is assigned num divided by den" 91 | *rem = num % den; // mod 92 | // "the contents of what rem points to is assigned num mod den" 93 | 94 | // what is in scope of divide()? 95 | // int num CONTENTS 13 96 | // int den CONTENTS 11 97 | // int * res CONTENTS 0x2000 98 | // int * rem CONTENTS 0x3000 99 | 100 | } 101 | -------------------------------------------------------------------------------- /PointerFun/PointerArithmeticMain.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | void printArray(int * arr, int size); 6 | 7 | int main() { 8 | // pointer: a variable that stores as its contents the memory address of another variable 9 | // an array stores the memory address of the first element of the array 10 | 11 | int nums[] = {5, 2, 8, 6}; 12 | // 16 contiguously allocated bytes 13 | // to stores 4 ints 14 | int size = 4; 15 | 16 | cout << &(nums[0]) << endl; 17 | cout << &(nums[1]) << endl; 18 | cout << &(nums[2]) << endl; 19 | cout << &(nums[3]) << endl; 20 | printArray(nums, size); 21 | 22 | return 0; 23 | } 24 | 25 | void printArray(int * arr, int size) { 26 | int i; 27 | for (i = 0; i < size; i++) { 28 | // cout << arr[i] << " "; // array notation 29 | cout << *(arr + i) << " "; // pointer notation 30 | // values of i... 31 | // i = 0, 1, 2, 3 32 | // ints are 4 bytes 33 | // the offset added to arr 34 | // is the size of the memory cell 35 | // times the offset to get the total 36 | // bytes 37 | } 38 | cout << endl; 39 | } 40 | 41 | -------------------------------------------------------------------------------- /QueueFun/LinkedList.cpp: -------------------------------------------------------------------------------- 1 | #include "LinkedList.h" 2 | 3 | LinkedList::LinkedList() { 4 | head = NULL; 5 | tail = NULL; 6 | cout << sizeof(Node) << endl; 7 | } 8 | 9 | LinkedList::~LinkedList() { 10 | destroyList(); 11 | } 12 | 13 | void LinkedList::destroyList() { 14 | // TODO: free each Node's memory in the list 15 | Node * currNode = head; 16 | Node * nextNode = NULL; 17 | 18 | while (currNode != NULL) { 19 | // save the link to the next node 20 | nextNode = currNode->next; 21 | // can safely delete currNode 22 | delete currNode; 23 | currNode = nextNode; 24 | } 25 | head = NULL; // for good practice 26 | tail = NULL; 27 | } 28 | 29 | void LinkedList::displayList() { 30 | Node * currNode = head; 31 | 32 | cout << "head->"; 33 | while (currNode != NULL) { 34 | cout << currNode->value << "->"; 35 | // progress towards BC being false 36 | currNode = currNode->next; 37 | } 38 | cout << "NULL" << endl; 39 | if (tail != NULL) { 40 | cout << "tail->" << tail->value << endl; 41 | } 42 | else { 43 | cout << "tail->NULL" << endl; 44 | } 45 | } 46 | 47 | void LinkedList::appendNode(int newValue) { 48 | // make a new Node 49 | Node * newNode = new Node; 50 | newNode->value = newValue; 51 | newNode->next = NULL; 52 | 53 | // 2 cases 54 | if (head == NULL) { 55 | head = newNode; 56 | tail = newNode; 57 | } 58 | else { 59 | // list is not empty 60 | tail->next = newNode; 61 | tail = newNode; 62 | } 63 | } 64 | 65 | 66 | int LinkedList::deleteAtFront() { 67 | // check to make sure there is something to delete 68 | int value = -1; 69 | if (head != NULL) { 70 | Node * nodeToDelete = head; 71 | head = head->next; 72 | value = nodeToDelete->value; 73 | delete nodeToDelete; 74 | if (head == NULL) { 75 | tail = NULL; 76 | } 77 | } 78 | return value; 79 | } 80 | 81 | void LinkedList::insertInOrder(int newValue) { 82 | // make a new Node 83 | Node * newNode = new Node; 84 | newNode->value = newValue; 85 | newNode->next = NULL; 86 | 87 | // 2 cases 88 | if (head == NULL) { 89 | head = newNode; 90 | tail = newNode; 91 | } 92 | else { 93 | // list is not empty 94 | Node * currNode = head; 95 | Node * prevNode = NULL; 96 | 97 | while (currNode != NULL && currNode->value > newValue) { 98 | prevNode = currNode; 99 | currNode = currNode->next; 100 | } 101 | 102 | // 2 cases to check 103 | // 1) inserting at head... so we didn't advance currNode (therefore prevNode is NULL) 104 | // 2) inserting somewhere other than the head, need to the splicing 105 | if (prevNode == NULL) { 106 | head = newNode; 107 | newNode->next = currNode; 108 | } 109 | else { 110 | prevNode->next = newNode; 111 | newNode->next = currNode; 112 | if (newNode->next == NULL) { 113 | // new last node in the list 114 | tail = newNode; 115 | } 116 | } 117 | } 118 | } 119 | -------------------------------------------------------------------------------- /QueueFun/LinkedList.h: -------------------------------------------------------------------------------- 1 | #ifndef LINKEDLIST_H 2 | #define LINKEDLIST_H 3 | 4 | #include 5 | 6 | using namespace std; 7 | 8 | // a linked list of Nodes 9 | // each Node stores a single integer value 10 | // can be expanded to store multiple values 11 | // or templated to store any value type 12 | class LinkedList { 13 | protected: 14 | // self referential 15 | struct Node { 16 | int value; // data value Node stores 17 | struct Node * next; // points to next Node in list 18 | }; 19 | 20 | Node * head; // list head pointer 21 | Node * tail; // list tail pointer 22 | 23 | public: 24 | LinkedList(); // DVC 25 | ~LinkedList(); // destructor 26 | 27 | // common linked list operations 28 | void displayList(); 29 | void appendNode(int); // insert at end 30 | int deleteAtFront(); 31 | void destroyList(); 32 | void insertInOrder(int); 33 | }; 34 | 35 | #endif 36 | -------------------------------------------------------------------------------- /QueueFun/Main.cpp: -------------------------------------------------------------------------------- 1 | #include "LinkedList.h" 2 | #include "Queue.h" 3 | #include "PriorityQueue.h" 4 | 5 | int main() { 6 | PriorityQueue q; 7 | int value = -1; 8 | q.enqueue(6); 9 | q.enqueue(3); 10 | q.enqueue(5); 11 | q.displayList(); 12 | value = q.dequeue(); 13 | cout << "dequeued: " << value << endl; 14 | q.displayList(); 15 | q.enqueue(12); 16 | q.displayList(); 17 | 18 | cout << q.peek() << endl; 19 | cout << q.isEmpty() << endl; 20 | q.clear(); 21 | cout << q.isEmpty() << endl; 22 | q.displayList(); 23 | 24 | 25 | /*LinkedList list; // start out empty list 26 | 27 | list.appendNode(12); 28 | list.appendNode(5); 29 | list.appendNode(3); 30 | 31 | list.displayList();*/ 32 | /*list.deleteNode(3); // delete first node 33 | list.displayList(); 34 | list.deleteNode(5); 35 | list.displayList(); 36 | list.deleteNode(12); 37 | list.displayList(); 38 | list.deleteNode(4); 39 | list.displayList();*/ 40 | 41 | 42 | /*list.deleteAtEnd(); 43 | list.displayList(); 44 | list.deleteAtEnd(); 45 | list.displayList(); 46 | list.deleteAtEnd(); 47 | list.displayList(); 48 | list.deleteAtEnd(); 49 | list.displayList();*/ 50 | 51 | /*list.deleteAtFront(); 52 | list.displayList(); 53 | list.deleteAtFront(); 54 | list.displayList(); 55 | list.deleteAtFront(); 56 | list.displayList(); 57 | list.deleteAtFront(); 58 | list.displayList(); 59 | */ 60 | 61 | //list.appendNode(15); 62 | /*list.displayList(); 63 | list.insertInOrder(7); 64 | list.displayList(); 65 | list.insertInOrder(2); 66 | list.displayList(); 67 | list.insertInOrder(15); 68 | list.displayList();*/ 69 | 70 | return 0; 71 | } 72 | -------------------------------------------------------------------------------- /QueueFun/PriorityQueue.cpp: -------------------------------------------------------------------------------- 1 | #include "PriorityQueue.h" 2 | 3 | void PriorityQueue::enqueue(int newValue) { 4 | insertInOrder(newValue); 5 | } 6 | -------------------------------------------------------------------------------- /QueueFun/PriorityQueue.h: -------------------------------------------------------------------------------- 1 | #ifndef PRIORITY_QUEUE 2 | #define PRIORITY_QUEUE 3 | 4 | #include 5 | #include "Queue.h" 6 | 7 | using namespace std; 8 | 9 | class PriorityQueue : public Queue { 10 | public: 11 | void enqueue(int); 12 | }; 13 | 14 | 15 | #endif 16 | -------------------------------------------------------------------------------- /QueueFun/Queue.cpp: -------------------------------------------------------------------------------- 1 | #include "Queue.h" 2 | 3 | void Queue::enqueue(int newValue) { 4 | appendNode(newValue); 5 | } 6 | 7 | int Queue::dequeue() { 8 | return deleteAtFront(); 9 | } 10 | 11 | int Queue::peek() { 12 | if (head != NULL) { 13 | return head->value; 14 | } 15 | return -1; 16 | } 17 | 18 | void Queue::clear() { 19 | // 2 ways to implement clear() 20 | // 1) we can write a loop 21 | //while (!isEmpty()) { 22 | // dequeue(); 23 | //} 24 | // 2) we can leverage the destructor 25 | // code we alread wrote in LinkedList 26 | destroyList(); 27 | } 28 | 29 | bool Queue::isEmpty() { 30 | if (head != NULL) { 31 | return false; 32 | } 33 | return true; 34 | } 35 | 36 | int Queue::size() { 37 | // 2 ways to implement size 38 | // 1) traverse the linked list and count 39 | // the number of nodes O(N) 40 | // 2) add a count/size attribute to LinkedList class 41 | // need to keep this up to date 42 | // O(1) 43 | 44 | // 1) 45 | int count = 0; 46 | Node * currNode = head; 47 | while (currNode != NULL) { 48 | count++; 49 | currNode = currNode->next; 50 | } 51 | return count; 52 | } 53 | -------------------------------------------------------------------------------- /QueueFun/Queue.h: -------------------------------------------------------------------------------- 1 | #ifndef QUEUE_H 2 | #define QUEUE_H 3 | 4 | #include 5 | #include "LinkedList.h" 6 | 7 | using namespace std; 8 | 9 | class Queue : public LinkedList { 10 | // no queue specific attributes needed 11 | public: 12 | // common queue operations 13 | virtual void enqueue(int); 14 | int dequeue(); 15 | int peek(); 16 | void clear(); 17 | bool isEmpty(); 18 | int size(); 19 | 20 | }; 21 | 22 | #endif 23 | -------------------------------------------------------------------------------- /QueueFun/a.out: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gsprint23/Cpp-Crash-Course/a864cbdf6775e16b2823143b03b04ef7cf6a8558/QueueFun/a.out -------------------------------------------------------------------------------- /RecursionFun/LinkedList.cpp: -------------------------------------------------------------------------------- 1 | #include "LinkedList.h" 2 | 3 | LinkedList::LinkedList() { 4 | head = NULL; 5 | cout << sizeof(Node) << endl; 6 | } 7 | 8 | LinkedList::~LinkedList() { 9 | // TODO: free each Node's memory in the list 10 | Node * currNode = head; 11 | Node * nextNode = NULL; 12 | 13 | while (currNode != NULL) { 14 | // save the link to the next node 15 | nextNode = currNode->next; 16 | // can safely delete currNode 17 | delete currNode; 18 | currNode = nextNode; 19 | } 20 | head = NULL; // for good practice 21 | } 22 | 23 | void LinkedList::insertAtFront(int newValue) { 24 | // make a new Node 25 | Node * newNode = new Node; 26 | newNode->value = newValue; 27 | newNode->next = NULL; 28 | 29 | // 2 cases 30 | if (head == NULL) { 31 | head = newNode; 32 | } 33 | else { 34 | // list is not empty 35 | newNode->next = head; 36 | head = newNode; 37 | } 38 | } 39 | 40 | void LinkedList::displayList() { 41 | Node * currNode = head; 42 | 43 | cout << "head->"; 44 | while (currNode != NULL) { 45 | cout << currNode->value << "->"; 46 | // progress towards BC being false 47 | currNode = currNode->next; 48 | } 49 | cout << "NULL" << endl; 50 | } 51 | 52 | void LinkedList::displayListRecursiveHelper(Node * currNode) { 53 | // base case 54 | if (currNode == NULL) { 55 | cout << "NULL" << endl; 56 | return; 57 | } 58 | 59 | cout << currNode->value << "->"; 60 | // recursive step 61 | displayListRecursiveHelper(currNode->next); 62 | } 63 | 64 | void LinkedList::displayListRecursive() { 65 | // public interface function 66 | // Node and head are private!! 67 | displayListRecursiveHelper(head); 68 | } 69 | 70 | void LinkedList::displayListReverseHelper(Node * currNode) { 71 | // base case 72 | if (currNode == NULL) { 73 | cout << "NULL"; 74 | return; 75 | } 76 | 77 | // recursive step 78 | displayListReverseHelper(currNode->next); 79 | cout << "<-" << currNode->value; 80 | if (currNode == head) { 81 | cout << "<-head" << endl; 82 | } 83 | } 84 | 85 | void LinkedList::displayListReverse() { 86 | // public interface function 87 | // Node and head are private!! 88 | displayListReverseHelper(head); 89 | } 90 | 91 | void LinkedList::appendNode(int newValue) { 92 | // make a new Node 93 | Node * newNode = new Node; 94 | newNode->value = newValue; 95 | newNode->next = NULL; 96 | 97 | // 2 cases 98 | if (head == NULL) { 99 | head = newNode; 100 | } 101 | else { 102 | // list is not empty 103 | // need to traverse list, stopping at the last node 104 | Node * currNode = head; 105 | while (currNode->next != NULL) { 106 | currNode = currNode->next; 107 | } 108 | // currNode points to the last node in the list 109 | currNode->next = newNode; 110 | } 111 | } 112 | 113 | void LinkedList::insertInOrder(int newValue) { 114 | // make a new Node 115 | Node * newNode = new Node; 116 | newNode->value = newValue; 117 | newNode->next = NULL; 118 | 119 | // 2 cases 120 | if (head == NULL) { 121 | head = newNode; 122 | } 123 | else { 124 | // list is not empty 125 | Node * currNode = head; 126 | Node * prevNode = NULL; 127 | 128 | while (currNode != NULL && currNode->value < newValue) { 129 | prevNode = currNode; 130 | currNode = currNode->next; 131 | } 132 | 133 | // 2 cases to check 134 | // 1) inserting at head... so we didn't advance currNode (therefore prevNode is NULL) 135 | // 2) inserting somewhere other than the head, need to the splicing 136 | if (prevNode == NULL) { 137 | head = newNode; 138 | newNode->next = currNode; 139 | } 140 | else { 141 | prevNode->next = newNode; 142 | newNode->next = currNode; 143 | } 144 | } 145 | } 146 | 147 | void LinkedList::deleteAtFront() { 148 | // check to make sure there is something to delete 149 | if (head != NULL) { 150 | Node * nodeToDelete = head; 151 | head = head->next; 152 | delete nodeToDelete; 153 | } 154 | } 155 | 156 | void LinkedList::deleteAtEnd() { 157 | if (head != NULL) { 158 | // list is not empty 159 | // need to traverse list, stopping at the last node 160 | Node * currNode = head; 161 | Node * prevNode = NULL; 162 | while (currNode->next != NULL) { 163 | prevNode = currNode; 164 | currNode = currNode->next; 165 | } 166 | if (prevNode == NULL) { 167 | // deleting at head... only one Node in the list 168 | delete head; 169 | head = NULL; // we now have an empty list 170 | } 171 | else { 172 | delete currNode; 173 | prevNode->next = NULL; 174 | } 175 | } 176 | } 177 | 178 | void LinkedList::deleteNode(int targetValue) { 179 | // check case 1 180 | if (head != NULL) { 181 | // list is not empty 182 | // need to traverse list, stopping at the last node 183 | Node * currNode = head; 184 | // check case 2... the node to delete is the first node 185 | if (head->value == targetValue) { 186 | head = head->next; 187 | delete currNode; 188 | } 189 | else { // case 3... the node to delete is not the first node, but might not even be in the list 190 | Node * prevNode = NULL; 191 | while (currNode != NULL && currNode->value != targetValue) { 192 | prevNode = currNode; 193 | currNode = currNode->next; 194 | } 195 | // check if we found targetValue 196 | if (currNode != NULL) { 197 | // did find it 198 | prevNode->next = currNode->next; 199 | delete currNode; 200 | } 201 | } 202 | } 203 | } 204 | -------------------------------------------------------------------------------- /RecursionFun/LinkedList.h: -------------------------------------------------------------------------------- 1 | #ifndef LINKEDLIST_H 2 | #define LINKEDLIST_H 3 | 4 | #include 5 | 6 | using namespace std; 7 | 8 | // a linked list of Nodes 9 | // each Node stores a single integer value 10 | // can be expanded to store multiple values 11 | // or templated to store any value type 12 | class LinkedList { 13 | private: 14 | // self referential 15 | struct Node { 16 | int value; // data value Node stores 17 | struct Node * next; // points to next Node in list 18 | }; 19 | 20 | Node * head; // list head pointer 21 | void displayListRecursiveHelper(Node *); 22 | void displayListReverseHelper(Node *); 23 | 24 | public: 25 | LinkedList(); // DVC 26 | ~LinkedList(); // destructor 27 | 28 | // common linked list operations 29 | void insertAtFront(int); 30 | void displayList(); 31 | void displayListRecursive(); 32 | void displayListReverse(); 33 | void appendNode(int); // insert at end 34 | void insertInOrder(int); 35 | void deleteAtFront(); 36 | void deleteAtEnd(); 37 | void deleteNode(int); 38 | }; 39 | 40 | #endif 41 | -------------------------------------------------------------------------------- /RecursionFun/Main.cpp: -------------------------------------------------------------------------------- 1 | #include "Recursion.h" 2 | #include "LinkedList.h" 3 | 4 | int main() { 5 | iterativeCountdown(3); 6 | iterativeCountdown(10); 7 | 8 | recursiveCountdown(3); 9 | recursiveCountdown(10); 10 | 11 | // a recursive function: a function that directly (or indirectly) calls itself 12 | // pro: simple/short/elegant solutions for some problems (compared to iterative solutions) 13 | // commonly used by other programmers 14 | // con: high memory overhead (compared to iterative solutions) 15 | 16 | cout << iterativeMultiplication(2, 3) << endl; 17 | cout << recursiveMultiplication(2, 3) << endl; 18 | 19 | cout << iterativePower(2, 3) << endl; 20 | cout << recursivePower(2, 3) << endl; 21 | 22 | cout << iterativeFactorial(3) << endl; 23 | cout << iterativeFactorial(5) << endl; 24 | 25 | cout << recursiveFactorial(3) << endl; 26 | cout << recursiveFactorial(5) << endl; 27 | 28 | displayString("hello", 0); 29 | displayString("recursion", 0); 30 | displayString("hello"); 31 | displayString("recursion"); 32 | 33 | displayStringReverse("hello"); 34 | cout << endl; 35 | displayStringReverse("recursion"); 36 | cout << endl; 37 | 38 | cout << countCharacters("hello") << endl; 39 | cout << countCharacters("recursion") << endl; 40 | 41 | // linked list 42 | LinkedList list; 43 | list.appendNode(10); 44 | list.appendNode(20); 45 | list.appendNode(30); 46 | list.displayList(); 47 | list.displayListRecursive(); 48 | list.displayListReverse(); 49 | 50 | // multiple recursive calls per single function call 51 | fun(5); 52 | cout << endl << endl; 53 | moreFun(5); 54 | 55 | 56 | return 0; 57 | } 58 | -------------------------------------------------------------------------------- /RecursionFun/Recursion.cpp: -------------------------------------------------------------------------------- 1 | #include "Recursion.h" 2 | 3 | void iterativeCountdown(int n) { 4 | for (int i = n; i > 0; i--) { 5 | cout << i << " "; 6 | } 7 | // i == 0 8 | cout << "blastoff!!" << endl; 9 | } 10 | 11 | 12 | void recursiveCountdown(int n) { 13 | // elements of recursion 14 | // 1. base case - no more recursion is appropriate 15 | // e.g. when n == 0 16 | // stop recursing!! 17 | if (n == 0) { 18 | cout << "blastoff!!" << endl; 19 | return; 20 | } 21 | // 2. code to approach the base case - reformation of a similar yet smaller version of the problem (like "progress towards BC being false") 22 | // e.g. print out n and call this function again 23 | // with n - 1 (smaller version of the problem, approaching 0) 24 | cout << n << " "; 25 | // recursive call (AKA step) 26 | recursiveCountdown(n - 1); 27 | cout << "returning from the " << n - 1 << " call" << endl; 28 | } 29 | 30 | int iterativeMultiplication(int m, int n) { 31 | // multiply by adding m n times 32 | int sum = 0, i = 0; 33 | 34 | for (i = 0; i < n; i++) { 35 | sum += m; 36 | } 37 | return sum; 38 | } 39 | 40 | int recursiveMultiplication(int m, int n) { 41 | // multiply by adding m n times 42 | if (n == 1) { 43 | return m; 44 | } 45 | // recursive step 46 | return m + recursiveMultiplication(m, n - 1); 47 | } 48 | 49 | int iterativePower(int base, int exponent) { 50 | // raise base to exponent by multiplying base exponent times 51 | int prod = 1, i = 0; 52 | 53 | for (i = 0; i < exponent; i++) { 54 | prod *= base; 55 | } 56 | return prod; 57 | } 58 | 59 | int recursivePower(int base, int exponent) { 60 | // raise base to exponent by multiplying base exponent times 61 | // base case 62 | if (exponent == 1) { 63 | return base; 64 | } 65 | // recursive step 66 | return base * recursivePower(base, exponent - 1); 67 | } 68 | 69 | int iterativeFactorial(int n) { 70 | // evaluate factorial by multiplying n by (n - 1), (n - 2), ... 1 71 | int result = 1, i = 1; 72 | 73 | for (i = n; i >= 1; i--) { 74 | result *= i; 75 | } 76 | return result; 77 | } 78 | 79 | int recursiveFactorial(int n) { 80 | // evaluate factorial by multiplying n by (n - 1), (n - 2), ... 1 81 | // base case 82 | if (n == 1) { 83 | // 1! = 1 84 | return 1; 85 | } 86 | // recursive step 87 | return n * recursiveFactorial(n - 1); 88 | } 89 | 90 | 91 | void displayString(string s, int index) { 92 | // print string char by char 93 | // base case 94 | if (index == s.length()) { 95 | // hello 96 | cout << endl; 97 | return; 98 | } 99 | // print out the char at index 100 | cout << s.at(index) << " "; 101 | // recursive step 102 | displayString(s, index + 1); 103 | } 104 | 105 | void displayString(string s) { 106 | // print string char by char 107 | if (s.length() == 0) { 108 | cout << endl; 109 | return; 110 | } 111 | // "hello", "ello", "llo", "lo", "o", "" 112 | cout << s.at(0) << " "; 113 | displayString(s.substr(1, s.length() - 1)); 114 | } 115 | 116 | void displayStringReverse(string s) { 117 | // print string char by char in reverse order 118 | if (s.length() == 0) { 119 | return; 120 | } 121 | // "hello", "ello", "llo", "lo", "o", "" 122 | displayStringReverse(s.substr(1, s.length() - 1)); 123 | cout << s.at(0) << " "; 124 | } 125 | 126 | int countCharacters(string s) { 127 | // return number of chars in string 128 | if (s.length() == 0) { 129 | return 0; 130 | } 131 | // "hello", "ello", "llo", "lo", "o", "" 132 | return 1 + countCharacters(s.substr(1, s.length() - 1)); 133 | } 134 | 135 | void fun(int n) { 136 | if (n > 2) { 137 | fun(n - 1); 138 | fun(n - 2); 139 | fun(n - 3); 140 | } 141 | cout << n << endl; 142 | } 143 | 144 | void moreFun(int n) { 145 | cout << n << endl; 146 | if(n > 2) { 147 | moreFun(n - 1); 148 | moreFun(n - 2); 149 | moreFun(n - 3); 150 | } 151 | } 152 | 153 | 154 | -------------------------------------------------------------------------------- /RecursionFun/Recursion.h: -------------------------------------------------------------------------------- 1 | #ifndef RECURSION_H 2 | #define RECURSION_H 3 | 4 | #include 5 | 6 | using namespace std; 7 | 8 | void iterativeCountdown(int); 9 | void recursiveCountdown(int); 10 | 11 | int iterativeMultiplication(int, int); 12 | int recursiveMultiplication(int, int); 13 | 14 | int iterativePower(int, int); 15 | int recursivePower(int, int); 16 | 17 | int iterativeFactorial(int); 18 | int recursiveFactorial(int); 19 | 20 | void displayString(string, int); 21 | void displayString(string); 22 | 23 | void displayStringReverse(string); 24 | 25 | int countCharacters(string); 26 | 27 | void fun(int); 28 | void moreFun(int); 29 | 30 | #endif 31 | -------------------------------------------------------------------------------- /RecursionFun/a.out: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gsprint23/Cpp-Crash-Course/a864cbdf6775e16b2823143b03b04ef7cf6a8558/RecursionFun/a.out -------------------------------------------------------------------------------- /SearchingSortingFun/Main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | void printArray(int[], int); 6 | void insertionSortArray(int[], int); 7 | int linearSearchArray(int[], int, int); 8 | 9 | int main() { 10 | int nums[] = {7, 4, 6, 9, 10, 2, 5, 3, 8}; 11 | int size = 9; 12 | int index = 0; 13 | 14 | printArray(nums, size); 15 | index = linearSearchArray(nums, size, 7); // first item 16 | cout << index << endl; 17 | index = linearSearchArray(nums, size, 8); // last item 18 | cout << index << endl; 19 | index = linearSearchArray(nums, size, 11); // not found 20 | cout << index << endl; 21 | 22 | return 0; 23 | } 24 | 25 | int linearSearchArray(int arr[], int n, int target) { 26 | int counter = 0; 27 | int i; 28 | counter++; // for int i 29 | counter++; // for i = 0 30 | for (i = 0; i < n; i++) { 31 | counter++; // for i < n true 32 | counter++; // for BC (boolean condition) 33 | if (arr[i] == target) { 34 | counter++; // for return i 35 | cout << "counter: " << counter << endl; 36 | return i; 37 | } 38 | counter++; // for i++ 39 | } 40 | counter++; // for i < n false 41 | counter++; // for return -1 42 | cout << "counter: " << counter << endl; 43 | return -1; 44 | } 45 | 46 | void insertionSortArray(int arr[], int size) { 47 | int i, j, currValue; // other += 3 48 | // i = 1 loopControlAssignment++ 49 | for (i = 1; i < size; i++) { 50 | // i < size loopControlComparisons++ 51 | currValue = arr[i]; 52 | j = i - 1; 53 | while (j >= 0 && currValue < arr[j]) { 54 | arr[j + 1] = arr[j]; 55 | j--; 56 | } 57 | arr[j + 1] = currValue; 58 | } 59 | // i < size loopControlComparisons++ 60 | // for the one time the BC evaluates to false 61 | } 62 | 63 | void printArray(int arr[], int size) { 64 | int i; 65 | for (i = 0; i < size - 1; i++) { 66 | cout << arr[i] << ", "; 67 | } 68 | cout << arr[i] << endl; 69 | 70 | } 71 | -------------------------------------------------------------------------------- /SearchingSortingFun/a.out: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gsprint23/Cpp-Crash-Course/a864cbdf6775e16b2823143b03b04ef7cf6a8558/SearchingSortingFun/a.out -------------------------------------------------------------------------------- /StackFun/LinkedList.cpp: -------------------------------------------------------------------------------- 1 | #include "LinkedList.h" 2 | 3 | LinkedList::LinkedList() { 4 | head = NULL; 5 | cout << sizeof(Node) << endl; 6 | } 7 | 8 | LinkedList::~LinkedList() { 9 | // TODO: free each Node's memory in the list 10 | destroyList(); 11 | } 12 | 13 | void LinkedList::destroyList() { 14 | Node * currNode = head; 15 | Node * nextNode = NULL; 16 | 17 | while (currNode != NULL) { 18 | // save the link to the next node 19 | nextNode = currNode->next; 20 | // can safely delete currNode 21 | delete currNode; 22 | currNode = nextNode; 23 | } 24 | head = NULL; // for good practice 25 | } 26 | 27 | void LinkedList::insertAtFront(int newValue) { 28 | // make a new Node 29 | Node * newNode = new Node; 30 | newNode->value = newValue; 31 | newNode->next = NULL; 32 | 33 | // 2 cases 34 | if (head == NULL) { 35 | head = newNode; 36 | } 37 | else { 38 | // list is not empty 39 | newNode->next = head; 40 | head = newNode; 41 | } 42 | } 43 | 44 | void LinkedList::displayList() { 45 | Node * currNode = head; 46 | 47 | cout << "head->"; 48 | while (currNode != NULL) { 49 | cout << currNode->value << "->"; 50 | // progress towards BC being false 51 | currNode = currNode->next; 52 | } 53 | cout << "NULL" << endl; 54 | } 55 | 56 | void LinkedList::appendNode(int newValue) { 57 | // make a new Node 58 | Node * newNode = new Node; 59 | newNode->value = newValue; 60 | newNode->next = NULL; 61 | 62 | // 2 cases 63 | if (head == NULL) { 64 | head = newNode; 65 | } 66 | else { 67 | // list is not empty 68 | // need to traverse list, stopping at the last node 69 | Node * currNode = head; 70 | while (currNode->next != NULL) { 71 | currNode = currNode->next; 72 | } 73 | // currNode points to the last node in the list 74 | currNode->next = newNode; 75 | } 76 | } 77 | 78 | void LinkedList::insertInOrder(int newValue) { 79 | // make a new Node 80 | Node * newNode = new Node; 81 | newNode->value = newValue; 82 | newNode->next = NULL; 83 | 84 | // 2 cases 85 | if (head == NULL) { 86 | head = newNode; 87 | } 88 | else { 89 | // list is not empty 90 | Node * currNode = head; 91 | Node * prevNode = NULL; 92 | 93 | while (currNode != NULL && currNode->value < newValue) { 94 | prevNode = currNode; 95 | currNode = currNode->next; 96 | } 97 | 98 | // 2 cases to check 99 | // 1) inserting at head... so we didn't advance currNode (therefore prevNode is NULL) 100 | // 2) inserting somewhere other than the head, need to the splicing 101 | if (prevNode == NULL) { 102 | head = newNode; 103 | newNode->next = currNode; 104 | } 105 | else { 106 | prevNode->next = newNode; 107 | newNode->next = currNode; 108 | } 109 | } 110 | } 111 | 112 | int LinkedList::deleteAtFront() { 113 | // check to make sure there is something to delete 114 | int value = -1; 115 | if (head != NULL) { 116 | Node * nodeToDelete = head; 117 | head = head->next; 118 | value = nodeToDelete->value; 119 | delete nodeToDelete; 120 | } 121 | return value; 122 | } 123 | 124 | void LinkedList::deleteAtEnd() { 125 | if (head != NULL) { 126 | // list is not empty 127 | // need to traverse list, stopping at the last node 128 | Node * currNode = head; 129 | Node * prevNode = NULL; 130 | while (currNode->next != NULL) { 131 | prevNode = currNode; 132 | currNode = currNode->next; 133 | } 134 | if (prevNode == NULL) { 135 | // deleting at head... only one Node in the list 136 | delete head; 137 | head = NULL; // we now have an empty list 138 | } 139 | else { 140 | delete currNode; 141 | prevNode->next = NULL; 142 | } 143 | } 144 | } 145 | 146 | void LinkedList::deleteNode(int targetValue) { 147 | // check case 1 148 | if (head != NULL) { 149 | // list is not empty 150 | // need to traverse list, stopping at the last node 151 | Node * currNode = head; 152 | // check case 2... the node to delete is the first node 153 | if (head->value == targetValue) { 154 | head = head->next; 155 | delete currNode; 156 | } 157 | else { // case 3... the node to delete is not the first node, but might not even be in the list 158 | Node * prevNode = NULL; 159 | while (currNode != NULL && currNode->value != targetValue) { 160 | prevNode = currNode; 161 | currNode = currNode->next; 162 | } 163 | // check if we found targetValue 164 | if (currNode != NULL) { 165 | // did find it 166 | prevNode->next = currNode->next; 167 | delete currNode; 168 | } 169 | } 170 | } 171 | } 172 | -------------------------------------------------------------------------------- /StackFun/LinkedList.h: -------------------------------------------------------------------------------- 1 | #ifndef LINKEDLIST_H 2 | #define LINKEDLIST_H 3 | 4 | #include 5 | 6 | using namespace std; 7 | 8 | // a linked list of Nodes 9 | // each Node stores a single integer value 10 | // can be expanded to store multiple values 11 | // or templated to store any value type 12 | class LinkedList { 13 | protected: 14 | // self referential 15 | struct Node { 16 | int value; // data value Node stores 17 | struct Node * next; // points to next Node in list 18 | }; 19 | 20 | Node * head; // list head pointer 21 | 22 | public: 23 | LinkedList(); // DVC 24 | ~LinkedList(); // destructor 25 | 26 | // common linked list operations 27 | void insertAtFront(int); 28 | void displayList(); 29 | void appendNode(int); // insert at end 30 | void insertInOrder(int); 31 | int deleteAtFront(); 32 | void deleteAtEnd(); 33 | void deleteNode(int); 34 | void destroyList(); 35 | }; 36 | 37 | #endif 38 | -------------------------------------------------------------------------------- /StackFun/Main.cpp: -------------------------------------------------------------------------------- 1 | #include "LinkedList.h" 2 | #include "Stack.h" 3 | 4 | int main() { 5 | Stack stack; // start out with empty stack 6 | // invoke the default DVC of Stack 7 | // which will invoke the DVC of LinkedList 8 | 9 | // okay to push and pop chars with our stack 10 | // each node in the linked list stores an int 11 | // A is ASCII value 65 12 | string toReverse = "Stack ADTS are awesome!!"; 13 | int asciiValue = -1; 14 | 15 | for (char c : toReverse) { 16 | stack.push(c); 17 | } 18 | cout << stack.size() << endl; 19 | cout << "Output: "; 20 | while (!stack.isEmpty()) { 21 | asciiValue = stack.pop(); 22 | cout << static_cast(asciiValue); 23 | } 24 | cout << endl; 25 | 26 | /*cout << "Pushing" << endl; 27 | stack.push(5); 28 | stack.push(3); 29 | cout << stack.peek() << endl; 30 | cout << stack.isEmpty() << endl; 31 | cout << stack.size() << endl; 32 | 33 | int value = -1; 34 | cout << "Popping" << endl; 35 | value = stack.pop(); 36 | cout << value << endl; 37 | cout << stack.peek() << endl; 38 | cout << stack.isEmpty() << endl; 39 | cout << stack.size() << endl; 40 | 41 | cout << "Popping" << endl; 42 | value = stack.pop(); 43 | cout << value << endl; 44 | cout << stack.peek() << endl; 45 | cout << stack.isEmpty() << endl; 46 | cout << stack.size() << endl; 47 | */ 48 | 49 | cout << "Pushing and clearing" << endl; 50 | stack.push(5); 51 | stack.push(3); 52 | stack.clear(); 53 | cout << stack.peek() << endl; 54 | cout << stack.isEmpty() << endl; 55 | cout << stack.size() << endl; 56 | 57 | 58 | /*LinkedList list; // start out empty list 59 | 60 | list.insertAtFront(12); 61 | list.insertAtFront(5); 62 | list.insertAtFront(3); 63 | 64 | list.displayList();*/ 65 | /*list.deleteNode(3); // delete first node 66 | list.displayList(); 67 | list.deleteNode(5); 68 | list.displayList(); 69 | list.deleteNode(12); 70 | list.displayList(); 71 | list.deleteNode(4); 72 | list.displayList();*/ 73 | 74 | 75 | /*list.deleteAtEnd(); 76 | list.displayList(); 77 | list.deleteAtEnd(); 78 | list.displayList(); 79 | list.deleteAtEnd(); 80 | list.displayList(); 81 | list.deleteAtEnd(); 82 | list.displayList();*/ 83 | 84 | /*list.deleteAtFront(); 85 | list.displayList(); 86 | list.deleteAtFront(); 87 | list.displayList(); 88 | list.deleteAtFront(); 89 | list.displayList(); 90 | list.deleteAtFront(); 91 | list.displayList(); 92 | */ 93 | 94 | //list.appendNode(15); 95 | /*list.displayList(); 96 | list.insertInOrder(7); 97 | list.displayList(); 98 | list.insertInOrder(2); 99 | list.displayList(); 100 | list.insertInOrder(15); 101 | list.displayList();*/ 102 | 103 | return 0; 104 | } 105 | -------------------------------------------------------------------------------- /StackFun/Stack.cpp: -------------------------------------------------------------------------------- 1 | #include "Stack.h" 2 | 3 | // the head of the linked list is the 4 | // top of the stack 5 | void Stack::push(int newItem) { 6 | insertAtFront(newItem); 7 | } 8 | 9 | int Stack::pop() { 10 | return deleteAtFront(); 11 | } 12 | 13 | int Stack::peek() { 14 | if (head != NULL) { 15 | return head->value; 16 | } 17 | return -1; 18 | } 19 | 20 | bool Stack::isEmpty() { 21 | if (head != NULL) { 22 | return false; 23 | } 24 | return true; 25 | } 26 | 27 | void Stack::clear() { 28 | // 2 ways to implement clear() 29 | // 1) we can write a loop 30 | //while (!isEmpty()) { 31 | // pop(); 32 | //} 33 | // 2) we can leverage the destructor code we already wrote in LinkedList 34 | destroyList(); 35 | } 36 | 37 | int Stack::size() { 38 | // 2 ways to implement size() 39 | // 1) traverse the list and count the # of nodes O(N) 40 | // 2) to add a count or size attribute to LinkedList or to Stack 41 | // keep it up to date on push() and on pop() 42 | // on all adds/inserts and on all deletes 43 | // O(1) 44 | int count = 0; 45 | Node * currNode = head; 46 | while (currNode != NULL) { 47 | count++; 48 | currNode = currNode->next; 49 | } 50 | return count; 51 | } 52 | -------------------------------------------------------------------------------- /StackFun/Stack.h: -------------------------------------------------------------------------------- 1 | #ifndef STACK_H 2 | #define STACK_H 3 | 4 | #include "LinkedList.h" 5 | 6 | // 2 ways to think about implementing a stack 7 | // 1) composition: Stack has a LinkedList 8 | // 2) inheritance: Stack is a LinkedList 9 | 10 | // 2) 11 | class Stack : public LinkedList { 12 | // no Stack-specific state 13 | // Stack-specific operations 14 | public: 15 | void push(int); 16 | int pop(); 17 | int peek(); 18 | bool isEmpty(); 19 | void clear(); 20 | int size(); 21 | }; 22 | 23 | #endif 24 | -------------------------------------------------------------------------------- /StackFun/a.out: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gsprint23/Cpp-Crash-Course/a864cbdf6775e16b2823143b03b04ef7cf6a8558/StackFun/a.out -------------------------------------------------------------------------------- /StringFun/BinaryFun.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | int convertBinaryToDecimal(string); 8 | string convertDecimalToBinary(int); 9 | 10 | int main() { 11 | 12 | cout << "0b000: " << 0b000 << endl; 13 | cout << "0b001: " << 0b001 << endl; 14 | cout << "0b010: " << 0b010 << endl; 15 | cout << "0b011: " << 0b011 << endl; 16 | cout << "0b100: " << 0b100 << endl; 17 | cout << "0b101: " << 0b101 << endl; 18 | cout << "0b110: " << 0b110 << endl; 19 | cout << "0b111: " << 0b111 << endl; 20 | // 8 in decimal 21 | cout << "0b1000: " << 0b1000 << endl; 22 | 23 | // task: write an algorithm that converts binary to decimal 24 | // a function that accepts a string representing binary number and returns an integer 25 | 26 | cout << convertBinaryToDecimal("11111") << endl; 27 | cout << convertDecimalToBinary(94) << endl; 28 | cout << convertDecimalToBinary(13) << endl; 29 | 30 | return 0; 31 | } 32 | 33 | string convertDecimalToBinary(int decimal) { 34 | string binary = ""; 35 | int highestPowerTwo = 0, powerTwoValue = 0; 36 | int i = 0; 37 | 38 | highestPowerTwo = log2(decimal); 39 | cout << highestPowerTwo << endl; 40 | for (i = highestPowerTwo; i >= 0; i--) { 41 | powerTwoValue = pow(2, i); 42 | if (decimal / powerTwoValue > 0) { 43 | binary += "1"; 44 | decimal -= powerTwoValue; 45 | } 46 | else { 47 | binary += "0"; 48 | } 49 | } 50 | 51 | return binary; 52 | } 53 | 54 | int convertBinaryToDecimal(string binary) { 55 | int decimal = 0; // store our summation 56 | int i = 0, powerTwo = 0; 57 | 58 | powerTwo = binary.length() - 1; // highest power of two 59 | // power of two for the digit at index 0 60 | for (i = 0; i < binary.length(); i++) { 61 | if (binary.at(i) == '1') { 62 | decimal += pow(2, powerTwo); 63 | } 64 | powerTwo--; 65 | } 66 | 67 | 68 | 69 | return decimal; 70 | } 71 | 72 | 73 | -------------------------------------------------------------------------------- /StringFun/StringFun.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | int main() { 7 | string word = "hello"; 8 | string word2(word); // word2 stores a copy of the string in word 9 | string word3(word, 2); // "llo" 10 | string word4(word, 3, 2); // starting at index 3, get 2 characters of word "lo" 11 | string sentence = ""; 12 | 13 | cout << word << endl; 14 | cout << word2 << endl; 15 | cout << word3 << endl; 16 | cout << word4 << endl; 17 | 18 | word2.at(0) = 'H'; 19 | cout << word << endl; 20 | cout << word2 << endl; 21 | 22 | // relational operators to compare strings 23 | // >, <, >=, <=, ==, != 24 | // strings are compared character by character based on their ASCII codes 25 | // code for 'A' is 65 26 | // code for 'a' is 97 27 | cout << (word > "Hello") << endl; 28 | cout << (word < "Hello") << endl; 29 | cout << (word == "Hello") << endl; 30 | cout << (word != "Hello") << endl; 31 | 32 | // concatenation operator + 33 | // adds two strings together by joining the end of the first string to the beginning of the second string 34 | sentence = word + ", there"; 35 | cout << sentence << endl; 36 | 37 | // shorthand assignment operator using + 38 | // += which is more commonly as the append operator 39 | sentence += "!!"; // sentence = sentence + "!!"; 40 | cout << sentence << endl; 41 | 42 | // the subscript operator [ ] 43 | // same as with arrays and vectors 44 | cout << sentence[0] << endl; 45 | 46 | return 0; 47 | } 48 | -------------------------------------------------------------------------------- /StringFun/StringFun2.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | int main() { 7 | string word = "hello"; 8 | string word2(word); // word2 stores a copy of the string in word 9 | string word3(word, 2); // "llo" 10 | string word4(word, 3, 2); // starting at index 3, get 2 characters of word "lo" 11 | string sentence = ""; 12 | string course = "CPSC 121"; 13 | 14 | int retVal = 0; 15 | 16 | cout << word << endl; 17 | cout << word2 << endl; 18 | cout << word3 << endl; 19 | cout << word4 << endl; 20 | 21 | word2.at(0) = 'H'; 22 | cout << word << endl; 23 | cout << word2 << endl; 24 | 25 | // relational operators to compare strings 26 | // >, <, >=, <=, ==, != 27 | // strings are compared character by character based on their ASCII codes 28 | // code for 'A' is 65 29 | // code for 'a' is 97 30 | cout << (word > "Hello") << endl; 31 | cout << (word < "Hello") << endl; 32 | cout << (word == "Hello") << endl; 33 | cout << (word != "Hello") << endl; 34 | 35 | // concatenation operator + 36 | // adds two strings together by joining the end of the first string to the beginning of the second string 37 | sentence = word + ", there"; 38 | cout << sentence << endl; 39 | 40 | // shorthand assignment operator using + 41 | // += which is more commonly as the append operator 42 | sentence += "!!"; // sentence = sentence + "!!"; 43 | cout << sentence << endl; 44 | 45 | // the subscript operator [ ] 46 | // same as with arrays and vectors 47 | cout << sentence[0] << endl; 48 | 49 | // STRING MEMBER FUNCTIONS 50 | // recall: a member function is called via 51 | // .(); 52 | // we know about size(), length(), and at() 53 | // time for some new ones! 54 | 55 | // substr() returns a string that is a substring of a larger string 56 | // string substr(int startIndex); returns a substring from [startIndex, end of the string] 57 | // 01234567 58 | // CPSC 121 59 | cout << course.substr(2) << endl; 60 | // string substr(int startIndex, int numChars); 61 | cout << course.substr(2, 2) << endl; 62 | // task: print the "12" of course 63 | cout << course.substr(5, 2) << endl; 64 | 65 | // find() returns an integer representing where in a string a target string (or a target character) is located 66 | // int find(char target); 67 | // int find(string target); 68 | // the returned integer is the index location of target 69 | // however, find() returns a special value string::npos when the target is not found 70 | cout << "string::npos: " << string::npos << endl; 71 | cout << course.find('2') << endl; 72 | cout << course.find(" 1") << endl; 73 | cout << course.find('Z') << endl; 74 | retVal = course.find('Z'); 75 | // check for npos 76 | if (retVal == string::npos) { 77 | cout << "Z was not found in the string." << endl; 78 | } 79 | // task: search for "cpsc" in course 80 | cout << course.find("cpsc") << endl; 81 | 82 | // replace() replaces characters in a string with another string 83 | // string replace(int startIndex, int numChars, string newChars); 84 | // newChars will replace the chars at indices [numChars, numChars + newChars) 85 | // replace the CPSC with cpsc 86 | course = course.replace(0, 4, "cpsc"); 87 | cout << course << endl; 88 | // task: replace the numbers 121 with "!!" 89 | course = course.replace(5, 3, "!!"); 90 | cout << course << endl; 91 | 92 | 93 | return 0; 94 | } 95 | -------------------------------------------------------------------------------- /StringFun/StringStreamFun.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include // needed for istringstream and ostringstream 3 | 4 | using namespace std; 5 | 6 | 7 | int main() { 8 | string courseInfo = "CPSC 121 C++"; 9 | // our goal is to extract each piece of information in courseInfo 10 | string prefix; 11 | string courseNum; 12 | string language; 13 | string line; 14 | 15 | // use istringstream just like you would with cin and >> and getline() to parse text into pieces (AKA tokens) 16 | // in the courseInfo string, each token is separated by a space 17 | // the >> uses spaces to separate strings into tokens for us :) 18 | istringstream inputStringStream; 19 | ostringstream outputStringStream; 20 | // need to tell istringstream variable what string to read from 21 | inputStringStream.str(courseInfo); 22 | 23 | // use >> and getline() with inputStringStream just like we would with cin 24 | inputStringStream >> prefix; 25 | cout << "Prefix: " << prefix << endl; 26 | // task: extract courseNum and extract language 27 | inputStringStream >> courseNum; 28 | cout << "Course num: " << courseNum << endl; 29 | inputStringStream >> language; 30 | cout << "Language: " << language << endl; 31 | 32 | courseInfo = "This course\nuses the\nC++ programming\nlanguage!!"; 33 | // suppose we want each line in its own string 34 | // use getline()! 35 | // need to reset the state of istringstream variable 36 | inputStringStream.clear(); 37 | inputStringStream.str(courseInfo); 38 | do { 39 | getline(inputStringStream, line); 40 | cout << line << endl; 41 | } while (inputStringStream.good()); 42 | 43 | // use ostringstream to write (AKA construct, build) to a string 44 | // we can use the << with ostringstream just like we would with cout and ofstream 45 | outputStringStream << "This courses uses the " << language << " programming language!!"; 46 | line = outputStringStream.str(); // get the string we have been building with << 47 | cout << line << endl; 48 | 49 | // valueA,valueB,valueC,... 50 | 51 | 52 | return 0; 53 | } 54 | -------------------------------------------------------------------------------- /StringFun/TokenizingFun/StringTokenizingFun.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | int main() { 9 | ifstream inputFile; 10 | string header, line; 11 | string id, first, last, standing, gpa; 12 | istringstream inputStringStream; 13 | double gpaDouble = 0.0; 14 | 15 | inputFile.open("student_info.csv"); 16 | // read in line by line the info in inputFile 17 | // read the header line in first! 18 | getline(inputFile, header); 19 | cout << header << endl; 20 | 21 | while (!inputFile.eof()) { 22 | getline(inputFile, line); 23 | // getline() by default uses \n as a delimiter 24 | // getline() is overloaded to accept a 3rd argument representing the delimiter we want to use!! 25 | if (inputFile.good()) { 26 | // successfully read in a row 27 | cout << "Read: " << line << endl; 28 | // use getline() and istringstream in order to tokenize the pieces of information separated by commas 29 | inputStringStream.clear(); 30 | inputStringStream.str(line); 31 | getline(inputStringStream, id, ','); 32 | getline(inputStringStream, first, ','); 33 | getline(inputStringStream, last, ','); 34 | getline(inputStringStream, standing, ','); 35 | getline(inputStringStream, gpa, ','); 36 | gpaDouble = stod(gpa); // string to double 37 | cout << id << " " << first << " " << last << " " << standing << " " << gpaDouble << endl; 38 | } 39 | } 40 | 41 | 42 | inputFile.close(); 43 | 44 | 45 | return 0; 46 | } 47 | -------------------------------------------------------------------------------- /StringFun/TokenizingFun/student_info.csv: -------------------------------------------------------------------------------- 1 | id,first,last,standing,gpa 2 | 1000,jane,student,freshman,3.5 3 | 1001,joe,schmoe,sophomore,3.2 4 | 1002,spike,bulldog,senior,3.7 5 | -------------------------------------------------------------------------------- /StructsFun/Main.cpp: -------------------------------------------------------------------------------- 1 | #include "Structs.h" 2 | 3 | int main() { 4 | // create Fruit variables 5 | // now memory will be allocated 6 | Fruit myFruit = {"kiwi", "brown", 2.5}; 7 | 8 | //cout << myFruit << endl; 9 | // can't use << and Fruit until we overload the << to work with Fruits 10 | // we can acess individual members using the . 11 | // . direction member selection operator 12 | cout << myFruit.type << endl; 13 | // define a function that accepts a Fruit and prints out with labels the values of all the Fruit members 14 | printFruit(myFruit); 15 | 16 | // pointers to structs 17 | Fruit * myFruitPtr = &myFruit; 18 | cout << (*myFruitPtr).type << endl; 19 | 20 | // -> arrow operator 21 | // indirect member selection operator 22 | // dereference the pointer and select from the struct it points to 23 | cout << myFruitPtr->type << endl; 24 | 25 | // structs are pass by value 26 | // struct assignment is okay... makes a copy 27 | Fruit myOtherFruit = myFruit; // copy 28 | myOtherFruit.type = "apple"; 29 | printFruit(myFruit); 30 | printFruit(myOtherFruit); 31 | 32 | // how do we compare fruits? 33 | Fruit myFruitArr[10]; // fill them up 34 | // sort myFruitArr... 35 | // relational operators < > == != <= >= 36 | // define a function that takes two Fruits and returns 37 | // -1 if the first fruit is "<" the second fruit 38 | // 1 if the second fruit is "<" the first fruit 39 | // 0 if the fruit stores the same values 40 | cout << compareFruits(&myFruit, &myOtherFruit) << endl; 41 | myOtherFruit.type = "kiwi"; 42 | cout << compareFruits(&myFruit, &myOtherFruit) << endl; 43 | 44 | Fruit * myDynFruitArr = new Fruit[20]; 45 | // be sure to zero out memory 46 | // be sure to free this memory 47 | 48 | return 0; 49 | } 50 | -------------------------------------------------------------------------------- /StructsFun/Makefile: -------------------------------------------------------------------------------- 1 | # Makefile is a script that contains rules 2 | # The rules define how to compile and run your project 3 | # the first rule in the file is the one that is executed when you run make 4 | # to run other rules, use their name after make 5 | all: 6 | g++ Main.cpp Structs.cpp -o runStructsFun 7 | ./runStructsFun 8 | compile: 9 | g++ Main.cpp Structs.cpp -o runStructsFun 10 | run: 11 | ./runStructsFun 12 | -------------------------------------------------------------------------------- /StructsFun/Structs.cpp: -------------------------------------------------------------------------------- 1 | #include "Structs.h" 2 | 3 | void printFruit(const Fruit f) { 4 | cout << "Type: " << f.type << endl; 5 | cout << "Color: " << f.color << endl; 6 | cout << "Weight: "<< f.weight << endl; 7 | } 8 | 9 | int compareFruits(Fruit * f1, Fruit * f2) { 10 | // compare by type, then color, then weight 11 | if (f1->type < f2->type) { 12 | return -1; 13 | } 14 | else if (f1->type > f2->type) { 15 | return 1; 16 | } 17 | else { // same type, check color 18 | if (f1->color < f2->color) { 19 | return -1; 20 | } 21 | else if (f1->color > f2->color) { 22 | return 1; 23 | } 24 | else { // same type AND color, check weight 25 | if (f1->weight < f2->weight) { 26 | return -1; 27 | } 28 | else if (f1->weight > f2->weight) { 29 | return 1; 30 | } 31 | else { // same type AND color AND weight 32 | return 0; 33 | } 34 | } 35 | } 36 | 37 | } 38 | -------------------------------------------------------------------------------- /StructsFun/Structs.h: -------------------------------------------------------------------------------- 1 | #ifndef STRUCTS_H 2 | #define STRUCTS_H 3 | 4 | // includes 5 | #include 6 | 7 | // usings 8 | using namespace std; 9 | 10 | // constant global variables 11 | // struct or class definitions 12 | // a struct is a programmer defined collection of data members 13 | // example: Fruit struct 14 | // structs are DEFINED in header files 15 | // note that no memory is allocated for a definition 16 | struct Fruit { 17 | string type; // apple, banana, orange, etc. 18 | string color; // red, green, yellow, etc. 19 | double weight; // in ounces 20 | }; 21 | 22 | // prototypes 23 | void printFruit(const Fruit); 24 | int compareFruits(Fruit *, Fruit *); 25 | 26 | #endif 27 | -------------------------------------------------------------------------------- /TemplatedLinkedListFun/LinkedList.h: -------------------------------------------------------------------------------- 1 | #ifndef LINKEDLIST_H 2 | #define LINKEDLIST_H 3 | 4 | #include 5 | 6 | using namespace std; 7 | 8 | // a linked list of Nodes 9 | // each Node stores a single integer value 10 | // can be expanded to store multiple values 11 | // or templated to store any value type 12 | template 13 | class LinkedList { 14 | private: 15 | // self referential 16 | struct Node { 17 | T value; // data value Node stores 18 | struct Node * next; // points to next Node in list 19 | }; 20 | 21 | Node * head; // list head pointer 22 | 23 | public: 24 | LinkedList(); // DVC 25 | ~LinkedList(); // destructor 26 | 27 | // common linked list operations 28 | void insertAtFront(T); 29 | void displayList(); 30 | void appendNode(T); // insert at end 31 | void insertInOrder(T); 32 | void deleteAtFront(); 33 | void deleteAtEnd(); 34 | void deleteNode(T); 35 | }; 36 | 37 | // to break this up into header and source 38 | // follow the guide below 39 | // method #3 from 40 | // https://www.codeproject.com/Articles/48575/How-to-Define-a-Template-Class-in-a-h-File-and-Imp 41 | // to avoid linking problems 42 | // during compilation because we 43 | // used a template class 44 | // and split its implementation up 45 | // into header and source file 46 | //#include "LinkedList.cpp" 47 | // then only compile Main.cpp 48 | 49 | // begin LinkedList.cpp contents 50 | template 51 | LinkedList::LinkedList() { 52 | head = NULL; 53 | cout << sizeof(Node) << endl; 54 | } 55 | 56 | template 57 | LinkedList::~LinkedList() { 58 | // TODO: free each Node's memory in the list 59 | Node * currNode = head; 60 | Node * nextNode = NULL; 61 | 62 | while (currNode != NULL) { 63 | // save the link to the next node 64 | nextNode = currNode->next; 65 | // can safely delete currNode 66 | delete currNode; 67 | currNode = nextNode; 68 | } 69 | } 70 | 71 | template 72 | void LinkedList::insertAtFront(T newValue) { 73 | // make a new Node 74 | Node * newNode = new Node; 75 | newNode->value = newValue; 76 | newNode->next = NULL; 77 | 78 | // 2 cases 79 | if (head == NULL) { 80 | head = newNode; 81 | } 82 | else { 83 | // list is not empty 84 | newNode->next = head; 85 | head = newNode; 86 | } 87 | } 88 | 89 | template 90 | void LinkedList::displayList() { 91 | Node * currNode = head; 92 | 93 | cout << "head->"; 94 | while (currNode != NULL) { 95 | cout << currNode->value << "->"; 96 | // progress towards BC being false 97 | currNode = currNode->next; 98 | } 99 | cout << "NULL" << endl; 100 | } 101 | 102 | template 103 | void LinkedList::appendNode(T newValue) { 104 | // make a new Node 105 | Node * newNode = new Node; 106 | newNode->value = newValue; 107 | newNode->next = NULL; 108 | 109 | // 2 cases 110 | if (head == NULL) { 111 | head = newNode; 112 | } 113 | else { 114 | // list is not empty 115 | // need to traverse list, stopping at the last node 116 | Node * currNode = head; 117 | while (currNode->next != NULL) { 118 | currNode = currNode->next; 119 | } 120 | // currNode points to the last node in the list 121 | currNode->next = newNode; 122 | } 123 | } 124 | 125 | template 126 | void LinkedList::insertInOrder(T newValue) { 127 | // make a new Node 128 | Node * newNode = new Node; 129 | newNode->value = newValue; 130 | newNode->next = NULL; 131 | 132 | // 2 cases 133 | if (head == NULL) { 134 | head = newNode; 135 | } 136 | else { 137 | // list is not empty 138 | Node * currNode = head; 139 | Node * prevNode = NULL; 140 | 141 | while (currNode != NULL && currNode->value < newValue) { 142 | prevNode = currNode; 143 | currNode = currNode->next; 144 | } 145 | 146 | // 2 cases to check 147 | // 1) inserting at head... so we didn't advance currNode (therefore prevNode is NULL) 148 | // 2) inserting somewhere other than the head, need to the splicing 149 | if (prevNode == NULL) { 150 | head = newNode; 151 | newNode->next = currNode; 152 | } 153 | else { 154 | prevNode->next = newNode; 155 | newNode->next = currNode; 156 | } 157 | } 158 | } 159 | 160 | template 161 | void LinkedList::deleteAtFront() { 162 | // check to make sure there is something to delete 163 | if (head != NULL) { 164 | Node * nodeToDelete = head; 165 | head = head->next; 166 | delete nodeToDelete; 167 | } 168 | } 169 | 170 | template 171 | void LinkedList::deleteAtEnd() { 172 | if (head != NULL) { 173 | // list is not empty 174 | // need to traverse list, stopping at the last node 175 | Node * currNode = head; 176 | Node * prevNode = NULL; 177 | while (currNode->next != NULL) { 178 | prevNode = currNode; 179 | currNode = currNode->next; 180 | } 181 | if (prevNode == NULL) { 182 | // deleting at head... only one Node in the list 183 | delete head; 184 | head = NULL; // we now have an empty list 185 | } 186 | else { 187 | delete currNode; 188 | prevNode->next = NULL; 189 | } 190 | } 191 | } 192 | 193 | template 194 | void LinkedList::deleteNode(T targetValue) { 195 | // check case 1 196 | if (head != NULL) { 197 | // list is not empty 198 | // need to traverse list, stopping at the last node 199 | Node * currNode = head; 200 | // check case 2... the node to delete is the first node 201 | if (head->value == targetValue) { 202 | head = head->next; 203 | delete currNode; 204 | } 205 | else { // case 3... the node to delete is not the first node, but might not even be in the list 206 | Node * prevNode = NULL; 207 | while (currNode != NULL && currNode->value != targetValue) { 208 | prevNode = currNode; 209 | currNode = currNode->next; 210 | } 211 | // check if we found targetValue 212 | if (currNode != NULL) { 213 | // did find it 214 | prevNode->next = currNode->next; 215 | delete currNode; 216 | } 217 | } 218 | } 219 | } 220 | #endif 221 | -------------------------------------------------------------------------------- /TemplatedLinkedListFun/Main.cpp: -------------------------------------------------------------------------------- 1 | #include "LinkedList.h" 2 | 3 | int main() { 4 | LinkedList list; // start out empty list 5 | 6 | list.insertAtFront(12); 7 | list.insertAtFront(5); 8 | list.insertAtFront(3); 9 | 10 | list.displayList(); 11 | /*list.deleteNode(3); // delete first node 12 | list.displayList(); 13 | list.deleteNode(5); 14 | list.displayList(); 15 | list.deleteNode(12); 16 | list.displayList(); 17 | list.deleteNode(4); 18 | list.displayList();*/ 19 | 20 | 21 | /*list.deleteAtEnd(); 22 | list.displayList(); 23 | list.deleteAtEnd(); 24 | list.displayList(); 25 | list.deleteAtEnd(); 26 | list.displayList(); 27 | list.deleteAtEnd(); 28 | list.displayList();*/ 29 | 30 | /*list.deleteAtFront(); 31 | list.displayList(); 32 | list.deleteAtFront(); 33 | list.displayList(); 34 | list.deleteAtFront(); 35 | list.displayList(); 36 | list.deleteAtFront(); 37 | list.displayList(); 38 | */ 39 | 40 | //list.appendNode(15); 41 | /*list.displayList(); 42 | list.insertInOrder(7); 43 | list.displayList(); 44 | list.insertInOrder(2); 45 | list.displayList(); 46 | list.insertInOrder(15); 47 | list.displayList();*/ 48 | 49 | return 0; 50 | } 51 | -------------------------------------------------------------------------------- /VectorFun/SortingFun.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | void printArray(int[], int); 7 | void selectionSortArray(int[], int); 8 | void printVector(vector); 9 | void selectionSortVector(vector&); 10 | 11 | int main() { 12 | int nums[] = {4, 8, 7, 10, 3, 6, 9, 2, 5}; 13 | int size = 9; 14 | vector numsVector{4, 8, 7, 10, 3, 6, 9, 2, 5}; 15 | 16 | printArray(nums, size); 17 | selectionSortArray(nums, size); 18 | printArray(nums, size); 19 | 20 | // task: define and call a function called selectionSortVector() to sort a vector of integers 21 | printVector(numsVector); 22 | selectionSortVector(numsVector); 23 | printVector(numsVector); 24 | 25 | return 0; 26 | } 27 | 28 | void selectionSortVector(vector& v) { 29 | int i = 0, j = 0; 30 | int minIndex = 0, min = 0; 31 | 32 | for (i = 0; i < v.size(); i++) { 33 | minIndex = i; 34 | min = v.at(i); 35 | for (j = i + 1; j < v.size(); j++) { 36 | if (v.at(j) < min) { 37 | minIndex = j; 38 | min = v.at(j); 39 | } 40 | } 41 | // swap 42 | v.at(minIndex) = v.at(i); 43 | v.at(i) = min; 44 | } 45 | cout << "**"; 46 | printVector(v); 47 | } 48 | 49 | void printVector(vector v) { 50 | // use a range based for loop 51 | for (int i : v) { 52 | cout << i << " "; 53 | } 54 | cout << endl; 55 | } 56 | 57 | void selectionSortArray(int arr[], int size) { 58 | int i = 0, j = 0; 59 | int min = 0, minIndex = 0; 60 | 61 | for (i = 0; i < size; i++) { 62 | minIndex = i; 63 | min = arr[i]; 64 | // classic find minimum problem 65 | // search through the unsorted portion of the array for a value smaller than min 66 | for (j = i + 1; j < size; j++) { 67 | if (arr[j] < min) { 68 | // we have a new min 69 | minIndex = j; 70 | min = arr[j]; 71 | } 72 | } 73 | // swap! 74 | arr[minIndex] = arr[i]; 75 | arr[i] = min; 76 | } 77 | } 78 | 79 | void printArray(int arr[], int size) { 80 | int i = 0; 81 | 82 | for (i = 0; i < size; i++) { 83 | cout << arr[i] << " "; 84 | } 85 | cout << endl; 86 | 87 | } 88 | -------------------------------------------------------------------------------- /VectorFun/VectorFun.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | void printVector(vector); 8 | void printTwoDVector(vector>); 9 | 10 | int main() { 11 | // vector declaration 12 | vector myInts; // empty vector that is ready to store integers 13 | vector myStrings(10); // a vector that stores 10 empty strings 14 | 15 | // vector declaration and initialization 16 | vector words(5, "hello"); // 5 strings that are all "hello" 17 | vector words2{"hello", "goodbye"}; // 2 strings 18 | 19 | // 2D vectors 20 | vector> twoDWords; // empty 2D vector of strings 21 | vector> twoDWords2{{"one", "two"}, {"three", "four"}}; 22 | 23 | 24 | 25 | // use .at() over [] because it performs bounds checking that will give you a runtime error if you use an out of bounds index 26 | cout << words2[0] << endl; 27 | cout << words2.at(1) << endl; 28 | 29 | // use size() member function in order to get the number of elements in the vector 30 | cout << myInts.size() << endl; 31 | cout << myStrings.size() << endl; 32 | cout << words.size() << endl; 33 | cout << words2.size() << endl; 34 | 35 | printVector(words); 36 | printVector(words2); 37 | 38 | printTwoDVector(twoDWords2); 39 | 40 | //cout << words << endl; // causes our program to crash 41 | 42 | 43 | return 0; 44 | } 45 | 46 | void printTwoDVector(vector> v) { 47 | int i = 0, j = 0; 48 | vector temp; 49 | 50 | for (i = 0; i < v.size(); i++) { 51 | temp = v.at(i); 52 | for (j = 0; j < temp.size(); j++) { 53 | cout << temp.at(j) << " "; 54 | } 55 | cout << endl; 56 | } 57 | 58 | } 59 | 60 | void printVector(vector v) { 61 | int i = 0; 62 | 63 | for (i = 0; i < v.size(); i++) { 64 | cout << v.at(i) << " "; 65 | } 66 | cout << endl; 67 | } 68 | -------------------------------------------------------------------------------- /VectorFun/VectorFun2.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | void printVector(vector); 8 | void printTwoDVector(vector>); 9 | 10 | int main() { 11 | // vector declaration 12 | vector myInts; // empty vector that is ready to store integers 13 | vector myStrings(10); // a vector that stores 10 empty strings 14 | 15 | // vector declaration and initialization 16 | vector words(5, "hello"); // 5 strings that are all "hello" 17 | vector words2{"hello", "goodbye"}; // 2 strings 18 | 19 | // 2D vectors 20 | vector> twoDWords; // empty 2D vector of strings 21 | vector> twoDWords2{{"one", "two"}, {"three", "four"}}; 22 | 23 | 24 | 25 | // use .at() over [] because it performs bounds checking that will give you a runtime error if you use an out of bounds index 26 | cout << words2[0] << endl; 27 | cout << words2.at(1) << endl; 28 | 29 | // use size() member function in order to get the number of elements in the vector 30 | cout << myInts.size() << endl; 31 | cout << myStrings.size() << endl; 32 | cout << words.size() << endl; 33 | cout << words2.size() << endl; 34 | 35 | printVector(words); 36 | printVector(words2); 37 | 38 | printTwoDVector(twoDWords2); 39 | 40 | //cout << words << endl; // causes our program to crash 41 | 42 | // add a word to the back of words2 43 | cout << words2.size() << endl; 44 | words2.push_back("summer"); 45 | cout << words2.size() << endl; 46 | printVector(words2); 47 | 48 | // remove a word from the back of words2 49 | cout << words2.size() << endl; 50 | words2.pop_back(); 51 | cout << words2.size() << endl; 52 | printVector(words2); 53 | 54 | // check to see if words2 is empty or not? 55 | cout << words2.empty() << endl; 56 | words2.clear(); 57 | cout << words2.empty() << endl; 58 | 59 | 60 | return 0; 61 | } 62 | 63 | void printTwoDVector(vector> v) { 64 | int i = 0, j = 0; 65 | vector temp; 66 | 67 | for (i = 0; i < v.size(); i++) { 68 | temp = v.at(i); 69 | for (j = 0; j < temp.size(); j++) { 70 | cout << temp.at(j) << " "; 71 | } 72 | cout << endl; 73 | } 74 | 75 | } 76 | 77 | void printVector(vector v) { 78 | int i = 0; 79 | 80 | for (i = 0; i < v.size(); i++) { 81 | cout << v.at(i) << " "; 82 | } 83 | cout << endl; 84 | } 85 | --------------------------------------------------------------------------------