├── .editorconfig ├── .gitignore ├── 00_intro ├── practice │ └── задачи.md └── seminar │ └── materials.md ├── 01_numeral_systems ├── practice │ └── задачи.md └── seminar │ └── materials.md ├── 02_types_operators_statements ├── practice │ ├── solutions │ │ ├── task_01.cpp │ │ ├── task_02.cpp │ │ ├── task_03.cpp │ │ ├── task_04.cpp │ │ ├── task_05.cpp │ │ ├── task_06.cpp │ │ ├── task_07.cpp │ │ ├── task_08.cpp │ │ ├── task_09.cpp │ │ └── task_10.cpp │ └── задачи.md └── seminar │ ├── block_diagram.png │ ├── conditional_statement.cpp │ ├── materials.md │ ├── operators.cpp │ └── variables_types.cpp ├── 03_execution_flow_control ├── practice │ ├── solutions │ │ ├── task_01.cpp │ │ ├── task_02.cpp │ │ ├── task_03.cpp │ │ ├── task_04.cpp │ │ ├── task_05.cpp │ │ ├── task_06.cpp │ │ ├── task_07.cpp │ │ ├── task_08.cpp │ │ ├── task_09.cpp │ │ ├── task_10.cpp │ │ ├── task_11.cpp │ │ ├── task_12.cpp │ │ └── task_13.cpp │ └── задачи.md └── seminar │ ├── basic_loops.cpp │ ├── bitwise_operators.cpp │ ├── enum_switch.cpp │ ├── for_loop_diagram.png │ ├── materials.md │ └── while_loop_diagram.png ├── 04_scopes_nested_loops ├── practice │ ├── task_01.cpp │ ├── task_02.cpp │ ├── task_03.cpp │ ├── task_04.cpp │ ├── task_05.cpp │ ├── task_06.cpp │ ├── task_07.cpp │ ├── task_08.cpp │ └── задачи.md └── seminar │ ├── double_comparison.cpp │ ├── input_output_manipulations.cpp │ ├── materials.md │ ├── nested_loops.cpp │ └── scopes.cpp ├── 05_functions ├── practice │ ├── solutions.cpp │ └── задачи.md └── seminar │ ├── ascii_table_function.cpp │ ├── basic_functions.cpp │ ├── materials.md │ └── scopes.cpp ├── 06_functions_array_basics ├── practice │ ├── solutions.cpp │ └── задачи.md └── seminar │ ├── advanced_functions.cpp │ ├── array_basics.cpp │ └── materials.md ├── 07_array_algos ├── practice │ ├── solutions.cpp │ └── задачи.md └── seminar │ ├── eratosthenes_sieve.cpp │ ├── materials.md │ └── searching_sorting.cpp ├── 08_multidimensional_arrays ├── practice │ ├── solutions.cpp │ └── задачи.md └── seminar │ ├── materials.md │ └── matrices.cpp ├── 09_memory_management ├── practice │ ├── solutions_01-04.cpp │ ├── solutions_05-06.cpp │ └── задачи.md └── seminar │ ├── dynamic_array.cpp │ ├── dynamic_matrix.cpp │ ├── materials.md │ ├── memory_classes.cpp │ ├── pointers_arrays.cpp │ ├── pointers_basics.cpp │ └── references_basics.cpp ├── 10_strings ├── practice │ ├── strings_advanced │ │ ├── one_time_pad.txt │ │ ├── solution_01.cpp │ │ ├── solution_02.cpp │ │ ├── solution_03.cpp │ │ ├── solution_04.cpp │ │ ├── solution_05.cpp │ │ ├── solution_06.cpp │ │ └── задачи.md │ └── strings_basics │ │ ├── solutions.cpp │ │ └── задачи.md └── seminar │ ├── materials.md │ ├── string_basics.cpp │ └── string_standard_lib.cpp ├── 11_recursion ├── practice │ ├── recursion_advanced │ │ ├── solution_01.cpp │ │ ├── solution_02.cpp │ │ ├── solution_03.cpp │ │ ├── solution_04.cpp │ │ ├── solution_05.cpp │ │ └── задачи.md │ └── recursion_basic │ │ ├── solutions_01-02.cpp │ │ ├── solutions_03-04.cpp │ │ ├── solutions_05-06.cpp │ │ ├── solutions_07-08.cpp │ │ └── задачи.md └── seminar │ ├── materials.md │ ├── recursion_basics.cpp │ └── recursive_binary_search.cpp ├── 12_function_pointers ├── practice │ ├── solution_01.cpp │ ├── solution_02.cpp │ ├── solution_03.cpp │ ├── solution_04.cpp │ └── задачи.md └── seminar │ ├── basic_example.cpp │ ├── calculator.cpp │ ├── materials.md │ └── pipeline.cpp ├── 13_preprocessor_cmd_line ├── command_line.cpp ├── materials.md ├── predefined_macros.cpp └── preprocessor.cpp ├── 14_small_project ├── helpers.cpp ├── helpers.h ├── materials.md └── maze.cpp ├── README.md ├── practical_tips ├── debugging_tips │ └── debugger.md └── visual_studio_tips │ ├── vs-create-cpp-file.gif │ └── vs-create-project.gif └── res └── mushroom.png /.editorconfig: -------------------------------------------------------------------------------- 1 | # EditorConfig is awesome: https://EditorConfig.org 2 | 3 | # top-most EditorConfig file 4 | root = true 5 | 6 | # Unix-style newlines with a newline ending every file 7 | [*] 8 | charset = utf-8 9 | trim_trailing_whitespace = true 10 | end_of_line = lf 11 | insert_final_newline = true 12 | 13 | # C/C++ source files 14 | [*.{c,h,cpp,hpp}] 15 | indent_style = tab 16 | indent_size = 4 17 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Compiled Object files 2 | *.slo 3 | *.lo 4 | *.o 5 | *.obj 6 | 7 | # Precompiled Headers 8 | *.gch 9 | *.pch 10 | 11 | # Compiled Dynamic libraries 12 | *.so 13 | *.dylib 14 | *.dll 15 | 16 | # Fortran module files 17 | *.mod 18 | *.smod 19 | 20 | # Compiled Static libraries 21 | *.lai 22 | *.la 23 | *.a 24 | *.lib 25 | 26 | # Executables 27 | *.exe 28 | *.out 29 | *.app 30 | 31 | # Project files 32 | *.layout 33 | *.depend 34 | 35 | # Test project dir 36 | /example/* 37 | 38 | # Old examples, pending to be added 39 | /archive 40 | 41 | # VS code stuff 42 | .vscode/ 43 | -------------------------------------------------------------------------------- /00_intro/practice/задачи.md: -------------------------------------------------------------------------------- 1 | # **Задачи - подготовка** 2 | 3 | Инсталирайте си "интегрирана среда за разработка" (IDE). 4 | 5 | под Windows: 6 | - [Visual Studio](https://www.fmi.uni-sofia.bg/bg/node/8261) + [install C++](https://docs.microsoft.com/en-us/cpp/build/vscpp-step-0-installation?view=vs-2019) 7 | 8 | под Linux/MacOS: 9 | - [Code::Blocks](http://www.codeblocks.org/downloads) 10 | - [Visual Studio Code](https://code.visualstudio.com/docs/languages/cpp) 11 | 12 | -------------------------------------------------------------------------------- /00_intro/seminar/materials.md: -------------------------------------------------------------------------------- 1 | ## Intro 2 | 3 | ### Who are we? 4 | [Ivan](https://www.linkedin.com/in/ivan-filipov-v11/)
5 | [Kristian](https://www.linkedin.com/in/kristian-krastev-666649169/) 6 | 7 | 8 | ### Brief talk about education. 9 | - university vs IT-academies (pros and cons) 10 | 11 | ### What we are going to learn from that course? 12 | - concepts - ["Imperative programming"](https://en.wikipedia.org/wiki/Imperative_programming) & ["Structured programming"](https://en.wikipedia.org/wiki/Structured_programming) 13 | - to think logical and apply mathematics in practice 14 | - general knowledge in the area of informatics 15 | 16 | ### Why C/C++? 17 | - [aren't they outdated?](https://spectrum.ieee.org/computing/software/the-top-programming-languages-2019) 18 | - [how are they compared to other programming languages](https://www.tiobe.com/tiobe-index/) 19 | - [their application in the real world](https://www.invensis.net/blog/it/applications-of-c-c-plus-plus-in-the-real-world/) 20 | 21 | ### What kind of programs we are going to implement? 22 | - [console applications](https://en.wikipedia.org/wiki/Console_application) 23 | 24 | ### Where to find information about the course? 25 | - [moolde 2019-2020](https://learn.fmi.uni-sofia.bg/course/view.php?id=5453) 26 | 27 | ### Which books to read? 28 | - [The C programming language](https://en.wikipedia.org/wiki/The_C_Programming_Language) - bulgarian edition can be found in the FMI's bookshop 29 | - C++ Without Fear 30 | - Programming - Principles and Practice Using C++ 31 | -------------------------------------------------------------------------------- /01_numeral_systems/practice/задачи.md: -------------------------------------------------------------------------------- 1 | # **Задачи - бройни системи** 2 | 3 | 1. Пресметнете (на листче): 4 | 5 | ``` 6 | 2543(10) = ?(2) 7 | 485(10) = ?(2) 8 | 1024(10) = ?(2) 9 | 10 | 101011(2) = ?(10) 11 | 110100101(2) = ?(10) 12 | 010111010(2) = ?(10) 13 | 14 | 101010110110(2) = ?(16) 15 | 2164(10) = ?(16) 16 | 17 | 10101(2) | 110100(2) = ?(2) 18 | 1101(2) & 1010(2) = ?(2) 19 | !101010101(2) = ?(2) 20 | ``` 21 | --- 22 | 2. Проверете си сметките с калкулатор (в programmer режим). 23 | --- 24 | 3. Разгледайте съдържането на произволен файл със 25 | binary/hex editor. 26 | - под Windows от Visual Studio -> File -> Open -> File -> Open with -> Binary Editor 27 | - под Linux: `$hexdump -C ` 28 | --- 29 | 4. Нипишете програма на C++, която отпечатва името и 30 | факултетния ви номер на екрана. 31 | -------------------------------------------------------------------------------- /01_numeral_systems/seminar/materials.md: -------------------------------------------------------------------------------- 1 | ## Numeral systems 2 | 3 | ### But, first - a history lesson. 4 | - [History of computing hardware](https://en.wikipedia.org/wiki/History_of_computing_hardware) 5 | - Notable people: 6 | - [Charles Babbage](https://en.wikipedia.org/wiki/Charles_Babbage) 7 | - [Ada Lovelace](https://en.wikipedia.org/wiki/Ada_Lovelace) 8 | - [Джон Атанасов](https://bg.wikipedia.org/wiki/%D0%94%D0%B6%D0%BE%D0%BD_%D0%90%D1%82%D0%B0%D0%BD%D0%B0%D1%81%D0%BE%D0%B2) 9 | - [Dennis Ritchie](https://en.wikipedia.org/wiki/Dennis_Ritchie) 10 | - [Ken Thompson](https://en.wikipedia.org/wiki/Ken_Thompson) 11 | - [Bjarne Stroustrup](https://en.wikipedia.org/wiki/Bjarne_Stroustrup) 12 | 13 | ## 14 | [Numeral systems](https://en.wikipedia.org/wiki/Numeral_system)
15 | [Representation of numbers](https://www.swarthmore.edu/NatSci/echeeve1/Ref/BinaryMath/NumSys.html) 16 | -------------------------------------------------------------------------------- /02_types_operators_statements/practice/solutions/task_01.cpp: -------------------------------------------------------------------------------- 1 | /**************************************************************************** 2 | * This file is part of the "Introduction to programming" course. FMI 2019/20 3 | *****************************************************************************/ 4 | 5 | /** 6 | * @file task_01.cpp 7 | * @author Ivan Filipov 8 | * @date 10.2019 9 | * @brief Solution for task 1 from practice 2. 10 | */ 11 | 12 | #include 13 | 14 | int main() { 15 | 16 | short int num; 17 | 18 | // read input 19 | std::cout << "Enter a three-digit number: " << std::endl; 20 | std::cin >> num; 21 | 22 | // validate input 23 | if (num < 100 || num > 999) { 24 | std::cout << "Invalid input!" << std::endl; 25 | return 1; // exit the program 26 | } 27 | 28 | // output results 29 | std::cout << num % 10 // last digit 30 | << (num / 10) % 10 // then the middle digit 31 | << num / 100 // and the first digit 32 | << std::endl; 33 | return 0; 34 | } 35 | -------------------------------------------------------------------------------- /02_types_operators_statements/practice/solutions/task_02.cpp: -------------------------------------------------------------------------------- 1 | /**************************************************************************** 2 | * This file is part of the "Introduction to programming" course. FMI 2019/20 3 | *****************************************************************************/ 4 | 5 | /** 6 | * @file task_02.cpp 7 | * @author Vasilena Peycheva 8 | * @author Ivan Filipov 9 | * @date 10.2019 10 | * @brief Solution for task 2 from practice 2. 11 | */ 12 | 13 | #include 14 | 15 | int main() { 16 | 17 | bool a, b; 18 | 19 | // read input 20 | std::cout << "a = "; 21 | std::cin >> a; 22 | std::cout << "b = "; 23 | std::cin >> b; 24 | 25 | // output results 26 | std::cout << "a & b = " << (a & b) << std::endl; 27 | std::cout << "a | b = " << (a | b) << std::endl; 28 | std::cout << "a ^ b = " << (a ^ b) << std::endl; 29 | 30 | return 0; 31 | } 32 | -------------------------------------------------------------------------------- /02_types_operators_statements/practice/solutions/task_03.cpp: -------------------------------------------------------------------------------- 1 | /**************************************************************************** 2 | * This file is part of the "Introduction to programming" course. FMI 2019/20 3 | *****************************************************************************/ 4 | 5 | /** 6 | * @file task_03.cpp 7 | * @author Vasilena Peycheva 8 | * @author Ivan Filipov 9 | * @date 10.2019 10 | * @brief Solution for task 3 from practice 2. 11 | */ 12 | 13 | #include 14 | 15 | int main() { 16 | 17 | int a, b, c; 18 | std::cin >> a >> b >> c; 19 | std::cout << "Triangle with sides (" << a << ", " << b << ", " << c << ") - "; 20 | 21 | if ((a > 0 && b > 0 && c > 0) && // check all positive 22 | (a + b > c) && (b + c > a) && (a + c > b)) { // and the triangle inequality rule 23 | std::cout << "exists!" << std::endl; 24 | } else { 25 | std::cout << "doesn't exist!" << std::endl; 26 | } 27 | 28 | return 0; 29 | } 30 | -------------------------------------------------------------------------------- /02_types_operators_statements/practice/solutions/task_04.cpp: -------------------------------------------------------------------------------- 1 | /**************************************************************************** 2 | * This file is part of the "Introduction to programming" course. FMI 2019/20 3 | *****************************************************************************/ 4 | 5 | /** 6 | * @file task_04.cpp 7 | * @author Vasilena Peycheva 8 | * @author Ivan Filipov 9 | * @date 10.2019 10 | * @brief Solution for task 4 from practice 2. 11 | */ 12 | 13 | #include 14 | #include // std::sqrt - gives the square root of a number 15 | 16 | int main() { 17 | 18 | // by given side and height 19 | unsigned short side, height; 20 | std::cout << "Input side: "; 21 | std::cin >> side; 22 | std::cout << "Input height: "; 23 | std::cin >> height; 24 | float area = (side * height) / 2.0f; 25 | std::cout << "Area: " << area << std::endl; 26 | 27 | // by given three valid sides 28 | unsigned short a, b, c; 29 | std::cout << "Input sides: "; 30 | std::cin >> a >> b >> c; 31 | float semi_per = (a + b + c) / 2.0f; // calculate the semi-parameter 32 | // calculate the area, using Heron's formula 33 | area = std::sqrt(semi_per * (semi_per - a) * (semi_per - b) * (semi_per - c)); 34 | std::cout << "Area: " << area << std::endl; 35 | 36 | return 0; 37 | } 38 | -------------------------------------------------------------------------------- /02_types_operators_statements/practice/solutions/task_05.cpp: -------------------------------------------------------------------------------- 1 | /**************************************************************************** 2 | * This file is part of the "Introduction to programming" course. FMI 2019/20 3 | *****************************************************************************/ 4 | 5 | /** 6 | * @file task_05.cpp 7 | * @author Vasilena Peycheva 8 | * @author Ivan Filipov 9 | * @date 10.2019 10 | * @brief Solution for task 5 from practice 2. 11 | */ 12 | 13 | #include 14 | 15 | int main() { 16 | 17 | int a, b, temp; 18 | std::cout << "a = "; 19 | std::cin >> a; 20 | std::cout << "b = "; 21 | std::cin >> b; 22 | 23 | // swap with temporary variable 24 | temp = a; 25 | a = b; 26 | b = temp; 27 | 28 | /* swap without help variable, 29 | using a simple arithmetic trick 30 | a += b; 31 | b = a - b; 32 | a = a - b; 33 | */ 34 | std::cout << std::endl; 35 | std::cout << "a = " << a << std::endl; 36 | std::cout << "b = " << b << std::endl; 37 | 38 | return 0; 39 | } 40 | -------------------------------------------------------------------------------- /02_types_operators_statements/practice/solutions/task_06.cpp: -------------------------------------------------------------------------------- 1 | /**************************************************************************** 2 | * This file is part of the "Introduction to programming" course. FMI 2019/20 3 | *****************************************************************************/ 4 | 5 | /** 6 | * @file task_06.cpp 7 | * @author Vasilena Peycheva 8 | * @author Ivan Filipov 9 | * @date 10.2019 10 | * @brief Solution for task 6 from practice 2. 11 | */ 12 | 13 | #include 14 | 15 | int main() { 16 | 17 | int p, q; 18 | std::cout << "p = "; 19 | std::cin >> p; 20 | std::cout << "q cannot be 0! But try if you dare..." << std::endl; 21 | std::cout << "q = "; 22 | std::cin >> q; 23 | 24 | std::cout << "quotient: " << p / q << std::endl; 25 | std::cout << "remainder: " << p % q << std::endl; 26 | 27 | return 0; 28 | } 29 | -------------------------------------------------------------------------------- /02_types_operators_statements/practice/solutions/task_07.cpp: -------------------------------------------------------------------------------- 1 | /**************************************************************************** 2 | * This file is part of the "Introduction to programming" course. FMI 2019/20 3 | *****************************************************************************/ 4 | 5 | /** 6 | * @file task_07.cpp 7 | * @author Petar Armyanov 8 | * @author Ivan Filipov 9 | * @date 10.2019 10 | * @brief Solution for task 7 from practice 2. 11 | */ 12 | 13 | #include 14 | #include 15 | 16 | int main() { 17 | 18 | int a, b, c; 19 | // input read 20 | std::cout << "a = "; 21 | std::cin >> a; 22 | std::cout << "b = "; 23 | std::cin >> b; 24 | std::cout << "c = "; 25 | std::cin >> c; 26 | 27 | if ((a == 0) || (b == 0) || (c == 0)) { 28 | std::cout << "not a valid quadratic equation!" << std::endl; 29 | return 1; 30 | } 31 | 32 | // calculate the discriminant 33 | double disc = b * b - (4 * a * c); 34 | if (disc < 0) { 35 | // negative discriminant 36 | std::cout << "The equation has no real roots!" << std::endl; 37 | } else if (disc > 0) { 38 | // positive discriminant 39 | double x1, x2; 40 | x1 = (-b + sqrt(disc)) / (2 * a); 41 | x2 = -x1 - b/a; // Viète's formula 42 | std::cout << "The equation " << a << "x^2 + " << b << "x + " << c << " = 0" 43 | << " has two roots: " << x1 << " and " << x2 << std::endl; 44 | } else { 45 | // zero discriminant 46 | double x = -b / (2 * a); 47 | std::cout << "The equation " << a << "x^2 + " << b << "x + " << c << " = 0" 48 | << " has one double root: " << x << std::endl; 49 | } 50 | 51 | return 0; 52 | } 53 | -------------------------------------------------------------------------------- /02_types_operators_statements/practice/solutions/task_08.cpp: -------------------------------------------------------------------------------- 1 | /**************************************************************************** 2 | * This file is part of the "Introduction to programming" course. FMI 2019/20 3 | *****************************************************************************/ 4 | 5 | /** 6 | * @file task_08.cpp 7 | * @author Vasilena Peycheva 8 | * @author Ivan Filipov 9 | * @date 10.2019 10 | * @brief Solution for task 8 from practice 2. 11 | */ 12 | 13 | #include 14 | 15 | int main() { 16 | 17 | int number; 18 | std::cout << "Enter a number: "; 19 | std::cin >> number; 20 | std::cout << "abs(" << number << ") = "; 21 | 22 | if (number < 0) { 23 | std::cout << -number << std::endl; 24 | } else { 25 | std::cout << number << std::endl; 26 | } 27 | 28 | return 0; 29 | } 30 | -------------------------------------------------------------------------------- /02_types_operators_statements/practice/solutions/task_09.cpp: -------------------------------------------------------------------------------- 1 | /**************************************************************************** 2 | * This file is part of the "Introduction to programming" course. FMI 2019/20 3 | *****************************************************************************/ 4 | 5 | /** 6 | * @file task_09.cpp 7 | * @author Vasilena Peycheva 8 | * @author Ivan Filipov 9 | * @date 10.2019 10 | * @brief Solution for task 9 from practice 2. 11 | */ 12 | 13 | #include 14 | #include 15 | 16 | int main() { 17 | 18 | int x1, y1, x2, y2; 19 | 20 | std::cout << "Input x, y for point A: "; 21 | std::cin >> x1 >> y1; 22 | std::cout << "Input x, y for point B: "; 23 | std::cin >> x2 >> y2; 24 | 25 | std::cout << "Distance between A(" 26 | << x1 << ", " << y1 27 | << ") and B(" 28 | << x2 << ", " << y2 29 | << ") is " 30 | << std::sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)) 31 | << std::endl; 32 | 33 | return 0; 34 | } 35 | -------------------------------------------------------------------------------- /02_types_operators_statements/practice/solutions/task_10.cpp: -------------------------------------------------------------------------------- 1 | /**************************************************************************** 2 | * This file is part of the "Introduction to programming" course. FMI 2019/20 3 | *****************************************************************************/ 4 | 5 | /** 6 | * @file task_10.cpp 7 | * @author Ivan Filipov 8 | * @date 10.2019 9 | * @brief Solution for task 9 from practice 2. 10 | */ 11 | 12 | #include 13 | #include 14 | 15 | int main() { 16 | 17 | int x, y; 18 | 19 | std::cout << "Input x, y for the point : "; 20 | std::cin >> x >> y; 21 | bool is_inside = false; // assume, that the point is outside 22 | 23 | if (y > 0) { 24 | // we should check if we are in the semi-circle 25 | int r = 2 * 2; // circle's radius (powered by 2, to avoid floating point calculations) 26 | // the distance from the point to (0, 0) [where the center of the circle is] 27 | int dist_squared = (x * x) + (y * y); 28 | if (dist_squared <= r) { 29 | is_inside = true; 30 | } 31 | 32 | } else { 33 | // we should check if we are in the rectangle 34 | if ((std::abs(x) <= 1) && 35 | (std::abs(y) <= 4)) { 36 | is_inside = true; 37 | } 38 | } 39 | 40 | std::cout << "The point is "; 41 | if (is_inside) { 42 | std::cout << "inside!" << std::endl; 43 | } else { 44 | std::cout << "outside!" << std::endl; 45 | } 46 | 47 | return 0; 48 | } 49 | -------------------------------------------------------------------------------- /02_types_operators_statements/practice/задачи.md: -------------------------------------------------------------------------------- 1 | # **Задачи - типове и оператори** 2 | 3 | 1. Обърнете (swap) цифрите на трицифрено число, прочетено от клавиатурата. 4 | 5 | Пример: 6 | ``` 7 | Вход: 827 8 | Изход: 728 9 | ``` 10 | 2. От стандартния вход се прочитат две булеви променливи,
11 | на стандартния изход се отпечатват резултатите от
12 | приложените логически операции върху тях. (&, | , ^)
13 | 14 | 3. ​Да​ ​се​ ​състави​ ​програма,​ ​която​ ​по​ въведени​
15 | 3​ ​променливи​ ​от​ ​конзолата - (a,​ ​b,​ ​c)​
16 | проверява​ ​дали​ ​съществува​ ​триъгълник​
17 | ​с​ъс страни ​въведените стойности.
18 | # 19 | 20 | 4. Да се напише програма, която намира лицето на триъгълник по дадени: 21 | - дължини на страна и височина към нея 22 | - три страни 23 | # 24 | 25 | 5. По въведени от клавиатурата стойности на променливите a и b,
разменя стойностите им и ги отпечатва на екрана. 26 | 27 | Пример: 28 | ``` 29 | Вход: 5 7 30 | Изход: 7 5 31 | ``` 32 | # 33 | 34 | 6. От конзолата се прочитат две цели 4-байтови числа “p” и “q”.
35 | Да се изкара на конзолата цялата част “quotient” и остатъка “remainder
36 | на частното, получено при делението на „p“ с “q”. 37 | 38 | Пример: 39 | ``` 40 | Вход: 4 2 41 | Изход: quotient = 2, remainder = 0 42 | ``` 43 | # 44 | 45 | 7. От конзолата се прочитат 3 цели числа, а,b и c, които представляват
46 | коефициенти на квадратно уравнение. Да се намерят неговите корени,
47 | и да се отпечатат на екрана. 48 | # 49 | 50 | 8. Да​ ​се​ ​състави​ ​програма,​ ​която​ ​по​ ​​въведено​ цяло 4-байтово​ ​число,
51 | изкарва на​ ​конзолата​ ​абсолютната​ ​му​ стойност.​ 52 | # 53 | 54 | 9. От конзолата се прочитат 4 цели числа, като първите две числа
55 | представляват координатите на eдна точка,
56 | а вторите две числа - координатите на друга точка.
57 | Да се изчисли разстоянието между двете точки и резултата да се изведе на екрана. 58 | 59 | **Пример:** 60 | ``` 61 | Вход: 2 1 4 5 // A(x1 = 2, y1 = 1), B(x2 = 4, y2 =5) 62 | Изход: distance = 4.47214 63 | ``` 64 | 65 | 10. Дадена е декартова координатна система,
66 | проверете дали точка с координати х, у (две цели числа)
67 | се намира вътре в защрихованата част на фигурата. 68 | 69 | ![Mushroom](/res/mushroom.png) 70 | 71 | -------------------------------------------------------------------------------- /02_types_operators_statements/seminar/block_diagram.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/VasiPeycheva/Introduction-to-Programming--2017-2020/b4ea6adf9e76b55724d3b914900f953f416796be/02_types_operators_statements/seminar/block_diagram.png -------------------------------------------------------------------------------- /02_types_operators_statements/seminar/conditional_statement.cpp: -------------------------------------------------------------------------------- 1 | /**************************************************************************** 2 | * This file is part of the "Introduction to programming" course. FMI 2019/20 3 | *****************************************************************************/ 4 | 5 | /** 6 | * @file variables_types.cpp 7 | * @author Ivan Filipov 8 | * @date 10.2019 9 | * @brief A simple program 10 | * that uses a conditional statement 11 | * if / else. 12 | * @see block_diagram 13 | */ 14 | 15 | #include 16 | 17 | int main() { 18 | 19 | // read a number 20 | int x; 21 | std::cin >> x; 22 | 23 | // check if it is an even or odd 24 | if (x % 2 == 0) { 25 | // if even -> divide it by 10 26 | x /= 10; 27 | } else { 28 | // if odd 29 | if (x > 100) { 30 | // odd and grater than 100 31 | x++; 32 | } else { 33 | // odd and less than 100 34 | x--; 35 | } 36 | } 37 | 38 | std::cout << x << std::endl; 39 | } 40 | -------------------------------------------------------------------------------- /02_types_operators_statements/seminar/materials.md: -------------------------------------------------------------------------------- 1 | ## C++ types, operators and statements 2 | --- 3 | 4 | [C++ program I/O](https://www.ntu.edu.sg/home/ehchua/programming/cpp/images/IOstreams.png)
5 | [The C++ compilation process](http://faculty.cs.niu.edu/~mcmahon/CS241/Notes/compile.html)
6 | 7 | --- 8 | 9 | [Structure of a C++ program](http://people.scs.carleton.ca/~dehne/projects/cpp-doc/tutorial/tut1-1.html)
10 | [Variables, data types, constants](http://people.scs.carleton.ca/~dehne/projects/cpp-doc/tutorial/tut1-2.html)
11 | [Operators](http://people.scs.carleton.ca/~dehne/projects/cpp-doc/tutorial/tut1-3.html)
12 | [Conditional structure: if and else](http://people.scs.carleton.ca/~dehne/projects/cpp-doc/tutorial/tut2-1.html) - _read first part only_ 13 | -------------------------------------------------------------------------------- /02_types_operators_statements/seminar/operators.cpp: -------------------------------------------------------------------------------- 1 | /**************************************************************************** 2 | * This file is part of the "Introduction to programming" course. FMI 2019/20 3 | *****************************************************************************/ 4 | 5 | /** 6 | * @file operators.cpp 7 | * @author Ivan Filipov 8 | * @date 10.2019 9 | * @brief C++ basic operators - 10 | * assignment, arithmetic, 11 | * logical, comparison, 12 | * increment/decrement. 13 | */ 14 | 15 | #include 16 | 17 | int main() { 18 | 19 | std::cout << "Assignment operator" << std::endl; 20 | int ii = 10; 21 | std::cout << "ii after initialize: " << ii << std::endl; 22 | ii = 20; 23 | std::cout << "ii after assigning value of 20: " << ii << std::endl; 24 | int iii = 30; 25 | ii = iii; 26 | std::cout << "ii after assigning the value of the variable iii: " << ii << std::endl; 27 | 28 | std::cout << std::endl << std::endl; 29 | 30 | std::cout << "Arithmetic operators" << std::endl; 31 | int i = 100 + 20; 32 | std::cout << "i = 100 + 20 = " << i << std::endl; 33 | int var = i - 10; 34 | std::cout << "var = i - 10 = " << var << std::endl; 35 | std::cout << "var * 3 = " << var * 3 << std::endl; 36 | 37 | int a = 19, b = 3; 38 | int c = a / b; 39 | int d = a % b; 40 | std::cout << "a = " << a << " b = " << b << std::endl; 41 | std::cout << "a / b = " << c << std::endl; 42 | std::cout << "a % b = " << d << std::endl; 43 | 44 | std::cout << std::endl << std::endl; 45 | 46 | std::cout << "Comparison operators" << std::endl; 47 | std::cout << "5 < 3? - " << (5 < 3) << std::endl; 48 | int h = 10, s = 11; 49 | std::cout << "h = " << h << " s = " << s << std::endl; 50 | std::cout << "h equal to s? - " << (h == s) << std::endl; 51 | std::cout << "h NOT equal to s? - " << (h != s) << std::endl; 52 | 53 | std::cout << std::endl << std::endl; 54 | 55 | std::cout << "Logical operators" << std::endl; 56 | int x = 10; 57 | std::cout << "x = " << x << std::endl; 58 | std::cout << "x less than 20 AND bigger than 0? - " 59 | << ((x < 20) && (x > 0)) << std::endl; 60 | 61 | std::cout << "x is 150 OR x is 10? - " 62 | << ((x == 150) || (x == 10)) << std::endl; 63 | 64 | std::cout << "NOT (x is 11)? - " 65 | << !(x == 11) << std::endl; 66 | 67 | // shorter forms: 68 | int j = 10; 69 | j += 1; // is same as: j = j + 1; 70 | j -= 10; // is same as: j = j - 10; 71 | j *= 4; // is same as: j = j * 4; 72 | j /= 2; // is same as: j = j / 2; 73 | 74 | bool flag = true; 75 | flag |= false; // is same as: flag = flag || false; 76 | 77 | std::cout << std::endl << std::endl; 78 | 79 | std::cout << "Increment/decrement operators" << std::endl; 80 | j = 20; 81 | std::cout << "j = " << j << std::endl; 82 | std::cout << "j++ = " << j++ << std::endl; 83 | std::cout << "j = " << j << std::endl; 84 | std::cout << "++j = " << ++j << std::endl; 85 | std::cout << "j = " << j << std::endl; 86 | 87 | std::cout << "j-- = " << j-- << std::endl; 88 | std::cout << "j = " << j << std::endl; 89 | std::cout << "--j = " << --j << std::endl; 90 | std::cout << "j = " << j << std::endl; 91 | 92 | return 0; 93 | } 94 | -------------------------------------------------------------------------------- /03_execution_flow_control/practice/solutions/task_01.cpp: -------------------------------------------------------------------------------- 1 | /**************************************************************************** 2 | * This file is part of the "Introduction to programming" course. FMI 2019/20 3 | *****************************************************************************/ 4 | 5 | /** 6 | * @file task_01.cpp 7 | * @author Ivan Filipov 8 | * @author Kristian Krastev 9 | * @date 11.2019 10 | * @brief Solution for task 1 from practice 3. 11 | */ 12 | 13 | #include 14 | 15 | int main() { 16 | 17 | unsigned int a, b, c; 18 | // read the numbers 19 | std::cin >> a >> b >> c; 20 | 21 | 22 | // create a compare tree with all possible outcomes -> 23 | // there are 3! = 6 total different relations 24 | if (a > b) { 25 | if (a > c) { // a is the largest one 26 | if (b > c) { 27 | std::cout << a << " > " << b << " > " << c << std::endl; 28 | } else { // b <= c 29 | std::cout << a << " > " << c << " >= " << b << std::endl; 30 | } 31 | } else { // a > b && a <= c 32 | std::cout << c << " >= " << a << " > " << b << std::endl; 33 | } 34 | } else { // a <= b 35 | if (b > c) { 36 | if (a > c) { 37 | std::cout << b << " >= " << a << " > " << c << std::endl; 38 | } else { 39 | std::cout << b << " > " << c << " >= " << a << std::endl; 40 | } 41 | } else { // b <= c 42 | std::cout << c << " >= " << b << " >= " << a << std::endl; 43 | } 44 | } 45 | 46 | return 0; 47 | } 48 | -------------------------------------------------------------------------------- /03_execution_flow_control/practice/solutions/task_02.cpp: -------------------------------------------------------------------------------- 1 | /**************************************************************************** 2 | * This file is part of the "Introduction to programming" course. FMI 2019/20 3 | *****************************************************************************/ 4 | 5 | /** 6 | * @file task_02.cpp 7 | * @author Ivan Filipov 8 | * @author Kristian Krastev 9 | * @date 11.2019 10 | * @brief Solution for task 2 from practice 3. 11 | */ 12 | 13 | #include 14 | 15 | // well known facts 16 | const int CARDS_COUNT = 52; 17 | const int CARDS_FROM_COLOR = 13; 18 | 19 | // valid only for MS (tested on MS-VS2017) 20 | #ifdef _WIN32 21 | #define CLUBS_SYMBOL "\x05" 22 | #define DIAMONDS_SYMBOL "\x04" 23 | #define HEARTS_SYMBOL "\x03" 24 | #define SPADES_SYMBOL "\x06" 25 | #else // on *NIX we can use UNICODE symbols 26 | #define CLUBS_SYMBOL "\xE2\x99\xA3" 27 | #define DIAMONDS_SYMBOL "\xE2\x99\xA6" 28 | #define HEARTS_SYMBOL "\xE2\x99\xA5" 29 | #define SPADES_SYMBOL "\xE2\x99\xA0" 30 | #endif // _WIN32 31 | 32 | enum card_colors { 33 | CLUBS_CLR, // = 0 34 | DIAMONDS_CLR, // = previous + 1 35 | HEARTS_CLR, 36 | SPADES_CLR 37 | }; 38 | 39 | int main() { 40 | 41 | unsigned int card_ind; 42 | 43 | do { 44 | 45 | std::cout << "Which card do you want to see?" << std::endl; 46 | std::cout << "Enter a value in [0; 51]" << std::endl; 47 | std::cin >> card_ind; 48 | 49 | // handle invalid input 50 | if (card_ind > CARDS_COUNT - 1) { 51 | std::cout << "Invalid input!" << std::endl 52 | << "Do you want to try again? - y/n" << std::endl; 53 | 54 | char choice; 55 | std::cin >> choice; 56 | 57 | if (choice == 'y') 58 | continue; // starting the loop from the beginning 59 | else { 60 | if (choice == 'n') 61 | std::cout << "Goodbye!" << std::endl; 62 | else 63 | std::cout << "Again invalid command, maybe we don't speak the same language?" << std::endl; 64 | 65 | return 1; // exit the program 66 | } 67 | 68 | } 69 | 70 | // we get here only on correct input 71 | 72 | unsigned int card_color = card_ind / CARDS_FROM_COLOR; // results in [0;3] 73 | unsigned int card_picture = card_ind % CARDS_FROM_COLOR; //results in [0;12] 74 | 75 | std::cout << "The chosen card is:" << std::endl; 76 | 77 | // plus 1, because it is easier to 'code' the cases 78 | card_picture += 1; 79 | switch (card_picture) { 80 | case 1: std::cout << 'A'; break; 81 | case 10: std::cout << "10"; break; 82 | case 11: std::cout << 'J'; break; 83 | case 12: std::cout << 'Q'; break; 84 | case 13: std::cout << 'K'; break; 85 | default: // all digits can be handled with a simple trick 86 | // we add the decimal value to the '0' ASCII code 87 | // the trick works, because '1' is the next symbol after '0' 88 | // '2' is '0' plus two and so on. 89 | std::cout << (char)('0' + card_picture); 90 | } 91 | 92 | // using the enumeration makes our own code much easier 93 | // to read and understand 94 | switch (card_color) { 95 | case CLUBS_CLR: std::cout << CLUBS_SYMBOL; break; 96 | case DIAMONDS_CLR: std::cout << DIAMONDS_SYMBOL; break; 97 | case HEARTS_CLR: std::cout << HEARTS_SYMBOL; break; 98 | case SPADES_CLR: std::cout << SPADES_SYMBOL; break; 99 | } 100 | 101 | // we have done our job 102 | std::cout << std::endl; 103 | break; 104 | 105 | } while (true); // endless loop - the only way to 'exit' the loop is by breaking it or using return 106 | 107 | return 0; 108 | } 109 | -------------------------------------------------------------------------------- /03_execution_flow_control/practice/solutions/task_03.cpp: -------------------------------------------------------------------------------- 1 | /**************************************************************************** 2 | * This file is part of the "Introduction to programming" course. FMI 2019/20 3 | *****************************************************************************/ 4 | 5 | /** 6 | * @file task_03.cpp 7 | * @author Ivan Filipov 8 | * @author Kristian Krastev 9 | * @date 11.2019 10 | * @brief Solution for task 3 from practice 3. 11 | */ 12 | 13 | #include 14 | 15 | int main() { 16 | 17 | unsigned int number; 18 | std::cin >> number; 19 | 20 | // sizeof() returns how many bytes is the passed type 21 | // we are traversing the bits from left to right 22 | for (short int i = (sizeof(unsigned int) * 8) - 1; i >= 0; i--) { 23 | // we create a "mask", which have only one "1" and many zeros, 24 | // the "1" is positioned on the i-th bit. 25 | std::cout << ((number & (1 << i)) ? '1' : '0'); 26 | 27 | if (i % 8 == 0 && i) std::cout << '\''; // print quotes for better readability 28 | } 29 | 30 | std::cout << std::endl; 31 | 32 | return 0; 33 | } 34 | -------------------------------------------------------------------------------- /03_execution_flow_control/practice/solutions/task_04.cpp: -------------------------------------------------------------------------------- 1 | /**************************************************************************** 2 | * This file is part of the "Introduction to programming" course. FMI 2019/20 3 | *****************************************************************************/ 4 | 5 | /** 6 | * @file task_04.cpp 7 | * @author Ivan Filipov 8 | * @author Kristian Krastev 9 | * @date 11.2019 10 | * @brief Solution for task 4 from practice 3. 11 | */ 12 | 13 | #include 14 | 15 | int main() { 16 | 17 | unsigned int A, a1, a2, a3; 18 | 19 | std::cout << "Input a number: "; 20 | std::cin >> A; 21 | std::cout << "Input 3 bit positions [0-31] (divided with spaces): "; 22 | std::cin >> a1 >> a2 >> a3; 23 | // we lift the bits by using | bitwise operator 24 | unsigned int A_prim = ((A | (1 << a1)) | (1 << a2)) | (1 << a3); 25 | std::cout << "The new integer is: " << A_prim << std::endl; 26 | std::cout << "A' - A = " << A_prim - A << std::endl; 27 | 28 | return 0; 29 | } 30 | -------------------------------------------------------------------------------- /03_execution_flow_control/practice/solutions/task_05.cpp: -------------------------------------------------------------------------------- 1 | /**************************************************************************** 2 | * This file is part of the "Introduction to programming" course. FMI 2019/20 3 | *****************************************************************************/ 4 | 5 | /** 6 | * @file task_05.cpp 7 | * @author Vasilena Peycheva 8 | * @author Kristian Krastev 9 | * @date 11.2019 10 | * @brief Solution for task 5 from practice 3. 11 | */ 12 | 13 | #include 14 | 15 | int main() { 16 | 17 | unsigned int n; 18 | std::cout << "Input a number: "; 19 | std::cin >> n; 20 | 21 | // hard way 22 | /*unsigned short first = 0, sec = 0; 23 | first |= (n >> 16) ; 24 | sec |= n; 25 | unsigned int n2 = 0; 26 | n2 = ((n2 | first) | ~sec);*/ 27 | 28 | // much easier approach 29 | unsigned short mask = 0xFFFF; 30 | std::cout << "Same number but with flipped first 16 bits: " << (n ^ mask) << std::endl; 31 | 32 | return 0; 33 | } 34 | -------------------------------------------------------------------------------- /03_execution_flow_control/practice/solutions/task_06.cpp: -------------------------------------------------------------------------------- 1 | /**************************************************************************** 2 | * This file is part of the "Introduction to programming" course. FMI 2019/20 3 | *****************************************************************************/ 4 | 5 | /** 6 | * @file task_06.cpp 7 | * @author Ivan Filipov 8 | * @author Kristian Krastev 9 | * @date 11.2019 10 | * @brief Solution for task 6 from practice 3. 11 | */ 12 | 13 | #include 14 | #include 15 | 16 | const short int TIMES_TO_SHIFT = 8; 17 | 18 | int main() { 19 | 20 | short int number; 21 | std::cin >> number; 22 | 23 | short int first_byte = (number & 0xFF); // get the first byte only with mask 24 | short int second_byte = (number >> TIMES_TO_SHIFT); // shift the number, so the first 8bits will be dropped 25 | 26 | short int res = ((first_byte << TIMES_TO_SHIFT) | second_byte); // combine the bytes with swapped positions 27 | std::cout << "Number with switched bytes: " << res; 28 | 29 | return 0; 30 | } 31 | 32 | 33 | -------------------------------------------------------------------------------- /03_execution_flow_control/practice/solutions/task_07.cpp: -------------------------------------------------------------------------------- 1 | /**************************************************************************** 2 | * This file is part of the "Introduction to programming" course. FMI 2019/20 3 | *****************************************************************************/ 4 | 5 | /* 6 | * @file task_07.cpp 7 | * @author Kristian Krastev 8 | * @date 11.2019 9 | * @brief Solution for task 7 from practice 3. 10 | */ 11 | 12 | #include 13 | 14 | int main() { 15 | 16 | int number; 17 | int previous; 18 | 19 | // we read the first number 20 | std::cin >> previous; 21 | int counter = 1; 22 | 23 | while (true) { 24 | std::cin >> number; 25 | 26 | // on every step we check if the next number is less that the previous one 27 | if (number < previous) 28 | break; 29 | 30 | // so that the next time we enter a new number, we got 31 | // access to the last one entered 32 | previous = number; 33 | counter++; 34 | } 35 | 36 | std::cout << std::endl << counter << std::endl; 37 | return 0; 38 | } 39 | -------------------------------------------------------------------------------- /03_execution_flow_control/practice/solutions/task_08.cpp: -------------------------------------------------------------------------------- 1 | /**************************************************************************** 2 | * This file is part of the "Introduction to programming" course. FMI 2019/20 3 | *****************************************************************************/ 4 | 5 | /** 6 | * @file task_08.cpp 7 | * @author Vasilena Peycheva 8 | * @author Ivan Filipov 9 | * @date 11.2019 10 | * @brief Solution for task 8 from practice 2. 11 | */ 12 | 13 | #include 14 | 15 | int main() { 16 | 17 | unsigned int n; 18 | unsigned int sum = 0; 19 | std::cin >> n; 20 | 21 | for (unsigned int i = 1; i <= n; i++) { 22 | sum += i; 23 | } 24 | 25 | // using Gauss's formula; be careful, an overflow may occur 26 | unsigned int gauss_sum = ((n + 1) * n) / 2; 27 | 28 | std::cout << "Sum = " << sum << std::endl 29 | << "With maths: " << gauss_sum << std::endl; 30 | 31 | return 0; 32 | } 33 | -------------------------------------------------------------------------------- /03_execution_flow_control/practice/solutions/task_09.cpp: -------------------------------------------------------------------------------- 1 | /**************************************************************************** 2 | * This file is part of the "Introduction to programming" course. FMI 2019/20 3 | *****************************************************************************/ 4 | 5 | /** 6 | * @file task_09.cpp 7 | * @author Vasilena Peycheva 8 | * @author Kristian Krastev 9 | * @date 11.2019 10 | * @brief Solution for task 9 from practice 3. 11 | */ 12 | 13 | #include 14 | 15 | int main() { 16 | 17 | unsigned int n; 18 | int current_num, sum = 0; 19 | 20 | std::cin >> n; 21 | 22 | for (unsigned int i = 0; i < n; i++) { 23 | std::cin >> current_num; // reading the new num 24 | sum += current_num; // adding it to the sum 25 | } 26 | 27 | // we should 'cast' our variables to double in oreder to calculate the exact result 28 | std::cout << "The average is: " << (double)sum / n << std::endl; 29 | 30 | return 0; 31 | } 32 | -------------------------------------------------------------------------------- /03_execution_flow_control/practice/solutions/task_10.cpp: -------------------------------------------------------------------------------- 1 | /**************************************************************************** 2 | * This file is part of the "Introduction to programming" course. FMI 2019/20 3 | *****************************************************************************/ 4 | 5 | /** 6 | * @file task_10.cpp 7 | * @author Ivan Filipov 8 | * @author Kristian Krastev 9 | * @date 11.2019 10 | * @brief Solution for task 10 from practice 3. 11 | */ 12 | 13 | #include 14 | #include // std::log10() 15 | 16 | 17 | int main() { 18 | 19 | unsigned int number; 20 | unsigned int digitsCount = 0; 21 | 22 | std::cin >> number; 23 | 24 | // using some math 25 | std::cout << "With math: " << (unsigned int)(1 + std::log10(number)) << std::endl; 26 | 27 | while (number) { // same as number != 0 28 | digitsCount++; 29 | number /= 10; 30 | } 31 | 32 | std::cout << "With simple loop: " << digitsCount << std::endl; 33 | 34 | return 0; 35 | } 36 | -------------------------------------------------------------------------------- /03_execution_flow_control/practice/solutions/task_11.cpp: -------------------------------------------------------------------------------- 1 | /**************************************************************************** 2 | * This file is part of the "Introduction to programming" course. FMI 2019/20 3 | *****************************************************************************/ 4 | 5 | /** 6 | * @file task_11.cpp 7 | * @author Vasilena Peycheva 8 | * @date 11.2019 9 | * @brief Solution for task 11 from practice 3. 10 | */ 11 | 12 | #include 13 | 14 | int main() { 15 | 16 | unsigned int number; 17 | std::cin >> number; 18 | 19 | while (number) { 20 | // we print the last digit 21 | std::cout << number % 10 << ' '; 22 | // then we 'cut' it from the number 23 | number /= 10; 24 | } 25 | 26 | return 0; 27 | } 28 | -------------------------------------------------------------------------------- /03_execution_flow_control/practice/solutions/task_12.cpp: -------------------------------------------------------------------------------- 1 | /**************************************************************************** 2 | * This file is part of the "Introduction to programming" course. FMI 2019/20 3 | *****************************************************************************/ 4 | 5 | /** 6 | * @file task_12.cpp 7 | * @author Ivan Filipov 8 | * @date 11.2019 9 | * @brief Solution for task 12 from practice 3. 10 | */ 11 | 12 | #include 13 | 14 | // calculated by just making tests 15 | const unsigned short N_LIMIT = 23; 16 | 17 | int main() { 18 | 19 | unsigned short n; 20 | unsigned long long fact = 1; 21 | 22 | std::cin >> n; 23 | 24 | if (n > N_LIMIT) { 25 | std::cout << "Can calculate only to " << N_LIMIT << "! which equals to "; 26 | n = N_LIMIT; 27 | } 28 | 29 | for (short i = 2; i <= n; i++) 30 | fact *= i; 31 | 32 | std::cout << fact << std::endl; 33 | 34 | return 0; 35 | } 36 | -------------------------------------------------------------------------------- /03_execution_flow_control/practice/solutions/task_13.cpp: -------------------------------------------------------------------------------- 1 | /**************************************************************************** 2 | * This file is part of the "Introduction to programming" course. FMI 2019/20 3 | *****************************************************************************/ 4 | 5 | /** 6 | * @file task_13.cpp 7 | * @author Ivan Filipov 8 | * @date 11.2019 9 | * @brief Solution for task 13 from practice 3. 10 | */ 11 | 12 | #include 13 | #include 14 | 15 | int main() { 16 | 17 | unsigned long long N; 18 | std::cin >> N; 19 | std::cout << "N is "; 20 | 21 | //is 1 really a prime ? 22 | if (N <= 2) 23 | std::cout << "prime!" << std::endl; 24 | 25 | unsigned long long sq = std::sqrt(N); 26 | 27 | // trying to find a number which can divide the given one 28 | // if there isn't such a number, than the given is prime 29 | for (unsigned long long i = 2; i <= sq; i++) { 30 | if (N % i == 0) { 31 | std::cout << "compose!" << std::endl; 32 | return 0; // exit the program 33 | } 34 | } 35 | 36 | std::cout << "prime!" << std::endl; 37 | 38 | return 0; 39 | } 40 | -------------------------------------------------------------------------------- /03_execution_flow_control/practice/задачи.md: -------------------------------------------------------------------------------- 1 | # **Задачи - побитови операции, цикли** 2 | 3 | *забележка: не е нужно да решавате задачите в дадената наредба* 4 | 5 | 1. Прочитат се 3 цели положителни числа - a, b, c,
6 | програмaта изкарва на стандартния си изход числата във низходящ ред. 7 | 8 | Пример: 9 | ``` 10 | Вход: 23 7 11 11 | Изход: 23 11 7 12 | ``` 13 | # 14 | 2. Нека е дадена стандартна колода от карти съдържаща всички карти от
15 | всички бои - общо 52 на брой. Приемаме, че картите са подредени както в
16 | неразопаковано ново тесте - за всяка боя имаме
17 | [А, 2, 3, 4, 5, 6, 7, 8, 9, 10, J, Q, K],
18 | а боите съответно са подредени - спатия, каро, купа, пика.
19 | Целта на вашата програма е по подадено цяло положително число
20 | к в интервала [0; 51] да изведе картата (картинка и боя),
21 | която се намира на к-та позиция в тестето, подредено по дефинирания по-горе начин.
22 | При невалиден вход програмата дава възможност за избор:
23 | ново въвеждане или приключване на програмата. 24 | 25 | Пример: 26 | ``` 27 | Вход: 13 28 | Изход: A♦ 29 | ``` 30 | *hint: за боите може да използвате подходящи ASCII символи.* 31 | # 32 | 3. Да се състави програма, която прочита от конзолата
33 | цяло положително 32-битово число и изкарва неговото двоично представяне. 34 | 35 | Пример: 36 | ``` 37 | Вход: 148 38 | Изход: 00000000'00000000'00000000'10010100 39 | ``` 40 | # 41 | 4. Напишете програма, която прочита цяло положително число
42 | unsigned int - А и три числа показващи позиции на битове -
43 | а1, а2, а3 в интервала [0;31]. Програмата да пресметне
44 | числото А’ получено от А, чрез вдигане на
45 | битовете на позиции а1, а2, а3 и да отпечата на екрана
46 | разликата А’ - А.
47 | Какво можем да кажем със сигурност за тази разлика? 48 | # 49 | 5. Реализирайте програма, която прочита цяло положително число
50 | unsigned int А и отпечатва стойноста на числото А’,
51 | получено при обръщане на първите 16 бита на А. 52 | 53 | Пример: 54 | ``` 55 | Вход: 19006 // 0b01001010'00111110 56 | Изход: 46529 // 0b10110101'11000001 57 | ``` 58 | # 59 | 6. Имплементирайте програма, която получава едно двубайтово число
60 | на стандартния си вход и го отпечатва с разменени байтове.
61 | 62 | Пример: 63 | ``` 64 | Вход: 19006 // 0b01001010'00111110 65 | Изход: 15946 // 0b00111110'01001010 66 | ``` 67 | # 68 | 7. Да се състави програма, която приема като входни данни
69 | цели 4-байтови числа, елементи на монотонно растяща редица,
70 | всяко от които в интервала [0;100].
71 | Програмата приключва, при първата въведена стойност, непринадлежаща
72 | на редицата. Отпечатайте броя на числата от редицата. 73 | 74 | Пример: 75 | ``` 76 | Вход: 1 2 3 4 5 3 // спира на втората 3-ка 77 | Изход: 5 78 | ``` 79 | # 80 | 8. По въведено n, oтпечатайте резултата от следната сума:
81 | n
82 | ⅀ i = ?
83 | i = 1
84 | _Дали можем да я пресметнем без да използваме цикъл?_ 85 | # 86 | 9. По въведено цяло положително число n програмата да прочита
87 | n на брой цели числа, а след това да отпечатва тяхното средно аритметично.
88 | # 89 | 10. По въведено цяло положително число n програмата
90 | да отпечатва броя на цифрите на числото.
91 | _Дали можем да ги пресметнем без да използваме цикъл?_ 92 | 93 | Пример: 94 | ``` 95 | Вход: 12345 96 | Изход: 5 97 | ``` 98 | # 99 | 11. По въведено цяло положително число n програмата да отпечатва
100 | цифрите на числото в обратен ред, разделени с интервали.
101 | 102 | Пример: 103 | ``` 104 | Вход: 12345 105 | Изход: 5 4 3 2 1 106 | ``` 107 | # 108 | 12. По въведено цяло положително число n програмата да отпечатва
109 | резултата на N! = N * (N-1) * .... * 1 (факториел).
110 | Oграничете входа, така че да не получавате препълване (overflow). 111 | # 112 | 13. По въведено цяло положително число n програмата да отпечатва
113 | “prime” ⇔ n e просто число (дели се само на 1 и на себе си).
114 | В противен случай програмата извежда “compose”. 115 | # 116 | -------------------------------------------------------------------------------- /03_execution_flow_control/seminar/basic_loops.cpp: -------------------------------------------------------------------------------- 1 | /**************************************************************************** 2 | * This file is part of the "Introduction to programming" course. FMI 2019/20 3 | *****************************************************************************/ 4 | 5 | /** 6 | * @file basic_loops.cpp 7 | * @author Ivan Filipov 8 | * @date 10.2019 9 | * @brief How to control the flow of 10 | * execution with loops. 11 | */ 12 | 13 | #include 14 | 15 | int main() { 16 | 17 | // see-the-matrix loop 18 | while (true) { // endless loop 19 | //std::cout << "a?#b1&c"; // commenting out is up to you :) 20 | break; // stop the loop (remove that line in the endless loop) 21 | } 22 | 23 | int i = 10; 24 | std::cout << "from 10 to 0 with while loop:" << std::endl; 25 | while (i > 0) { 26 | std::cout << i << " "; 27 | --i; 28 | } 29 | 30 | std::cout << std::endl; 31 | std::cout << "than from " << i << " to 0 with while loop:" << std::endl; 32 | while (i > 0) { 33 | std::cout << i << " "; 34 | --i; 35 | } 36 | 37 | std::cout << "than from " << i << " to 0 with do-while loop:" << std::endl; 38 | do { 39 | std::cout << i << " "; 40 | --i; 41 | } while (i > 0); 42 | 43 | std::cout << std::endl; 44 | std::cout << "Enter n (> 0):"; 45 | unsigned int n; 46 | std::cin >> n; 47 | std::cout << "All natural numbers to n: " << std::endl; 48 | for (unsigned int i = 0; i < n; i++) { 49 | std::cout << i << " "; 50 | } 51 | 52 | std::cout << std::endl; 53 | std::cout << "All even natural numbers to n: " << std::endl; 54 | for (unsigned int i = 0; i < n; i++) { 55 | if (i % 2 != 0) { 56 | continue; // make step forward, without executing the code below 57 | } 58 | std::cout << i << " "; 59 | 60 | /* which is the same as: 61 | if (i % 2 == 0) { 62 | std::cout << i << " "; 63 | } 64 | */ 65 | } 66 | 67 | std::cout << std::endl; 68 | // !!! please, don't write stuff like the example above - 69 | // there is much smarter approach 70 | for (unsigned int i = 0; i < n; i += 2) { // make the step 2 71 | std::cout << i << " "; 72 | } 73 | 74 | return 0; 75 | } 76 | -------------------------------------------------------------------------------- /03_execution_flow_control/seminar/bitwise_operators.cpp: -------------------------------------------------------------------------------- 1 | /**************************************************************************** 2 | * This file is part of the "Introduction to programming" course. FMI 2019/20 3 | *****************************************************************************/ 4 | 5 | /** 6 | * @file bitwise_operators.cpp 7 | * @author Ivan Filipov 8 | * @date 10.2019 9 | * @brief Some common tricks with bitwise operations. 10 | * Also, shows the idea of over/under-flows. 11 | */ 12 | 13 | #include 14 | #include // defines constants line INT_MAX - the maximum value an int can have 15 | 16 | const unsigned char BITS_PER_BYTE = CHAR_BIT; // each byte have eight bits. 17 | 18 | int main() { 19 | 20 | // an overflow example 21 | int a = INT_MAX; 22 | std::cout << "INT_MAX = " << a << std::endl 23 | << "INT_MAX + 1 = " << a + 1 << std::endl; 24 | 25 | // and an underflow one 26 | int b = INT_MIN; 27 | std::cout << "INT_MIN = " << b << std::endl 28 | << "INT_MIN - 1 = " << b - 1 << std::endl; 29 | //- Why is this happening? 30 | //- Because of the "in-memory" representation of the numbers. 31 | 32 | std::cout << "-----------------------" << std::endl; 33 | 34 | // how to generate a value, such as unsigned char max? 35 | std::cout << "UCHAR_MAX = " << UCHAR_MAX << std::endl; 36 | // an unsigned char is actually a byte -> 37 | // each byte has 8bits, so the maximum value it can 38 | // have is when all of those bits are on -> 39 | // 0b1111111, lets add 1 to that number, 40 | // we got 0b100000000, which is exactly 2 ^ 8. 41 | // to compute the maximum value we need, we have to 42 | // remove the added 1 -> (2 ^ 8 - 1) 43 | // 1 << 8 is "one shifted eight times to the left", 44 | // which is 2 ^ 8 45 | std::cout << "UCHAR_MAX = " << (1 << BITS_PER_BYTE) - 1 46 | << "(bitwise calculated)" << std::endl; 47 | 48 | // lets apply the same trick with unsigned int 49 | std::cout << "UINT_MAX = " << UINT_MAX << std::endl; 50 | unsigned int ui = (1 << (sizeof(unsigned int) * BITS_PER_BYTE)) - 1; 51 | std::cout << "UINT_MAX = " << ui 52 | << "(bitwise calculated)" << std::endl; 53 | 54 | std::cout << "-----------------------" << std::endl; 55 | 56 | // a common bitwise task is to extract a given bit 57 | // from a number, for example the third bit 58 | unsigned int bb = 0b00110101; 59 | // to do so, we need a "mask" - a special value, created to fit the task 60 | unsigned mask = 1 << 2; 61 | // and a bitwise operation - "and" in this case 62 | std::cout << "Third bit of 0b00110101 is: " 63 | << ((bb & mask) ? 1 : 0) << std::endl; // the parenthesis are needed here 64 | 65 | // another task could be to set a bit on a given position 66 | unsigned int bar = 0b00111011; 67 | // again we need a mask 68 | mask = 1 << 2; // 0b00000100 69 | // set the bit using the mask and "or" bitwise operation 70 | bar |= mask; // bar = bar | mask; 71 | std::cout << "0b00110101 after setting the third bit to 1: " 72 | << bar << std::endl; 73 | // lets have a simple check 74 | std::cout << bar << " =? " 75 | << ((1 << 6) - 1) << std::endl; 76 | 77 | // other possible usage - extract a byte from a 4-byte number 78 | unsigned int num = 0xFF0AC0; 79 | // we are going to extract the middle byte 80 | // |00|FF|0A|C0 81 | // our mask is |00|00|FF|00 82 | // the result should be right-shifted with one byte, 83 | std::cout << "The hex number 0xFF0AC0, has a second byte with decimal value of: " 84 | << ((num & 0xFF00) >> 8) << std::endl; 85 | 86 | std::cout << "Let's apply bitwise XOR to 42 and 11, just for fun." 87 | << std::endl << "result: " << (42 ^ 11) << std::endl; 88 | 89 | return 0; 90 | } 91 | -------------------------------------------------------------------------------- /03_execution_flow_control/seminar/enum_switch.cpp: -------------------------------------------------------------------------------- 1 | /**************************************************************************** 2 | * This file is part of the "Introduction to programming" course. FMI 2019/20 3 | *****************************************************************************/ 4 | 5 | /** 6 | * @file enum_switch.cpp 7 | * @author Ivan Filipov 8 | * @date 10.2019 9 | * @brief Basic example, showing the usage 10 | * of enumerations and transferring control 11 | * to one of the several statements, 12 | * depending on the value of a condition. 13 | */ 14 | 15 | #include 16 | 17 | // enumerations could be used to "pack" 18 | // related constants 19 | enum weekday { 20 | MON = 0, // as a general rule: values could be initialized 21 | TUE, // but if they aren't - the last value + 1 is passed automatically (TUE = 1) 22 | WED, // WED = 2 (TUE + 1), and so on. 23 | THU, 24 | FRI, 25 | SAT, 26 | SUN 27 | }; 28 | 29 | int main() { 30 | 31 | int day_num; 32 | std::cout << "Enter a number (weekday 1-7): "; 33 | std::cin >> day_num; 34 | 35 | day_num -= 1; // from 1-7 to 0-6 36 | weekday day = (weekday)day_num; 37 | std::cout << "The inputted day is: " << std::endl; 38 | 39 | // switch can be used instead of multiple if statements 40 | switch (day) { // the value here SHOULD be from an integer-like type (aka only numbers -10, 10, 0, 20, etc.) 41 | case MON: // check if day == MON 42 | std::cout << "Monday" << std::endl; 43 | break; // we use "break", to show, that no more cases should be matched 44 | case TUE: 45 | std::cout << "Tuesday" << std::endl; 46 | break; 47 | case WED: 48 | std::cout << "Wednesday" << std::endl; 49 | break; 50 | case THU: 51 | std::cout << "Thursday" << std::endl; 52 | break; 53 | case FRI: 54 | std::cout << "Friday" << std::endl; 55 | break; 56 | case SAT: 57 | std::cout << "Saturday" << std::endl; 58 | break; 59 | case SUN: 60 | std::cout << "Sunday" << std::endl; 61 | break; 62 | default: // matches all other possible values for (day) 63 | std::cout << "Invalid day" << std::endl; 64 | } 65 | 66 | // we can also take advantage of switch cases fall-through-s 67 | switch (day) { 68 | case MON: // fall-through (go to the below case) 69 | case TUE: // down 70 | case WED: // down 71 | case THU: // down 72 | case FRI: // up to here 73 | std::cout << "Which is part of the weekdays." << std::endl; 74 | break; 75 | case SAT: 76 | case SUN: 77 | std::cout << "Which is part of the weekend." << std::endl; 78 | break; 79 | } 80 | 81 | return 0; 82 | } 83 | -------------------------------------------------------------------------------- /03_execution_flow_control/seminar/for_loop_diagram.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/VasiPeycheva/Introduction-to-Programming--2017-2020/b4ea6adf9e76b55724d3b914900f953f416796be/03_execution_flow_control/seminar/for_loop_diagram.png -------------------------------------------------------------------------------- /03_execution_flow_control/seminar/materials.md: -------------------------------------------------------------------------------- 1 | ## Execution flow control 2 | --- 3 | 4 | [Bitwise operators](https://www.cprogramming.com/tutorial/bitwise_operators.html) 5 | 6 | --- 7 | [Enumerations](https://www.programiz.com/cpp-programming/enumeration)
8 | [Control Structures](http://people.scs.carleton.ca/~dehne/projects/cpp-doc/tutorial/tut2-1.html) 9 | -------------------------------------------------------------------------------- /03_execution_flow_control/seminar/while_loop_diagram.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/VasiPeycheva/Introduction-to-Programming--2017-2020/b4ea6adf9e76b55724d3b914900f953f416796be/03_execution_flow_control/seminar/while_loop_diagram.png -------------------------------------------------------------------------------- /04_scopes_nested_loops/practice/task_01.cpp: -------------------------------------------------------------------------------- 1 | /**************************************************************************** 2 | * This file is part of the "Introduction to programming" course. FMI 2019/20 3 | *****************************************************************************/ 4 | 5 | /** 6 | * @file task_01.cpp 7 | * @author Ivan Filipov 8 | * @author Kristian Krastev 9 | * @author Vasilena Peycheva 10 | * @date 11.2019 11 | * @brief Solution for task 1 from practice 4. 12 | */ 13 | 14 | #include 15 | #include 16 | 17 | int main() { 18 | 19 | unsigned long long a, b; 20 | unsigned long long sum = 0; 21 | 22 | std::cin >> a >> b; 23 | 24 | if (b <= a) { 25 | std::cout << "wrong interval" << std::endl; 26 | return 1; 27 | } 28 | 29 | // helpers 30 | unsigned long long sq; 31 | bool is_prime_current = true; 32 | 33 | // handle 1 and 2, outside the loop 34 | if (a == 2) { 35 | sum = 2; 36 | a++; 37 | } else if (a == 1) { 38 | sum = 3; 39 | a = 3; 40 | } 41 | 42 | // iterating each number between 'a' and 'b' 43 | for (unsigned long long i = a; i < b; i++) { 44 | sq = std::sqrt(i); 45 | is_prime_current = true; 46 | // we check if the number is prime 47 | for (unsigned long long j = 2; j <= sq; j++) { 48 | if (i % j == 0) { 49 | is_prime_current = false; 50 | break; // breaks the nearest loop 51 | } 52 | } 53 | 54 | if (is_prime_current) 55 | sum += i; 56 | } 57 | 58 | std::cout << "the sum is : " << sum << std::endl; 59 | return 0; 60 | } 61 | -------------------------------------------------------------------------------- /04_scopes_nested_loops/practice/task_02.cpp: -------------------------------------------------------------------------------- 1 | /**************************************************************************** 2 | * This file is part of the "Introduction to programming" course. FMI 2019/20 3 | *****************************************************************************/ 4 | 5 | /** 6 | * @file task_02.cpp 7 | * @author Ivan Filipov 8 | * @author Kristian Krastev 9 | * @author Vasilena Peycheva 10 | * @date 11.2019 11 | * @brief Solution for task 2 from practice 4. 12 | */ 13 | 14 | #include 15 | 16 | int main() { 17 | 18 | unsigned int N; 19 | 20 | std::cin >> N; 21 | 22 | unsigned int current_number; 23 | unsigned long long sum_digits = 0; 24 | 25 | for (int i = 0; i < N; i++){ 26 | std::cin >> current_number; 27 | 28 | // for each input number we are 29 | // adding its digits to the sum 30 | while (current_number) { 31 | sum_digits += (current_number % 10); 32 | current_number /= 10; 33 | } 34 | } 35 | 36 | std::cout << "sum of the digits is : " 37 | << sum_digits << std::endl; 38 | return 0; 39 | } 40 | -------------------------------------------------------------------------------- /04_scopes_nested_loops/practice/task_03.cpp: -------------------------------------------------------------------------------- 1 | /**************************************************************************** 2 | * This file is part of the "Introduction to programming" course. FMI 2019/20 3 | *****************************************************************************/ 4 | 5 | /** 6 | * @file task_03.cpp 7 | * @author Ivan Filipov 8 | * @author Kristian Krastev 9 | * @author Vasilena Peycheva 10 | * @date 11.2019 11 | * @brief Solution for task 3 from practice 4. 12 | */ 13 | 14 | #include 15 | 16 | int main() { 17 | 18 | unsigned int N; 19 | std::cin >> N; 20 | std::cout << "N = "; 21 | 22 | for (int i = 2; i <= N; i++) { 23 | // dividing the numbers as many times as we can 24 | while (N % i == 0) { 25 | std::cout << i; 26 | N /= i; 27 | 28 | if (N != 1) //still have divisors 29 | std::cout << " * "; 30 | } 31 | } 32 | 33 | std::cout << std::endl; 34 | return 0; 35 | } 36 | -------------------------------------------------------------------------------- /04_scopes_nested_loops/practice/task_04.cpp: -------------------------------------------------------------------------------- 1 | /**************************************************************************** 2 | * This file is part of the "Introduction to programming" course. FMI 2019/20 3 | *****************************************************************************/ 4 | 5 | /** 6 | * @file task_04.cpp 7 | * @author Ivan Filipov 8 | * @author Kristian Krastev 9 | * @date 11.2019 10 | * @brief Solution for task 4 from practice 4. 11 | */ 12 | 13 | #include 14 | 15 | int main() { 16 | 17 | int number; 18 | 19 | for (int f_digit = 1; f_digit <= 9; f_digit++) { 20 | for (int s_digit = 0; s_digit <= 9; s_digit++) { 21 | for (int t_digit = 0; t_digit <= 9; t_digit++) { 22 | if (f_digit != s_digit && 23 | f_digit != t_digit && 24 | s_digit != t_digit) { 25 | number = 100 * f_digit + 10 * s_digit + t_digit; 26 | std::cout << number << std::endl; 27 | } 28 | } 29 | } 30 | } 31 | 32 | return 0; 33 | } 34 | -------------------------------------------------------------------------------- /04_scopes_nested_loops/practice/task_05.cpp: -------------------------------------------------------------------------------- 1 | /**************************************************************************** 2 | * This file is part of the "Introduction to programming" course. FMI 2019/20 3 | *****************************************************************************/ 4 | 5 | /** 6 | * @file task_05.cpp 7 | * @author Ivan Filipov 8 | * @author Kristian Krastev 9 | * @date 11.2019 10 | * @brief Solution for task 5 from practice 4. 11 | */ 12 | 13 | #include 14 | 15 | int main() { 16 | 17 | unsigned int n; 18 | unsigned int sum = 0; 19 | int number_to_add; // helper number 20 | std::cin >> n; 21 | 22 | for (int i = 1; i <= n; i++) { 23 | number_to_add = i; 24 | 25 | for (int j = 1; j < i; j++) { // multiply our number (i - 1) times 26 | number_to_add *= i; 27 | } 28 | 29 | sum += number_to_add; 30 | } 31 | 32 | std::cout << "Sum: " << sum << std::endl; 33 | return 0; 34 | } 35 | -------------------------------------------------------------------------------- /04_scopes_nested_loops/practice/task_06.cpp: -------------------------------------------------------------------------------- 1 | /**************************************************************************** 2 | * This file is part of the "Introduction to programming" course. FMI 2019/20 3 | *****************************************************************************/ 4 | 5 | /** 6 | * @file task_06.cpp 7 | * @author Ivan Filipov 8 | * @author Kristian Krastev 9 | * @author Vasilena Peycheva 10 | * @date 11.2019 11 | * @brief Solution for task 6 from practice 4. 12 | */ 13 | 14 | #include 15 | 16 | int main() { 17 | 18 | unsigned int x, y; 19 | std::cin >> x >> y; 20 | 21 | if (x <= 1 || y <= 1) { 22 | std::cout << "can't draw! \n"; 23 | return 0; 24 | } 25 | 26 | // top line 27 | for (unsigned int i = 0; i < x; i++) { 28 | std::cout << "* "; 29 | } 30 | std::cout << std::endl; 31 | 32 | // the side lines 33 | for (unsigned int i = 0; i < y - 2; i++) { 34 | std::cout << "* "; 35 | for (unsigned int j = 0; j < x - 2; j++) { 36 | std::cout << " "; 37 | } 38 | std::cout << '*' << std::endl; 39 | } 40 | 41 | // the bottom line 42 | for (unsigned int i = 0; i < x; i++) { 43 | std::cout << "* "; 44 | } 45 | 46 | std::cout << std::endl; 47 | return 0; 48 | } 49 | -------------------------------------------------------------------------------- /04_scopes_nested_loops/practice/task_07.cpp: -------------------------------------------------------------------------------- 1 | /**************************************************************************** 2 | * This file is part of the "Introduction to programming" course. FMI 2019/20 3 | *****************************************************************************/ 4 | 5 | /** 6 | * @file task_07.cpp 7 | * @author Ivan Filipov 8 | * @date 11.2019 9 | * @brief Solution for task 7 from practice 4. 10 | */ 11 | 12 | #include 13 | #include 14 | 15 | const int TRIANGLE_MAX = 7; 16 | const int SAND_GLASS_MAX_SIZE = 8; 17 | 18 | int main() { 19 | 20 | // print the first figure 21 | for (int row = 1; row <= TRIANGLE_MAX; row++) { 22 | for (int col = 1; col <= row; col++) { 23 | std::cout << std::setw(2) << col; 24 | } 25 | std::cout << std::endl; 26 | } 27 | 28 | std::cout << std::endl << std::endl; 29 | 30 | // print second figure 31 | for (int row = 0; row < TRIANGLE_MAX; row++) { 32 | for (int spaces = 0; spaces < row; spaces++) { 33 | std::cout << std::setw(2) << " "; 34 | } 35 | for (int col = 1; col <= TRIANGLE_MAX - row; col++) { 36 | std::cout << std::setw(2) << col; 37 | } 38 | std::cout << std::endl; 39 | } 40 | 41 | std::cout << std::endl << std::endl; 42 | 43 | // print the third figure 44 | int max_num = SAND_GLASS_MAX_SIZE / 2; 45 | bool mid_printed = false; 46 | for (int row = 0; row < SAND_GLASS_MAX_SIZE; row++) { 47 | // revert logic, if below the center 48 | int row_num = std::min(SAND_GLASS_MAX_SIZE - row - 1, row); 49 | 50 | // don't print the mid line twice 51 | if (row_num == max_num - 1 && !mid_printed) 52 | mid_printed = true; 53 | else if (row_num == max_num - 1 && mid_printed) 54 | continue; 55 | 56 | // white-spaces in front 57 | for (int spaces = 0; spaces < row_num; spaces++) { 58 | std::cout << std::setw(2) << " "; 59 | } 60 | // numbers print in-order 61 | for (int num = row_num + 1; num <= max_num; num++) { 62 | std::cout << std::setw(2) << num; 63 | } 64 | // print numbers reverse order 65 | for (int num = max_num; num > row_num; num--) { 66 | std::cout << std::setw(2) << num; 67 | } 68 | 69 | // white-spaces in back 70 | for (int spaces = 0; spaces < row_num; spaces++) { 71 | std::cout << std::setw(2) << " "; 72 | } 73 | std::cout << std::endl; 74 | } 75 | 76 | return 0; 77 | } 78 | -------------------------------------------------------------------------------- /04_scopes_nested_loops/practice/task_08.cpp: -------------------------------------------------------------------------------- 1 | /**************************************************************************** 2 | * This file is part of the "Introduction to programming" course. FMI 2019/20 3 | *****************************************************************************/ 4 | 5 | /** 6 | * @file task_08.cpp 7 | * @author Ivan Filipov 8 | * @date 11.2019 9 | * @brief Solution for task 8 from practice 4. 10 | */ 11 | 12 | #include 13 | 14 | int main() { 15 | 16 | int a1, a2, a3, a4, a; 17 | int p, q; 18 | 19 | std::cout << "a1 = "; 20 | std::cin >> a1; 21 | 22 | std::cout << "a2 = "; 23 | std::cin >> a2; 24 | 25 | std::cout << "a3 = "; 26 | std::cin >> a3; 27 | 28 | std::cout << "a4 = "; 29 | std::cin >> a4; 30 | 31 | std::cout << "a = "; 32 | std::cin >> a; 33 | 34 | std::cout << "Enter lower bound (p): "; 35 | std::cin >> p; 36 | 37 | std::cout << "Enter upper bound (q): "; 38 | std::cin >> q; 39 | 40 | if (p >= q) { 41 | std::cout << "Invalid input." << std::endl; 42 | return 1; 43 | } 44 | 45 | 46 | std::cout << "Solutions for: " << std::endl 47 | << a1 << " * x1 + " 48 | << a2 << " * x2 + " 49 | << a3 << " * x3 + " 50 | << a4 << " * x4 = " 51 | << a << std::endl; 52 | 53 | std::cout << "in [" << p << ", " << q << "]:" << std::endl; 54 | 55 | for (int x1 = p; x1 <= q; x1++) 56 | for (int x2 = p; x2 <= q; x2++) 57 | for (int x3 = p; x3 <= q; x3++) 58 | for (int x4 = p; x4 <= q; x4++) 59 | if (a1 * x1 + a2 * x2 + a3 * x3 + a4 * x4 == a) 60 | std::cout << a1 << " * " << x1 << " + " 61 | << a2 << " * " << x2 << " + " 62 | << a3 << " * " << x3 << " + " 63 | << a4 << " * " << x4 << " = " 64 | << a << std::endl; 65 | 66 | return 0; 67 | } 68 | -------------------------------------------------------------------------------- /04_scopes_nested_loops/practice/задачи.md: -------------------------------------------------------------------------------- 1 | # **Задачи - вложени цикли** 2 | 3 | *забележка: не е нужно да решавате задачите в дадената наредба* 4 | 5 | 1. По въведени цели положителни числа a, b (b > a) програмата да изведе
6 | сумата от всички прости числа в интервала [a;b].
7 | 8 | Пример: 9 | ``` 10 | Вход: 2 10 11 | Изход: 17 // 2 + 3 + 5 + 7 12 | ``` 13 | # 14 | 2. По въведено цяло положително число N програмата да прочита N на брой
15 | цели числа, а след това да отпечатва сумата от цифрите им.
16 | 17 | Пример: 18 | ``` 19 | Вход: 3 20 | 11 255 42 21 | Изход: 20 // 1 + 1 + 2 + 5 + 5 + 4 + 2 22 | ``` 23 | # 24 | 3. По въведено цяло положително число N програмата да отпечатва всичките
25 | му прости делители разделени с интервали.
26 | 27 | Пример: 28 | ``` 29 | Вход: 990 30 | Изход: 2 3 3 5 11 31 | ``` 32 | # 33 | 4. Да се напише програма, която извежда в нарастващ ред всички трицифрени
34 | естествени числа, които не съдържат еднакви цифри. 35 | # 36 | 5. По въведени N на брой числа изведете на екрана сумата:
37 | n
38 | ⅀ ii = ?
39 | i = 1 40 | # 41 | 6. По въведени две цели положителни числа x > 1, y > 1 програмата да
42 | отпечатва в конзолата рамките на правоъгълник от звездички ‘*’
43 | като по хоризонтала имаме х на брой звездички, а по вертикала у.
44 | Приемаме, че горният десен ъгъл на конзолата е (0,0).
45 | 46 | Пример: 47 | ``` 48 | Вход: 5 3 49 | Изход: 50 | 51 | * * * * * 52 | * * 53 | * * * * * 54 | ``` 55 | # 56 | 7. Да се напише програма която извежда на екрана следните фигури:
57 | ``` 58 | 1 59 | 1 2 60 | 1 2 3 61 | 1 2 3 4 62 | 1 2 3 4 5 63 | 1 2 3 4 5 6 64 | 1 2 3 4 5 6 7 65 | ``` 66 | ``` 67 | 1 2 3 4 5 6 7 68 | 1 2 3 4 5 6 69 | 1 2 3 4 5 70 | 1 2 3 4 71 | 1 2 3 72 | 1 2 73 | 1 74 | ``` 75 | ``` 76 | 1 2 3 4 4 3 2 1 77 | 2 3 4 4 3 2 78 | 3 4 4 3 79 | 4 4 80 | 3 4 4 3 81 | 2 3 4 4 3 2 82 | 1 2 3 4 4 3 2 1 83 | ``` 84 | # 85 | 8. Да с напише програма, която намира всички решения на диофантовото
86 | уравнение **a1.x1 + a2.x2 + a3.x3 + a4.x4 = a** , където а1, а2, а3, а4 и а
87 | са дадени цели числа, а неизвестните x1, x2, x3, x4 приемат стойности
88 | от интервала **[p, q]** (p и q са дадени цели числа, p < q).
89 | # 90 | -------------------------------------------------------------------------------- /04_scopes_nested_loops/seminar/double_comparison.cpp: -------------------------------------------------------------------------------- 1 | /**************************************************************************** 2 | * This file is part of the "Introduction to programming" course. FMI 2019/20 3 | *****************************************************************************/ 4 | 5 | /** 6 | * @file double_comparison.cpp 7 | * @author Ivan Filipov 8 | * @date 11.2019 9 | * @brief An example, which shows how to (how to not) 10 | * work with floating point numbers in C++. 11 | * 12 | * @note The results may vary on different platforms. 13 | */ 14 | 15 | #include 16 | #include 17 | #include // std::abs 18 | 19 | const double EPS = 0.001f; 20 | const double SMALLER_EPS = 0.000000001f; 21 | 22 | int main() { 23 | 24 | double num = 1.1f; // just 1.1 number 25 | 26 | // lets calculate it as a sum 27 | // starting from 0.0 when we add 11 time 0.1, the result 28 | // will be 1.1, won't it? 29 | double step = 0.1f; 30 | double sum = 0.0f; 31 | for (int i = 0; i < 11; i++) 32 | sum += step; 33 | 34 | // again 1.1, but as a multiplication 35 | double mul = step * 11.0f; 36 | 37 | // print 20 digits after the floating point 38 | std::cout << std::setprecision(20) << std::fixed; 39 | 40 | std::cout << "num: " << num << std::endl; 41 | std::cout << "num as a sum: " << sum << std::endl; 42 | std::cout << "num as a multiplication: " << mul << std::endl << std::endl; 43 | 44 | // the "num" and "sum" should be equal - both 1.1 45 | // but are they? 46 | if (num == sum) { 47 | std::cout << "num == sum" << std::endl; 48 | } else { 49 | std::cout << "Lol?! num != sum" << std::endl; 50 | } 51 | 52 | // so, one of the correct ways to compare floating point numbers 53 | // is by a tolerance. We say they are equal, if they are close enough, 54 | // in the terms of mathematics. 55 | // EPS (epsilon controls how precise the compression to be ("how many digits to be taken into consideration") 56 | if (std::abs(num - sum) < EPS) { 57 | std::cout << "num == sum with EPS(" << EPS << ')' << std::endl; 58 | } else { 59 | std::cout << "lol" << std::endl; 60 | } 61 | 62 | // if we want to see if one floating point number is smaller than other: 63 | if (num - sum > SMALLER_EPS) { 64 | std::cout << "num > sum with EPS(" << SMALLER_EPS << ')' << std::endl; 65 | } 66 | 67 | return 0; 68 | } 69 | -------------------------------------------------------------------------------- /04_scopes_nested_loops/seminar/input_output_manipulations.cpp: -------------------------------------------------------------------------------- 1 | /**************************************************************************** 2 | * This file is part of the "Introduction to programming" course. FMI 2019/20 3 | *****************************************************************************/ 4 | 5 | /** 6 | * @file input_output_manipulations.cpp 7 | * @author Ivan Filipov 8 | * @date 11.2019 9 | * @brief Some utilities for I/O formatting. 10 | * 11 | */ 12 | 13 | #include 14 | #include // all formatting flags are located here 15 | 16 | int main() { 17 | 18 | // the simplest task can be to format a number into different numeral system 19 | 20 | int foo = 42; 21 | std::cout << "foo: " << foo << "(dec)" << std::endl 22 | << "foo: 0x" << std::hex << foo << "(hex)" << std::endl 23 | << "foo: 0" << std::oct << foo << "(oct)" << std::endl; 24 | 25 | bool bar = false; 26 | std::cout << "bar: " << std::boolalpha << bar << std::endl; 27 | 28 | int x; 29 | std::cout << "Enter hexadecimal number: "; 30 | std::cin >> std::setbase(16) >> x; 31 | std::cout << "x " << std::dec << x << "(dec)" << std::endl; 32 | 33 | 34 | // a common task is to print a fixed number of 35 | // digits after the decimal comma (point), when 36 | // working with floating point numbers 37 | std::cout << std::setprecision(4) // we will format up to 4 digits after the "." -> 3.13121 - 3.1312 38 | << std::fixed // format exact 4 digits, because when using only setprecision 3.01 will be formatted as 3.01, not 3.0100 39 | << 3.13121f 40 | << std::endl; 41 | 42 | // another example -> format the output into some boxes 43 | int a = 321; 44 | std::cout << std::setw(5) // set five boxes [][][][][] 45 | << std::setfill('0') // set filling character, if not set 321 will be outputted as [][][3][2][1] (two spaces in front) 46 | << a 47 | << std::endl; 48 | 49 | // put a string into quotes 50 | std::cout << std::quoted("test string") 51 | << " \"test string\"" // we can achieve the same result using escape sequences 52 | << std::endl; 53 | 54 | return 0; 55 | } 56 | -------------------------------------------------------------------------------- /04_scopes_nested_loops/seminar/materials.md: -------------------------------------------------------------------------------- 1 | ## I/O manipulations, Doubles comparison 2 | --- 3 | 4 | [I/O manipulations C++](https://en.cppreference.com/w/cpp/header/iomanip) 5 | 6 | [Double comparison](https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/) 7 | 8 | ## Scopes, nested loops 9 | 10 | --- 11 | [Scopes](http://www.cplusplus.com/doc/tutorial/namespaces/)
12 | 13 | --- 14 | 15 | [Nested loops](https://www.programtopia.net/cplusplus/docs/nested-loops) 16 | -------------------------------------------------------------------------------- /04_scopes_nested_loops/seminar/nested_loops.cpp: -------------------------------------------------------------------------------- 1 | /**************************************************************************** 2 | * This file is part of the "Introduction to programming" course. FMI 2019/20 3 | *****************************************************************************/ 4 | 5 | /** 6 | * @file nested_loops.cpp 7 | * @author Ivan Filipov 8 | * @date 11.2019 9 | * @brief An example, which prints nicely the representative 10 | * part of the ASCII table, using nested loops. 11 | */ 12 | 13 | #include 14 | #include 15 | 16 | const int SYMBOLS_PER_ROW = 3; // on each row we are going to print 3 ASCII symbols 17 | const int SYMBOLS_PER_COL = 32; // we will have 32 symbols in each column 18 | 19 | int main() { 20 | 21 | for (int rows = 0; rows < SYMBOLS_PER_COL; rows++) { // <- outer loop, on each of it's steps, the inter loop will be fully executed 22 | for (int cols = 0; cols < SYMBOLS_PER_ROW; cols++) { // <- inner loop 23 | // decimal representation of that symbol (+1, to skip the first 32 character, which are system specific) 24 | int decimal = rows + ((cols + 1) * SYMBOLS_PER_COL); 25 | // symbol representation -> just save the decimal number as a symbol 26 | char symbol = decimal; 27 | std::cout << std::setw(3) << decimal << "->" 28 | << '\'' << symbol << '\'' << "| "; 29 | } 30 | // on each step of the outer loop, print a new line (so the rows are on new line each) 31 | std::cout << std::endl; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /04_scopes_nested_loops/seminar/scopes.cpp: -------------------------------------------------------------------------------- 1 | /**************************************************************************** 2 | * This file is part of the "Introduction to programming" course. FMI 2019/20 3 | *****************************************************************************/ 4 | 5 | /** 6 | * @file scopes.cpp 7 | * @author Ivan Filipov 8 | * @date 11.2019 9 | * @brief An example, which shows from where, 10 | * which variable we can "see". 11 | */ 12 | 13 | #include 14 | 15 | // here is the zone we call the global scope 16 | 17 | const int FORCE = 42; // the "FORCE" can be seen from each scope below 18 | 19 | // the main function like each other function 20 | // has its own scope 21 | int main() { 22 | // a local variable 23 | int jedi_master = 11; 24 | 25 | // all the stuff from the global scope can be "seen" here 26 | jedi_master += FORCE; 27 | 28 | // the statements have their own scopes too 29 | // in these scopes we can see everything from 30 | // the scope above the statement 31 | if (true) { 32 | // the padawan is created and 33 | // lives only in the current scope 34 | int padawan = 1; 35 | padawan += jedi_master; // the padawan can 'see' the 'jedi_master' 36 | } //<--- here the scope ends and the padawan gets destroyed 37 | 38 | // jedi_master += padawan; <- problem here the padawan doesn't exist in the current scope 39 | 40 | 41 | int destroyers = 10; 42 | for (int clones = 10; clones < 20; clones++) { 43 | // the clones variable lives only in the for loop's scope 44 | 45 | int droids = 5; /* the variable droids will be created 46 | and destroyed in each step of the loop 47 | maybe we don't want to do so 48 | and the proper approach when we want 49 | to use a variable in each step of the loop 50 | is to create it above the loop just like 51 | the variable 'destroyers' */ 52 | 53 | if (destroyers + droids > clones) 54 | std::cout << "Separatists win!" << std::endl; 55 | else 56 | std::cout << "The Republic wins!" << std::endl; 57 | } 58 | 59 | return 0; 60 | } 61 | -------------------------------------------------------------------------------- /05_functions/practice/задачи.md: -------------------------------------------------------------------------------- 1 | # **Задачи - Функции** 2 | 3 | 1. Да се напише функция, която връща по-голямото от две цели числа.
4 | 5 | Пример: 6 | ``` 7 | Вход: -10 -2 8 | Изход: -2 9 | ``` 10 | # 11 | 2. Да се напише функция, която връща абсолютната стойност на дадено число.
12 | 13 | Пример: 14 | ``` 15 | Вход: -2 16 | Изход: 2 17 | ``` 18 | # 19 | 3. Да се напише функция, която връща резултата от повдигането на дадено
20 | число n на степен k. (две цели положителни числа) (функцията pow)
21 | 22 | Пример: 23 | ``` 24 | Вход: 3 3 25 | Изход: 27 26 | ``` 27 | # 28 | 4. Да се напише функция, която връща НОД на две цели числа.
29 | 30 | Пример: 31 | ``` 32 | Вход: -4 10 33 | Изход: 2 34 | ``` 35 | # 36 | 5. Функция, която връща n-тото число на Фибоначи.
37 | 38 | Пример: 39 | ``` 40 | Вход: 6 41 | Изход: 8 42 | ``` 43 | # 44 | 6. Функция, която проверява дали число е просто.
45 | 46 | Пример: 47 | ``` 48 | Вход: 5 49 | Изход: True 50 | ``` 51 | ``` 52 | Вход: 12 53 | Изход: False 54 | ``` 55 | # 56 | 7. Функция, която получава два цели числа x,y като аргументи и проверява
57 | колко пъти y дели x.
58 | 59 | Пример: 60 | ``` 61 | Вход: 20 2 62 | Изход: 2 63 | ``` 64 | ``` 65 | Вход: 10 3 66 | Изход: 0 67 | ``` 68 | # 69 | 8. Функция, която да връща като резултат лицето на кръг по подаден радиус
70 | като параметър. Резултата трябва да бъде закръглен до втората цифра
71 | след запетаята
72 | 73 | Пример: 74 | ``` 75 | Вход: 1 76 | Изход: 3.14 77 | ``` 78 | # 79 | 9. Да се напишат две функции:
80 | - Първата функция (input) реализира: въвежда се цяло положително число n,
81 | което оказва колко цели числа след това искаме да въведем.
82 | От всички въведени числа, функцията трябва да върне най-голямото.
83 | - Втората функция(print) приема като аргумент резултата от първата
84 | функция и изкарва резултата на екрана.
85 | 86 | Пример: 87 | ``` 88 | Вход: 4 89 | 2 -3 1 0 90 | Изход: 2 91 | ``` 92 | # 93 | -------------------------------------------------------------------------------- /05_functions/seminar/ascii_table_function.cpp: -------------------------------------------------------------------------------- 1 | /**************************************************************************** 2 | * This file is part of the "Introduction to programming" course. FMI 2019/20 3 | *****************************************************************************/ 4 | 5 | /** 6 | * @file ascii_table_function.cpp 7 | * @author Ivan Filipov 8 | * @date 11.2019 9 | * @brief Printing the ASCII table, with some 10 | * helper functions 11 | * @see nested_loops.cpp 12 | * @see https://bg.wikipedia.org/wiki/ASCII 13 | */ 14 | 15 | #include 16 | #include 17 | 18 | const int SYMBOLS_PER_ROW = 4; // on each row we are going to print 4 ASCII symbols 19 | const int SYMBOLS_PER_COL = 32; // we will have 32 symbols in each column 20 | 21 | 22 | bool is_special_symbol(char c) { 23 | 24 | if (c >= 0 && c <= 31) 25 | return true; 26 | 27 | return c == 127; 28 | } 29 | 30 | 31 | void output_normal_char(char c, int dec) { 32 | 33 | std::cout << std::setw(3) << dec << "->" 34 | << '\'' << c << '\'' << "| "; 35 | } 36 | 37 | void output_special_char(char c, int dec) { 38 | 39 | std::cout << std::setw(3) << dec << "->"; 40 | switch(c) { 41 | case 0: std::cout << "NUL"; break; 42 | case 1: std::cout << "SOH"; break; 43 | case 2: std::cout << "STX"; break; 44 | case 3: std::cout << "ETX"; break; 45 | case 4: std::cout << "EOT"; break; 46 | case 5: std::cout << "ENQ"; break; 47 | case 6: std::cout << "ACK"; break; 48 | case 7: std::cout << "BEL"; break; 49 | case 8: std::cout << "BS "; break; 50 | case 9: std::cout << "HT "; break; 51 | case 10: std::cout << "LF "; break; 52 | case 11: std::cout << "VT "; break; 53 | case 12: std::cout << "FF "; break; 54 | case 13: std::cout << "CR "; break; 55 | case 14: std::cout << "SO "; break; 56 | case 15: std::cout << "SI "; break; 57 | case 16: std::cout << "DLE"; break; 58 | case 17: std::cout << "DC1"; break; 59 | case 18: std::cout << "DC2"; break; 60 | case 19: std::cout << "DC3"; break; 61 | case 20: std::cout << "DC4"; break; 62 | case 21: std::cout << "NAK"; break; 63 | case 22: std::cout << "SYN"; break; 64 | case 23: std::cout << "ETB"; break; 65 | case 24: std::cout << "CAN"; break; 66 | case 25: std::cout << "EM "; break; 67 | case 26: std::cout << "SUB"; break; 68 | case 27: std::cout << "ESC"; break; 69 | case 28: std::cout << "FS "; break; 70 | case 29: std::cout << "GS "; break; 71 | case 30: std::cout << "RS "; break; 72 | case 31: std::cout << "US "; break; 73 | 74 | case 127: std::cout << "DEL"; break; 75 | 76 | default: std::cout << "LOL"; // won't get here 77 | } 78 | 79 | std::cout << "| "; 80 | } 81 | 82 | // a function that prints the ASCII table to stdout 83 | void print_ascii_table() { 84 | 85 | for (int rows = 0; rows < SYMBOLS_PER_COL; rows++) { 86 | for (int cols = 0; cols < SYMBOLS_PER_ROW; cols++) { 87 | int decimal = rows + (cols * SYMBOLS_PER_COL); 88 | char symbol = decimal; 89 | 90 | if (is_special_symbol(symbol)) 91 | output_special_char(symbol, decimal); 92 | else 93 | output_normal_char(symbol, decimal); 94 | } 95 | std::cout << std::endl; 96 | } 97 | } 98 | 99 | int main() { 100 | 101 | print_ascii_table(); 102 | 103 | return 0; 104 | } 105 | -------------------------------------------------------------------------------- /05_functions/seminar/basic_functions.cpp: -------------------------------------------------------------------------------- 1 | /**************************************************************************** 2 | * This file is part of the "Introduction to programming" course. FMI 2019/20 3 | *****************************************************************************/ 4 | 5 | /** 6 | * @file basic_functions.cpp 7 | * @author Ivan Filipov 8 | * @date 11.2019 9 | * @brief Functions basics - arguments, parameters, return types. 10 | */ 11 | 12 | #include 13 | 14 | // when can have a function which does not return a value, 15 | // and has no parameters 16 | void print_msg() { 17 | 18 | std::cout << "Just a test massage..." << std::endl; 19 | } 20 | 21 | // simple function, which takes an integer 22 | // an returns the same value 23 | int id(int x) { 24 | 25 | return x; 26 | } 27 | 28 | // a function with has two parameters int-s 29 | // and returns their multiplication 30 | int mul(int a, int b) { 31 | 32 | return a * b; 33 | } 34 | 35 | int sum_mul(int a, int b) { 36 | // we can call other functions inside a given function 37 | return a + b + mul(a, b); 38 | } 39 | 40 | // the arguments of a function are passed by value -> 41 | // an inner copy of their value is created for the function's 42 | // purposes 43 | int inc_with_ten(int x) { 44 | // we add 10 to "ours" x, not the one, with which the function has been called 45 | x = x + 10; 46 | return x; 47 | } 48 | 49 | 50 | int main() { 51 | 52 | std::cout << 100 << "=? " << id(100) << std::endl; 53 | 54 | int x= 23, y = 11; 55 | std::cout << x << " * " << y << " = " << mul(x, y) << std::endl; 56 | 57 | std::cout << x << " + " << y << " + " 58 | << x << " * " << y << " = " << sum_mul(x, y) << std::endl; 59 | 60 | 61 | std::cout << "adding 10 to my_var("; 62 | int my_var = 42; 63 | std::cout << my_var << ") 5times: " << std::endl; 64 | for (int i = 0; i < 5; i++) 65 | std::cout << inc_with_ten(my_var) << std::endl; 66 | std::cout << "my_var in main:" << my_var << std::endl; 67 | 68 | std::cout << "(" << x << " + 10) * " 69 | << "(" << y << " + 10) = " 70 | << mul(inc_with_ten(x), inc_with_ten(y)) 71 | << std::endl; 72 | 73 | return 0; 74 | } 75 | -------------------------------------------------------------------------------- /05_functions/seminar/materials.md: -------------------------------------------------------------------------------- 1 | ## Functions basics 2 | --- 3 | 4 | [ASCII table](https://en.wikipedia.org/wiki/ASCII) 5 | 6 | --- 7 | 8 | [Fuctions I](http://people.scs.carleton.ca/~dehne/projects/cpp-doc/tutorial/tut2-2.html) 9 | 10 | --- 11 | -------------------------------------------------------------------------------- /05_functions/seminar/scopes.cpp: -------------------------------------------------------------------------------- 1 | /**************************************************************************** 2 | * This file is part of the "Introduction to programming" course. FMI 2019/20 3 | *****************************************************************************/ 4 | 5 | /** 6 | * @file scopes.cpp 7 | * @author Ivan Filipov 8 | * @date 11.2019 9 | * @brief Declare/define functions. Function scopes. 10 | */ 11 | 12 | #include 13 | 14 | // here is the zone we call the global scope 15 | 16 | const int FORCE = 42; // the "FORCE" can be seen from each scope below 17 | 18 | // declaring the function do_it, so it can be called from all other functions below, 19 | // and it's definition can be done wherever we want - before/after main, before/after other functions 20 | void do_it(); 21 | 22 | // each function defines its own scope 23 | void use_the_force(int jedi_knight) { 24 | // jedi_knight and light_saber are seen as local variables 25 | int light_saber = 35; 26 | // here we can 'see' all global defined constants and variables 27 | // All locals are destroyed 28 | // after leaving the function /when the function ends/ 29 | 30 | jedi_knight += FORCE; // the 'jediKnight' can 'see' the 'FORCE' 31 | 32 | jedi_knight += light_saber; // and each variable in the current scope 33 | 34 | std::cout << "Jedi's power: " << jedi_knight << std::endl; 35 | 36 | // we also can call all previously defined (or at least declared) functions 37 | do_it(); 38 | 39 | // wrong! - another_happy_landing is neither previously defined nor declared 40 | // another_happy_landing(); 41 | } 42 | 43 | void another_happy_landing() { 44 | 45 | std::cout << "Well done, Anakin" << std::endl; 46 | } 47 | 48 | void do_it() { 49 | 50 | std::cout << "Dew it!" << std::endl; 51 | } 52 | 53 | // the main function like each other function 54 | // has its own scope 55 | int main() { 56 | // a local variable 57 | int jedi_master = 11; 58 | 59 | // all the stuff from the global scope can be "seen" here 60 | jedi_master += FORCE; 61 | 62 | // we can call use_the_force with "jedi master" as parameter 63 | use_the_force(jedi_master); 64 | 65 | // the statements have their own scopes too 66 | // in these scopes we can see everything from 67 | // the scope above the statement 68 | if (true) { 69 | // the padawan is created and 70 | // lives only in the current scope 71 | int padawan = 1; 72 | padawan += jedi_master; // the padawan can 'see' the 'jedi_master' 73 | // we can call use_the_force with "padawan" as parameter 74 | use_the_force(jedi_master); 75 | } // <--- here the scope ends and the padawan gets destroyed 76 | 77 | // jedi_master += padawan; //problem here the padawan doesn't exist 78 | 79 | int destroyers = 10; 80 | for (int clones = 10; clones < 20; clones++) { 81 | // the clones variable lives only in the for loop's scope 82 | 83 | int droids = 5; /* the variable droids will be created 84 | and destroyed in each step of the loop 85 | maybe we don't want to do so 86 | and the proper approach when we want 87 | to use a variable in each step of the loop 88 | is to create it above the loop just like 89 | the variable 'destroyers' */ 90 | 91 | if (destroyers + droids > clones) 92 | std::cout << "Separatists win!" << std::endl; 93 | else 94 | std::cout << "The Republic wins!" << std::endl; 95 | } 96 | 97 | // the function is previously defined 98 | another_happy_landing(); 99 | 100 | return 0; 101 | } 102 | -------------------------------------------------------------------------------- /06_functions_array_basics/practice/задачи.md: -------------------------------------------------------------------------------- 1 | # **Задачи - Масиви** 2 | 3 | 1. Използвайте _Debugger_ за да проследите процеса на дадената програма:
4 | ```C++ 5 | #include 6 | 7 | #define PRIME false 8 | #define COMPOSITE true 9 | #define N 20000 10 | 11 | bool sieve[N] = { PRIME, }; 12 | 13 | void print_primes() { 14 | 15 | for (unsigned long long int i = 2; i < N; i++) { 16 | if (sieve[i] == PRIME) { 17 | std::cout << i << " is a prime!" << std::endl; 18 | } 19 | } 20 | } 21 | 22 | void eratosthenes_sieve() { 23 | 24 | for (unsigned long long int i = 2; i <= N; i++) { 25 | if (sieve[i] == PRIME) { 26 | for (unsigned long long int j = i * i; j <= N; j += i) { 27 | sieve[j] = COMPOSITE; 28 | } 29 | } 30 | } 31 | 32 | print_primes(); 33 | } 34 | 35 | int main() { 36 | 37 | eratosthenes_sieve(); 38 | return 0; 39 | } 40 | ``` 41 | Какво прави тя? Има ли потенциални проблеми в кода? 42 | # 43 | 44 | ***За всички задачи по-долу:***
45 | ***приемаме, че размерът на масива е строго по-малък от 1024.***
46 | ***Нека е n, число въведено от потребителя [1, 1023].***
47 | 48 | # 49 | 50 | 2. Напишете функция, която прочита елементите от конзолата на едномерен
51 | масив с дължина n (отново въведена от конзолата) и функция,
52 | която изкарва въведените елементите на конзолата.
53 | 54 | Пример: 55 | ``` 56 | Вход: 5 1 2 3 4 5 57 | Изход: 1 2 3 4 5 58 | ``` 59 | # 60 | 61 | 3. Напишете функции, които връщат сбора/ произведението на всички елементи
62 | в масив с размер n.
63 | 64 | Пример: 65 | ``` 66 | Вход: 3 1 2 3 67 | Изход: sum 6 product 6 68 | ``` 69 | # 70 | 71 | 4. Напишете функции, които намират най-големия/най-малкия
72 | елемент в масив, отпечатвайки индекса и стойността му.
73 | 74 | Пример: 75 | ``` 76 | Вход: 5 10 44 2 78 1 77 | Изход: min_index = 4 min_value = 1 max_index = 3 max_value = 78 78 | ``` 79 | # 80 | 81 | 5. Напишете функция, която изкарва на конзолата само простите числа,
82 | които са елементи на масив с размер n, предварително попълнен
83 | с числа, прочетени от клавиатурата.
84 | 85 | Пример: 86 | ``` 87 | Вход: 5 4 6 7 8 11 88 | Изход: 7 11 89 | ``` 90 | # 91 | 92 | 6. Напишете функция, която връща произведението на всички индекси,
93 | на който има нечетни числа.
94 | 95 | Пример: 96 | ``` 97 | Вход: 4 5 66 3 8 98 | Изход: 0 99 | ``` 100 | # 101 | 102 | 7. Напишете функция, която връща разликата на произведението на елементите
103 | с четни индекси (P) и сумата на елементите с нечетни индекси (S). (P - S) = ?
104 | 105 | Пример: 106 | ``` 107 | Вход: 4 2 7 4 1 108 | Изход: 22 109 | ``` 110 | # 111 | 112 | 8. Напишете функция, която връща сумата на всички елементи на масива,
113 | които имат повече вдигнати битове(1ци) отколкото свалени (0ли).
114 | # 115 | -------------------------------------------------------------------------------- /06_functions_array_basics/seminar/advanced_functions.cpp: -------------------------------------------------------------------------------- 1 | /**************************************************************************** 2 | * This file is part of the "Introduction to programming" course. FMI 2019/20 3 | *****************************************************************************/ 4 | 5 | /** 6 | * @file advanced_functions.cpp 7 | * @author Ivan Filipov 8 | * @date 11.2019 9 | * @brief More about functions - overloading, inline. 10 | * @see /05_functions/seminar/basic_functions.cpp for simple example 11 | */ 12 | 13 | #include 14 | 15 | // foo is a function with no arguments 16 | void foo() { 17 | 18 | std::cout << "foo() -> none" << std::endl; 19 | } 20 | 21 | // here foo takes one - int, so it's an overloaded version of foo 22 | int foo(int x) { 23 | 24 | std::cout << "foo(int) -> int" << std::endl; 25 | return x; 26 | } 27 | 28 | int foo(double x) { 29 | 30 | std::cout << "foo(double) -> int" << std::endl; 31 | return x; 32 | } 33 | 34 | int foo(int x, int y) { 35 | 36 | std::cout << "foo(int, int) -> int" << std::endl; 37 | return x + y; 38 | } 39 | 40 | 41 | // here we have two versions of divide -> 42 | // the compiler will call the one, which 43 | // fits the arguments better 44 | double divide(double x, double y) { 45 | 46 | std::cout << "divide(double, double) -> double:" << std::endl; 47 | return x / y; 48 | } 49 | 50 | int divide(int x, int y) { 51 | 52 | std::cout << "divide(int, int) -> int:" << std::endl; 53 | return x / y; 54 | } 55 | 56 | 57 | int main() { 58 | 59 | foo(); 60 | foo(42); 61 | foo(42.0); 62 | foo(42, 11); 63 | 64 | std::cout << "---------------------------------------" << std::endl; 65 | 66 | std::cout << 5 << " / " << 2 << " by " << divide(5, 2) << std::endl; 67 | std::cout << 5.0f << " / " << 2.0f << " by " << divide(5.0f, 2.0f) << std::endl; 68 | 69 | return 0; 70 | } 71 | -------------------------------------------------------------------------------- /06_functions_array_basics/seminar/array_basics.cpp: -------------------------------------------------------------------------------- 1 | /**************************************************************************** 2 | * This file is part of the "Introduction to programming" course. FMI 2019/20 3 | *****************************************************************************/ 4 | 5 | /** 6 | * @file array_basics.cpp 7 | * @author Ivan Filipov 8 | * @date 11.2019 9 | * @brief Some features of fixed size arrays - 10 | * initialize, pass to function, indexing. 11 | */ 12 | 13 | #include 14 | 15 | // those C-like arrays will have a fixed size 16 | // which should be known at compile time - 17 | // so consider using constants for those arrays 18 | // size_t is a typedef for unsigned int (possibly unsigned long int) 19 | size_t MAX_N = 10; 20 | 21 | // the arrays are always passed by pointer, 22 | // not by copy 23 | void print_array(int arr[], size_t arr_size) { 24 | 25 | for (size_t i = 0; i < arr_size; i++) 26 | std::cout << arr[i] << " "; // arr[i] in this context means -> read the element on index i from the array 27 | std::cout << std::endl << std::endl; 28 | } 29 | 30 | // the array parameter can have it's size in the [] brackets, 31 | // but that doesn't ensure nothing - the array can be with different size 32 | void print_fixed_arr(int arr[10]) { 33 | 34 | size_t size = sizeof(arr) / sizeof(int); // that won't work, because arr is actually treated as a pointer 35 | 36 | for (size_t i = 0; i < 10; i++) 37 | std::cout << arr[i] << " "; 38 | std::cout << std::endl; 39 | } 40 | 41 | void modify_array(int arr[], size_t size) { 42 | 43 | for (size_t i = 0; i < size; i++) 44 | arr[i] += i; // arr[i] in this context means -> write a value into the element on index i from the array 45 | } 46 | 47 | int main() { 48 | 49 | // initialize an array with initialization list, 50 | // when using [] the count of elements will be exactly the 51 | // number of elements in the list 52 | int array[] = { 1, 2, 3, 4 }; 53 | int size = sizeof(array) / sizeof(int); 54 | std::cout << "size of array(in elements): " << size << std::endl; 55 | std::cout << "array content: " << std::endl; 56 | print_array(array, size); 57 | 58 | 59 | 60 | int arr[MAX_N] = {1, 2, }; // all other will be filled automatically with zeroes 61 | 62 | std::cout << "size of arr(in elements): " << MAX_N 63 | << " calculated: " << sizeof(arr) / sizeof(int) 64 | << std::endl; 65 | std::cout << "arr content: " << std::endl; 66 | print_array(arr, MAX_N); 67 | 68 | modify_array(arr, MAX_N); 69 | std::cout << "arr content (after modifying): " << std::endl; 70 | print_array(arr, MAX_N); 71 | 72 | int unin_arr[MAX_N]; 73 | std::cout << "unin_arr content (uninitialized): " << std::endl; 74 | print_array(unin_arr, MAX_N); 75 | 76 | 77 | return 0; 78 | } 79 | -------------------------------------------------------------------------------- /06_functions_array_basics/seminar/materials.md: -------------------------------------------------------------------------------- 1 | ## Functions and array basics 2 | --- 3 | 4 | [Fuctions II](http://people.scs.carleton.ca/~dehne/projects/cpp-doc/tutorial/tut2-3.html) 5 | 6 | --- 7 | 8 | [Arrays](http://people.scs.carleton.ca/~dehne/projects/cpp-doc/tutorial/tut3-1.html) 9 | 10 | --- 11 | -------------------------------------------------------------------------------- /07_array_algos/practice/задачи.md: -------------------------------------------------------------------------------- 1 | # **Задачи - Алгоритми върху масиви** 2 | 3 | 0. Чрез "тресиране/проследяване" на следния фрагмет от програмен код: 4 | 5 | ```C++ 6 | #include 7 | 8 | int magic_function(int arr[], size_t element, int golemina) { 9 | 10 | int left = golemina / element + 1; 11 | int right = golemina - 1; 12 | 13 | int mid_ind, mid_val; 14 | 15 | while (left >= right) { 16 | 17 | mid_val = right + (left - right) / 2; 18 | mid_ind = arr[mid_val]; 19 | 20 | if (mid_val == golemina) { 21 | return mid_ind; 22 | } 23 | if (mid_val < golemina) { 24 | right = mid_ind; 25 | } 26 | if (mid_val > golemina) { 27 | left = mid_ind - 1; 28 | } 29 | } 30 | 31 | return -1; 32 | } 33 | 34 | int main() { 35 | 36 | int arr[] = { 1, 2, 3, 4, 5 }; 37 | 38 | if (magic_function(arr, sizeof(arr), 11)) 39 | std::cout << "Magic happened for 11!"; 40 | else 41 | std::cout << "11 is not that magical at all!"; 42 | 43 | } 44 | ``` 45 | 46 | 47 | Отговорете на върпосите: 48 | - Какво трябва да прави той? (На кой изучаван алгоритъм прилича?) 49 | - Кой са нужните промени, за да работи както трбява? 50 | - Въведете промените, които смятате, че са наложителни. 51 | - Проведете eмпирични опити с поне няколко различни набора от данни.
Не използвайте подход само със случайни числа,
ами се уверете, че кодът + вашите промени работи и в граничните случаи. 52 | # 53 | 1. Напишете функция, която проверява дали масив е сортиран в низходящ ред.
54 | 55 | Пример: 56 | ``` 57 | Вход: 23 20 7 5 1 58 | Изход: "The array is sorted in descending order" 59 | ``` 60 | # 61 | 62 | 2. Напишете функция, която вмъква елемент в сортиран във възходящ ред масив, като след
63 | вмъкването, масивът остава сортиран.
64 | Ако напълним целия масив, при следващо добавяне изваждаме съобщение за грешка
65 | 66 | Пример: 67 | ``` 68 | Вход: 1 4 7 12 32 59 69 | 15 70 | Изход: 1 4 7 12 15 32 59 71 | ``` 72 | # 73 | 74 | 3. Напишете функция, която изтрива елемент от сортиран във възходящ ред масив, като
75 | след изтриването, масивът остава сортиран.
76 | 77 | Пример: 78 | ``` 79 | Вход: 1 4 7 12 32 59 80 | 7 81 | Изход: 1 4 12 32 59 82 | ``` 83 | # 84 | 85 | 4. Напишете функция, която проверява дали масив е симтеричен
86 | (прочетен отляво надясно и отдясно наляво е един и същ).
87 | 88 | Пример: 89 | ``` 90 | Вход: 1 5 8 10 8 5 1 91 | Изход: "The array is simetric!" 92 | ``` 93 | # 94 | 95 | 5. Напишете фунцкия, която приема два масива arr_1 и arr_2, като
96 | "филтрира" всички четни елементи от arr_1 в arr_2 в сортиран вид.
97 | 98 | Пример: 99 | ``` 100 | arr_1: { 3, 12, 5, 2, 3, 8, 4 } 101 | arr_2: { 2, 4, 8, 12 } 102 | ``` 103 | # 104 | 105 | 6. Напишете функция, която обединява два сортирани масива в трети
106 | в сортиран вид (ще приемем че третият масив е с фиксирана големина 2*N,
107 | където N е големината на първия и втория масив arr_1[N], arr_2[N])
108 | 109 | Пример: 110 | ``` 111 | arr_1: { 10, 12, 15, 20, 31, 81 } 112 | arr_2: { 1, 7, 18, 20, 26, 102} 113 | arr_3: { 1, 7, 10, 12, 15, 18, 20, 20, 26, 31, 81, 102 } 114 | ``` 115 | # 116 | 117 | 7. Дадена е матрица А. Сортирайте всеки нейн ред поотделно в нарастващ ред,
118 | след което сортирайте и стълбовете и.
119 | # 120 | 121 | 8. Иванчо и Марийка - братче и сестричка решили да вдигат купон.
122 | Предварително се разбрали кой кого ще кани - Иванчо само момчета, а Марийка - само момичета.
123 | Дошла им идея да подредят гостите по височина. Всички поканени
124 | имали ръст - естествено число от интервала [150..200]. Ще им помогнете ли да
125 | групират гостите си по двойки - момче с момиче?
126 | Да се състави програма на C++, чрез която се генерират случайни естествени
127 | числа - 10 четни и 10 нечетни. Числата да се подредят последователно
128 | четно-нечетно във възходящ ред на височината на гостите от двата пола.
129 | 130 | Пример: 131 | ``` 132 | Височина на поканените гости: 133 | M201; L186; M163; L154; M207; L180; M153; L186; M183; L152; 134 | M185; L170; M161; L194; M197; L164; M175; L214; M161; L186; 135 | Изход: 136 | M 153; L 152 137 | M 161; L 154 138 | M 161; L 164 139 | M 163; L 170 140 | M 175; L 180 141 | M 183; L 186 142 | M 185; L 186 143 | M 197; L 186 144 | M 201; L 194 145 | M 207; L 214 146 | ``` 147 | # 148 | -------------------------------------------------------------------------------- /07_array_algos/seminar/eratosthenes_sieve.cpp: -------------------------------------------------------------------------------- 1 | /**************************************************************************** 2 | * This file is part of the "Introduction to programming" course. FMI 2019/20 3 | *****************************************************************************/ 4 | 5 | /** 6 | * @file eratosthenes_sieve.cpp 7 | * @author Ivan Filipov 8 | * @date 11.2019 9 | * @brief Example implementation of Eratosthenes algorithm 10 | * for finding out prime numbers below N. 11 | * 12 | * @see https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes 13 | */ 14 | 15 | #include 16 | 17 | #define PRIME false // all occurrences of "PRIME" will be replaced with false 18 | #define COMPOSITE true 19 | #define MAX_N 20000 20 | 21 | // array with markers 22 | // if sieve[i] == PRIME -> the number i is PRIME 23 | // note: that array will be initialized with zeros -> all values will be false (PRIME), because 24 | // the array is placed at the global memory. 25 | bool sieve[MAX_N] = { PRIME, }; 26 | 27 | // just output all prime numbers 28 | void print_primes() { 29 | 30 | for (unsigned long long int i = 2; i < MAX_N; i++) { 31 | if (sieve[i] == PRIME) { 32 | std::cout << i << " is a prime!" << std::endl; 33 | } 34 | } 35 | } 36 | 37 | // The algorithm's implementation 38 | void eratosthenes_sieve() { 39 | 40 | // for each number 41 | for (unsigned long long int i = 2; i < MAX_N; i++) { 42 | // if it is considered PRIME, mark all greater numbers, that are 43 | // dividable as COMPOSITE numbers 44 | if (sieve[i] == PRIME) { 45 | for (unsigned long long int j = i * i; j < MAX_N; j += i) { // the inner loops starts from i squared 46 | sieve[j] = COMPOSITE; 47 | } 48 | } 49 | } 50 | 51 | print_primes(); 52 | } 53 | 54 | int main() { 55 | 56 | eratosthenes_sieve(); 57 | return 0; 58 | } 59 | -------------------------------------------------------------------------------- /07_array_algos/seminar/materials.md: -------------------------------------------------------------------------------- 1 | ## Array algorithms 2 | --- 3 | 4 | ### General info: 5 | [Algorithm](https://en.wikipedia.org/wiki/Algorithm)
6 | [Pseudorandom generator](https://en.wikipedia.org/wiki/Pseudorandom_number_generator)
7 |
8 | [C/C++ rand](https://en.cppreference.com/w/cpp/numeric/random/rand)
9 | [C/C++ time](https://en.cppreference.com/w/cpp/chrono/c/time)
10 | [UNIX timestamp](https://en.wikipedia.org/wiki/Unix_time)
11 | 12 | --- 13 | 14 | ### Sorting: 15 | [Selection sort](https://en.wikipedia.org/wiki/Selection_sort) 16 | 17 | --- 18 | 19 | ### Searching: 20 | [Linear search](https://en.wikipedia.org/wiki/Linear_search)
21 | [Binary search](https://en.wikipedia.org/wiki/Binary_search_algorithm)
22 | [Searching visualizations](https://www.cs.usfca.edu/~galles/visualization/Search.html) 23 | 24 | --- 25 | 26 | ### See also: 27 | 28 | [Bubble sort](https://en.wikipedia.org/wiki/Bubble_sort)
29 | [Insertion sort](https://en.wikipedia.org/wiki/Insertion_sort)
30 | [Sorting algorithms visualizations](https://www.toptal.com/developers/sorting-algorithms) 31 | -------------------------------------------------------------------------------- /08_multidimensional_arrays/practice/задачи.md: -------------------------------------------------------------------------------- 1 | # **Задачи - Матрици** 2 | 3 | ***За всички задачи по-долу:***
4 | ***приемаме, че размерът за редовете и колоните на матрицата не по-голям от 100.***
5 | ***Нека е n, m са числа въведени от потребителя [1, 99].***
6 | 7 | 1. Напишете функция, която по въведени m, n инициализира елементите
8 | на матрица M(m x n) и функция, която изкарва стойностите на матрицата на екрана.
9 | # 10 | 2. Напишете функция, която връща най-малкия елемент на двумерен масив
11 | с големина m x n.
12 | 13 | Пример: 14 | ``` 15 | Вход: 4 4 3 6 5 7 16 | 5 2 9 6 17 | 8 1 4 8 18 | 3 6 1 8 19 | Изход: 1 20 | ``` 21 | # 22 | 3. Напишете функция, която по дадени число h и матрица М(m x n),
23 | умножава матрицата със скалара h.
24 | 25 | Пример: 26 | ``` 27 | Вход: 2 2 2 1 2 28 | 3 4 29 | Изход: 2 4 30 | 6 8 31 | ``` 32 | # 33 | 4. Напишете функция, която по дадени две матрици М(m x n) и T(m x n)
34 | cъбира двете матрици и резултата го записва в М(m x n).
35 | 36 | Пример: 37 | ``` 38 | Вход: 2 2 3 6 5 7 39 | 5 2 9 6 40 | Изход: 8 13 41 | 14 8 42 | ``` 43 | # 44 | 5. Напишете функция, която по дадена матрица М(m x n), изкарва на
45 | екрана първите и последните редове и стълбове на матрицата.
46 | 47 | Пример: 48 | ``` 49 | Вход: 4 3 3 6 8 50 | 5 2 9 51 | 6 8 2 52 | 4 6 7 53 | 54 | Изход: 3 6 8 55 | 5 9 56 | 6 2 57 | 4 6 7 58 | ``` 59 | # 60 | 6. Напишете функция, която изкарва на екрана стойностите на двата
61 | диагонала на матрица M(n x n).
62 | 63 | Пример: 64 | ``` 65 | Вход: 4 4 3 6 5 7 66 | 5 2 9 6 67 | 8 1 4 8 68 | 3 6 1 8 69 | 70 | Изход: 3 7 71 | 2 9 72 | 1 4 73 | 3 8 74 | ``` 75 | # 76 | 7. Напишете функция, която намира сумата на всички елементи над
77 | главния диагонал на матрица M(n x m), умножава сумата по броя на нечетните
78 | елементи под главния диагонал и след това я отпечатва на екрана.
79 | 80 | Пример: 81 | ``` 82 | Вход: 3 4 1 2 3 4 83 | 5 6 7 8 84 | 9 10 11 12 85 | 86 | сумата: 2 + 3 + 4 + 7 + 8 + 12 = 36 87 | броя на нечетните под диагонала: 2 ( 5 и 9 ) 88 | 89 | Изход: 72 90 | ``` 91 | 8. Под “седлова” точка на матрица M(n x m), ще разбираме такъв елемент
92 | на матрицата, който е с максимална стойност в реда и минимална стойност на
93 | колоната, на които принадлежи.
94 | Напишете функция, която по подадена матрица и нейните размери,
95 | определя координатите на “седловата” си точка.
96 | *Забележете, че не всяка матрица притежава “седлова” точка, ако подадената*
97 | *матрица няма таква, то от програмата ви се очаква да отпечата съобщение за грешка.*
98 | 99 | Пример: 100 | ``` 101 | Вход: 3 3 1 9 1 102 | 4 3 2 103 | 7 8 9 104 | Изход: *съобщение за грешка : няма такава точка” 105 | ``` 106 | 107 | Пример: 108 | ``` 109 | Вход: 3 3 1 6 3 110 | 2 5 4 111 | 3 7 6 112 | Изход: елементът с индекси ( 1 , 1 ) е “седлова” точка на матрицата, неговата стойност е: 5 113 | ``` 114 | -------------------------------------------------------------------------------- /08_multidimensional_arrays/seminar/materials.md: -------------------------------------------------------------------------------- 1 | ## Multidimensional arrays 2 | --- 3 | 4 | [2D (matrices)](https://beginnersbook.com/2014/01/2d-arrays-in-c-example/) 5 | 6 | --- 7 | 8 | [Multidimensional arrays](https://beginnersbook.com/2017/08/cpp-multidimensional-arrays/) 9 | 10 | [Arrays 2D, 3D](http://people.scs.carleton.ca/~dehne/projects/cpp-doc/tutorial/tut3-1.html) 11 | 12 | --- 13 | 14 | ### See also: 15 | [Raster graphics](https://en.wikipedia.org/wiki/Raster_graphics) 16 | 17 | [Image processing](https://en.wikipedia.org/wiki/Kernel_(image_processing)) 18 | -------------------------------------------------------------------------------- /08_multidimensional_arrays/seminar/matrices.cpp: -------------------------------------------------------------------------------- 1 | /**************************************************************************** 2 | * This file is part of the "Introduction to programming" course. FMI 2019/20 3 | *****************************************************************************/ 4 | 5 | /** 6 | * @file matrices.cpp 7 | * @author Ivan Filipov 8 | * @date 11.2019 9 | * @brief Example for working with 2D arrays (Matrices). 10 | */ 11 | 12 | 13 | #include 14 | #include 15 | #include // std::rand(), std::srand() 16 | #include // std::time() 17 | #include // std::log10() 18 | 19 | const size_t MAX_ROW = 10; // max number of rows 20 | const size_t MAX_COL = 10; // max number of columns (how many elements each row will have) 21 | const int MAX_EL = 11; // maximum value for the random fill 22 | 23 | 24 | // print a matrix 25 | // notice: the matrix is passed to the function with number of columns specialized! 26 | // we pass a "large enough" matrix, than the parameters rows and cols describe the 27 | // real logical size of the matrix 28 | void print_mat(int mat[][MAX_COL], size_t rows, size_t cols) { 29 | 30 | int cells = (int)std::log10(MAX_EL) + 1; 31 | for (size_t i = 0; i < rows; i++) { 32 | for (size_t j = 0; j < cols; j++) { 33 | std::cout << std::setw(cells) << mat[i][j] << ' '; 34 | } 35 | std::cout << std::endl; 36 | } 37 | } 38 | 39 | // fill the matrix with random numbers 40 | void init_mat(int mat[][MAX_COL], size_t rows, size_t cols) { 41 | 42 | for (size_t i = 0; i < rows; i++) 43 | for (size_t j = 0; j < cols; j++) 44 | mat[i][j] = std::rand() % MAX_EL; 45 | } 46 | 47 | // find the sum of the main diagonal of a given matrix 48 | // notice: the matrix could be square or not 49 | int sum_main_diagonal(int mat[][MAX_COL], size_t rows, size_t cols) { 50 | 51 | int sum = 0; 52 | 53 | /* slower and sillier way: 54 | for (size_t i = 0; i < rows; i++) 55 | for (size_t j = 0; j < cols; j++) 56 | if (i == j) 57 | sum += mat[i][j]; 58 | */ 59 | 60 | // better way: all element on the main diagonal have same x, y coordinates 61 | for (size_t i = 0; i < rows; i++) 62 | sum += mat[i][i]; 63 | 64 | return sum; 65 | } 66 | 67 | // find the sum of elements from a given matrix row 68 | // notice: the row is actually a 1D array 69 | int sum_row(int arr[], size_t size) { 70 | 71 | int sum = 0; 72 | for (size_t i = 0; i < size; i++) 73 | sum += arr[i]; 74 | 75 | return sum; 76 | } 77 | 78 | // find the multiplication of sums for each row 79 | int mul_sum_row(int mat[][MAX_COL], size_t rows, size_t cols) { 80 | 81 | int pr = 1; 82 | for (size_t row = 0; row < rows; row++) // for each row 83 | pr *= sum_row(mat[row], cols); // pass the row to the function and get the sum 84 | 85 | return pr; 86 | } 87 | 88 | int main() { 89 | 90 | // fixed and initialized matrix: 91 | const int L_SIZE = 3; // logical size 92 | int fixed_mat[][MAX_COL] = { 93 | { 1, 2, 3 }, // fixed_mat[0] (a.k.a first row) 94 | { 4, 5, 6 }, // second row 95 | { 7, 8, 9 }, // third row 96 | }; 97 | 98 | std::cout << "Fixed matrix:" << std::endl; 99 | print_mat(fixed_mat, L_SIZE, L_SIZE); 100 | 101 | 102 | // initialize a random matrix: 103 | size_t rows, cols; 104 | std::cout << "Enter number of rows [0, " << MAX_ROW << "]:" << std::endl; 105 | std::cin >> rows; 106 | std::cout << "Enter number of columns [0, " << MAX_COL << "]:" << std::endl; 107 | std::cin >> cols; 108 | 109 | if (rows >= MAX_ROW || cols >= MAX_COL) { 110 | std::cout << "Invalid input" << std::endl; 111 | return 1; 112 | } 113 | 114 | // create "large enough" matrix 115 | int mat[MAX_ROW][MAX_COL]; 116 | // initialize the random generator 117 | std::srand(std::time(0)); 118 | // fill the matrix 119 | init_mat(mat, rows, cols); 120 | // output it 121 | std::cout << "The randomly generated matrix looks like:" << std::endl; 122 | print_mat(mat, rows, cols); 123 | 124 | std::cout << "Sum of elements on the main diagonal: " << sum_main_diagonal(mat, rows, cols) << std::endl; 125 | std::cout << "Product of rows sums: " << mul_sum_row(mat, rows, cols) << std::endl; 126 | 127 | return 0; 128 | } 129 | -------------------------------------------------------------------------------- /09_memory_management/practice/задачи.md: -------------------------------------------------------------------------------- 1 | # **Задачи - Динамична памет** 2 | 3 | ***За тези задачи е нужно да се грижите за заделената от вас***
4 | ***памет - да бъде заделяна и освобождавана правилно.
*** 5 | 6 | 1. Реализирайте функциите push_back/pop_back, които добавят/премахват елемент
7 | на последна позиция в динамичен масив.
8 | 9 | Пример: 10 | ``` 11 | Вход: 9 11 42 12 12 | push_back 5 -> 9 11 42 12 5 13 | pop_back -> 9 11 42 12 14 | ``` 15 | # 16 | 2. Реализирайте функции insert_at(index, element)/remove_at(index), които
17 | добавят/премахват елемент на дадена позиция в динамичен масив.
18 | 19 | Пример: 20 | ``` 21 | Вход: 8 12 92 32 4 22 | insert_at 4 123 -> 8 12 92 32 123 4 23 | remove_at 1 -> 8 92 32 123 4 24 | ``` 25 | # 26 | 3. Реализирайте функция, която филтрира всички прости числа от зададен динамичен масив.
27 | 28 | Пример: 29 | ``` 30 | Вход: 3 5 8 7 11 24 42 31 | Изод: 3 5 7 11 32 | ``` 33 | # 34 | 4. Реализирайте функция, която обединява два сортирани динамични масива,
35 | като резултатния масив остава сортиран.
36 | 37 | Пример: 38 | ``` 39 | Вход: 1 3 5 10 21 40 | 2 7 12 32 41 | Изход: 1 2 3 5 7 10 12 21 32 42 | ``` 43 | # 44 | 5. Реализирайте функция, която при подадена динамична матрица
45 | премахва редовете с нечетна сума.
46 | 47 | *Забележка: не използвайте допълнителна памет.*
48 | 49 | Пример: 50 | ``` 51 | Вход: 1 4 2 7 52 | 8 1 5 6 53 | 9 2 4 8 54 | 55 | Изход: 1 4 2 7 56 | 8 1 5 6 57 | ``` 58 | # 59 | 6. Реализирайте функция, която създава 'назъбена'
60 | матрица(с различен брой колони на всеки ред).
61 | Напишете друга функция, която сортира матрицата по дължината на редовете и.
62 | 63 | *Забележка: не използвайте допълнителна памет.*
64 | 65 | Пример: 66 | ``` 67 | Вход: 1 8 3 5 68 | 8 2 69 | 5 1 5 2 1 5 9 70 | 2 8 6 1 7 71 | 1 72 | 73 | Изход: 1 74 | 8 2 75 | 1 8 3 5 76 | 2 8 6 1 7 77 | 5 1 5 2 1 5 9 78 | ``` 79 | # 80 | -------------------------------------------------------------------------------- /09_memory_management/seminar/dynamic_array.cpp: -------------------------------------------------------------------------------- 1 | /**************************************************************************** 2 | * This file is part of the "Introduction to programming" course. FMI 2019/20 3 | *****************************************************************************/ 4 | 5 | /** 6 | * @file dynamic_array.cpp 7 | * @author Ivan Filipov 8 | * @date 12.2019 9 | * @brief Working with dynamically allocated arrays. 10 | */ 11 | 12 | #include 13 | #include // std::time() 14 | #include // std::rand(), std::srand() 15 | 16 | const size_t MAX_SIZE = 10; // array max size 17 | const int MAX_ELEM_VAL = 100; // maximum value for filling arrays 18 | 19 | // initialize an array with random values 20 | void init_arr(int* p_arr, size_t size) { 21 | 22 | if (p_arr == nullptr) return; 23 | 24 | for (size_t i = 0; i < size; i++) 25 | p_arr[i] = std::rand() % (MAX_ELEM_VAL + 1); 26 | } 27 | 28 | // simply output an array content 29 | void print_arr(int* p_arr, size_t size) { 30 | 31 | if (p_arr == nullptr) return; 32 | 33 | std::cout << "The array starts at: " << p_arr << std::endl; 34 | for (size_t i = 0; i < size; i++) 35 | std::cout << p_arr[i] << ' '; 36 | std::cout << std::endl; 37 | } 38 | 39 | // doubles the memory allocated for an array pointed by p_arr 40 | // we take the pointer by reference, because we will redirecting it. 41 | // If not taken by ref, only the local copied pointer will be redirected, 42 | // which will cause the dangling of the pointer in the main. 43 | void realloc_arr(int*& p_arr, size_t& size) { 44 | 45 | if (p_arr == nullptr) return; 46 | 47 | // allocated new memory 48 | int* new_mem = new (std::nothrow) int[size * 2]; 49 | if (!new_mem) { // check if the allocation was successful 50 | std::cout << "Reallocating have failed." << std::endl; 51 | return; 52 | } 53 | // 54 | // copy all old elements 55 | for (size_t i = 0; i < size; i++) 56 | new_mem[i] = p_arr[i]; 57 | // 58 | // free the old array 59 | delete[] p_arr; 60 | // redirect the given pointer to the new memory 61 | p_arr = new_mem; 62 | // double the logical size 63 | size *= 2; 64 | // 65 | } 66 | 67 | 68 | int main() { 69 | 70 | // trying to allocate too much memory 71 | int* p_arr = new (std::nothrow) int[212110210211L]; 72 | if (p_arr == nullptr) { 73 | std::cout << "Not enough memory..." << std::endl; 74 | } 75 | // 76 | 77 | srand(time(nullptr)); 78 | 79 | size_t size; 80 | std::cout << "Enter base size for the array:"; 81 | std::cin >> size; 82 | 83 | int* pd_arr = new (std::nothrow) int[size]; 84 | if (pd_arr == nullptr) { 85 | std::cout << "Not enough memory..." << std::endl; 86 | return 1; 87 | } 88 | 89 | init_arr(pd_arr, size); 90 | std::cout << "Allocated array with random elements:" << std::endl; 91 | print_arr(pd_arr, size); 92 | 93 | 94 | realloc_arr(pd_arr, size); 95 | std::cout << "Reallocated array with random elements and uninitialized ones:" 96 | << std::endl; 97 | print_arr(pd_arr, size); 98 | 99 | // don't forget to free the allocated memory. 100 | delete[] pd_arr; 101 | 102 | return 0; 103 | } 104 | -------------------------------------------------------------------------------- /09_memory_management/seminar/dynamic_matrix.cpp: -------------------------------------------------------------------------------- 1 | /**************************************************************************** 2 | * This file is part of the "Introduction to programming" course. FMI 2019/20 3 | *****************************************************************************/ 4 | 5 | /** 6 | * @file dynamic_matrix.cpp 7 | * @author Ivan Filipov 8 | * @date 12.2019 9 | * @brief Working with dynamically allocated matrices. 10 | */ 11 | 12 | #include 13 | #include 14 | #include // std::time() 15 | #include // std::rand(), std::srand() 16 | 17 | const int MAX_ELEM_VAL = 100; // limit for randomly generated numbers 18 | const int NCELLS = 3; // number of cells for output formatting 19 | 20 | // forward declaration, because we want to 'see' it from init_mat 21 | void clear_mat(int**&, size_t); 22 | 23 | // mat is a pointer to pointers (will be pointing an array of pointers) 24 | // we take the pointer by reference, because we will redirecting it. 25 | // If not taken by ref, only the local copied pointer will be redirected, 26 | // which will cause the dangling of the pointer in the main. 27 | bool init_mat(int**& mat, size_t n, size_t m) { 28 | // allocate array of pointers (will be pointing to the rows) 29 | mat = new (std::nothrow) int* [n]; 30 | // if the allocating was unsuccessful, just return 31 | if (!mat) return false; 32 | // 33 | for (size_t i = 0; i < n; i++) { 34 | // allocate the current row 35 | mat[i] = new (std::nothrow) int[m]; 36 | // if unsuccessful, we should go back and 37 | // free all previously allocated memory 38 | if (!mat[i]) { 39 | clear_mat(mat, i - 1); 40 | return false; 41 | } 42 | } 43 | // if we got here, all the allocations were successful, 44 | // we proceed with the initialization of each element. 45 | for (size_t i = 0; i < n; i++) 46 | for (size_t j = 0; j < m; j++) 47 | mat[i][j] = rand() % MAX_ELEM_VAL; 48 | // 49 | return true; 50 | } 51 | 52 | // just output a matrix's content. 53 | // notice: here we DO NOT have to pass the pointer 54 | // by reference, because we are not going to redirect it. 55 | void print_mat(int** mat, size_t n, size_t m){ 56 | 57 | if (!mat) return; 58 | 59 | for (size_t i = 0; i < n; i++) { 60 | for (size_t j = 0; j < m; j++) 61 | std::cout << std::setw(NCELLS) << mat[i][j]; 62 | std::cout << std::endl; 63 | } 64 | } 65 | 66 | // frees the allocated memory for a matrix 67 | void clear_mat(int**& mat, size_t n) { 68 | 69 | if (!mat) return; 70 | 71 | // free the memory for each line 72 | for (size_t i = 0; i < n; i++) 73 | delete[] mat[i]; 74 | 75 | // free the memory for the array of pointers 76 | delete[] mat; 77 | 78 | // if we don't have this line, we can pass the pointer without ref, 79 | // but we want to assure that `mat` is in a valid state, it just 80 | // doesn't point to an allocated memory 81 | mat = nullptr; 82 | } 83 | 84 | int main() { 85 | 86 | srand(time(nullptr)); 87 | 88 | size_t n, m; 89 | int** mat = nullptr; 90 | 91 | std::cout << "Enter n and m (matrix size):" << std::endl; 92 | std::cin >> n >> m; 93 | 94 | init_mat(mat, n, m); 95 | print_mat(mat, n, m); 96 | clear_mat(mat, n); 97 | 98 | return 0; 99 | } 100 | -------------------------------------------------------------------------------- /09_memory_management/seminar/materials.md: -------------------------------------------------------------------------------- 1 | ## Memory management 2 | 3 | From now on, each variable will have those features: 4 | - type (int, double, etc.) 5 | - name (how we refer to that variable) 6 | - storage size (how much memory the variable takes in bytes) 7 | - storage type (in which type of memory the variable is stored) 8 | - address (where in the memory is our variable) 9 | - scope (from where we can see/access the defined variable) 10 | - lifetime (when the variable is created and when destroyed) 11 | 12 | --- 13 | 14 | [Address space](https://en.wikipedia.org/wiki/Address_space) 15 | 16 | [Address space/Virtual memory](https://sites.ualberta.ca/dept/chemeng/AIX-43/share/man/info/C/a_doc_lib/aixprggd/genprogc/address_space.htm) 17 | 18 | --- 19 | 20 | [Pointers/Arithmetic of pointers](http://people.scs.carleton.ca/~dehne/projects/cpp-doc/tutorial/tut3-3.html) 21 | 22 | [References](https://en.wikipedia.org/wiki/Reference_(C%2B%2B)) 23 | 24 | --- 25 | 26 | [Types of memory](https://doc.lagout.org/programmation/C/Understanding%20and%20Using%20C%20Pointers%20%5BReese%202013-05-18%5D.pdf) - Chapter 1. 27 | 28 | [Dynamic memory](http://people.scs.carleton.ca/~dehne/projects/cpp-doc/tutorial/tut3-4.html) 29 | 30 | 31 | --- 32 | ### Consider also: 33 | Reading the whole book [Understanding and using C pointers](https://doc.lagout.org/programmation/C/Understanding%20and%20Using%20C%20Pointers%20%5BReese%202013-05-18%5D.pdf), will help you to fully understand what is the deal with pointers and memory management. 34 | -------------------------------------------------------------------------------- /09_memory_management/seminar/memory_classes.cpp: -------------------------------------------------------------------------------- 1 | /**************************************************************************** 2 | * This file is part of the "Introduction to programming" course. FMI 2019/20 3 | *****************************************************************************/ 4 | 5 | /** 6 | * @file memory_classes.cpp 7 | * @author Ivan Filipov 8 | * @date 12.2019 9 | * @brief Example about different memory classes - 10 | * automatic, static, dynamic. 11 | */ 12 | 13 | 14 | #include 15 | 16 | /* 17 | For each type of memory we will take a look at those features: 18 | - scope (from where we can see/access the defined variable); 19 | - lifetime (when the variable is created and when destroyed). 20 | */ 21 | 22 | /* 23 | Global variables and global static variable belong to the 24 | static memory class. They are initialized with zeros by default. 25 | They are created before entering the main function. 26 | Their lifetime is the lifetime of the application. 27 | */ 28 | int global_var; 29 | static int static_global_var; 30 | // for the `static` specifier - there is a slight difference, 31 | // which will be discussed during OOP course. 32 | 33 | void call_me() { 34 | // this variable also belong to Static memory class, 35 | // but is created on the first function call. 36 | // It is destroyed when the application ends. 37 | static int call_cnt = 0; 38 | 39 | std::cout << "Total calls: " << call_cnt++ << std::endl; 40 | } 41 | 42 | void local_vars() { 43 | /* 44 | Local variables - belong to Automatic memory class, they are allocated on the Stack. 45 | These variables are declared within a function and are created when a function is called. 46 | Their scope is restricted to the function and their lifetime is limited to the time 47 | the function is executing. 48 | */ 49 | 50 | int x = 11; 51 | std::cout << "Local variable x: " << x << " at " 52 | << &x << std::endl; 53 | 54 | if (true) { 55 | int y = 21; 56 | // here we can use both x, y and global variables 57 | } // y got destroyed 58 | 59 | } // here x is destroyed 60 | 61 | void dynamic_vars() { 62 | 63 | /* 64 | Dynamic class memory - 65 | Memory is allocated from the heap and can be released when necessary. 66 | A pointer references the allocated memory. 67 | The scope is limited to the pointer or pointers that reference the memory. 68 | It exists until it is released. 69 | */ 70 | int* dynamic_int = new int; 71 | *dynamic_int = 11; 72 | std::cout << "Dynamic int allocated at: " << dynamic_int 73 | << " and has value of: " << *dynamic_int << std::endl; 74 | 75 | // we are responsible for dynamic memory releasing! 76 | delete dynamic_int; 77 | } // here the pointer `dynamic_int` is destroyed. If we haven't called 78 | // delete dynamic_int; - the pointer to the dynamic memory is lost and the memory - LEAKED! 79 | 80 | int main() { 81 | 82 | local_vars(); 83 | dynamic_vars(); 84 | 85 | call_me(); 86 | call_me(); 87 | call_me(); 88 | 89 | return 0; 90 | } 91 | -------------------------------------------------------------------------------- /09_memory_management/seminar/pointers_arrays.cpp: -------------------------------------------------------------------------------- 1 | /**************************************************************************** 2 | * This file is part of the "Introduction to programming" course. FMI 2019/20 3 | *****************************************************************************/ 4 | 5 | /** 6 | * @file pointer_arrays.cpp 7 | * @author Ivan Filipov 8 | * @date 12.2019 9 | * @brief Example about relationship between pointers and arrays. 10 | */ 11 | 12 | #include 13 | 14 | /* forward declarations read below */ 15 | void print_arr(int* arr, size_t size); 16 | 17 | int main() { 18 | 19 | // we know that an array is a sequence of variables 20 | // placed continuously (as a block) into the memory 21 | int arr[] = { 1, 2, 3, 4 }; 22 | size_t arr_size = sizeof(arr) / sizeof(int); 23 | 24 | for (size_t i = 0; i < arr_size; i++) 25 | std::cout << "arr[" << i << "] = " << arr[i] 26 | << " placed at: " << &arr[i] << std::endl; 27 | 28 | std::cout << std::endl; 29 | std::cout << "the array begins at: " << arr; // the name of the array is actually an address 30 | std::cout << std::endl; 31 | 32 | // so we can direct a pointer to the array's beginning: 33 | int* p = arr; // p points to the beginning of arr 34 | int* p1 = &arr[0]; // p1, also, why? 35 | 36 | std::cout << "p points to: " << p 37 | << " and the pointed value is: " << *p 38 | << std::endl; 39 | 40 | // there are operations with pointers called "pointers arithmetic" 41 | p = p + 3; // when adding/removing an number to/from a pointer 42 | // we actually move it with that number multiplied by pointer's type 43 | // addresses forward/backward. 44 | // so here we have moved `p` with 3 * sizeof(int) addresses forward, guess what is placed at that address? 45 | std::cout << "After moving - p points to: " << p 46 | << " and the pointed value is: " << *p 47 | << std::endl; 48 | std::cout << std::endl; 49 | 50 | // now we can understand what is the compiler does, when we use [] operator on an array: 51 | std::cout << "arr[3] = " << arr[3] << std::endl; 52 | std::cout << "*(arr + 3) = " << *(arr + 3) << std::endl; 53 | // arr[i] <=> *(arr + i) 54 | std::cout << std::endl; 55 | 56 | 57 | // same can be done with matrices, because as we know, 58 | // they are a block of arrays with fixed size, placed one after 59 | // another in the memory 60 | int mat[2][3] = { 61 | { 1, 2, 3 }, 62 | { 11, 5, 6 } 63 | }; 64 | // that is equivalent to int mat[2 * 3]; 65 | 66 | 67 | int* mat_base = &mat[0][0]; 68 | std::cout << "The matrix is allocated at: " << mat << std::endl; 69 | std::cout << "&mat[0][0] is: " << mat_base << std::endl; 70 | 71 | // We can compute the address of an element of the matrix 72 | // using the rows and columns. For this we use the following formula: 73 | // mat[i][j] = base_address + [(i x no_of_cols + j) x size_of_data_type] 74 | std::cout << "mat[1][2] = " << mat[1][2] << std::endl; 75 | //int* m_base = (int*)mat; // could also do the trick, mat is int (*)[3] 76 | std::cout << "*(mat_base + 1 * 3 + 2) = " << *(mat_base + (1 * 3 + 2)) << std::endl; 77 | 78 | // or also: 79 | std::cout << "*(*(mat + 1) + 2) = " << *(*(mat + 1) + 2) << std::endl; 80 | // here mat is of type (*)[3], so (mat + 1) gives a pointer to first row, dereferencing it 81 | // we got an address - where that row starts, than adding 2 (as in 1D array). 82 | 83 | // DO NOT write code like above - always prefer [] syntax! 84 | std::cout << std::endl; 85 | 86 | std::cout << "Printing array with function using pointer: " << std::endl; 87 | print_arr(arr, arr_size); 88 | std::cout << std::endl; 89 | 90 | std::cout << "Printing matrix with function using pointer: " << std::endl; 91 | print_arr(mat_base, 2 * 3); 92 | 93 | return 0; 94 | } 95 | 96 | // we can print array or matrix, or even more D object, by just passing 97 | // it's beginning and type as a pointer of that type 98 | void print_arr(int* arr, size_t size) { 99 | 100 | for (size_t i = 0; i < size; i++) 101 | std::cout << arr[i] << ' '; 102 | std::cout << std::endl; 103 | 104 | // or like an absolute hacker: 105 | std::cout << "As a hacker:" << std::endl; 106 | int i = 0; 107 | while (i < size) { 108 | // here we first make *arr -> get currently point value, 109 | // than arr = arr + 1 -> move pointer with one position 110 | std::cout << *arr++ << ' '; 111 | i++; 112 | } 113 | std::cout << std::endl; 114 | } 115 | -------------------------------------------------------------------------------- /09_memory_management/seminar/pointers_basics.cpp: -------------------------------------------------------------------------------- 1 | /**************************************************************************** 2 | * This file is part of the "Introduction to programming" course. FMI 2019/20 3 | *****************************************************************************/ 4 | 5 | /** 6 | * @file pointers_basics.cpp 7 | * @author Ivan Filipov 8 | * @date 12.2019 9 | * @brief Example syntax and usage of pointers. 10 | */ 11 | 12 | #include 13 | 14 | // forward declaration, see below for details. 15 | void swap_with_ptr(int* a, int* b); 16 | 17 | int main() { 18 | // each variable has: 19 | // - type 20 | // - name 21 | // - value 22 | // - address (where in the memory it is) 23 | // - storage type (type of memory) 24 | int x = 11; 25 | std::cout << "x: " << x << " at " 26 | << &x << std::endl; // with operator& we can extract the address of a variable 27 | 28 | // pointers are special type of variables, their values are addresses of other variables 29 | // here p_x is a pointer to a integer 30 | int* p_x = &x; // p_x points to x (p_x has a value - address of the variable x) 31 | 32 | // pointers are also variables, so &p_x gives us the address of the pointer itself 33 | // p_x is the value of the pointer -> the address of the pointed object 34 | // *p_x extracts the value of the pointed object (dereferencing) 35 | std::cout << "p_x: " << p_x << " at " 36 | << &p_x << " pointed value: " << *p_x << std::endl; 37 | std::cout << std::endl; 38 | // we can change the value of the pointed variable though the pointer 39 | *p_x = 23; 40 | 41 | std::cout << "x: " << x << " at " 42 | << &x << std::endl; 43 | 44 | std::cout << "p_x: " << p_x << " at " 45 | << &p_x << " pointed value: " << *p_x << std::endl; 46 | std::cout << std::endl; 47 | // 48 | 49 | // we have a special value (NULL/nullptr), which has the meaning of 50 | // "this pointer currently points to NOTHING". (NULL is C-style, nullptr - C++). 51 | int* p = nullptr; // NULL 52 | //!!! trying to get the value of a pointer, which points to NULL, will result in program's termination. 53 | // tryme: 54 | // std::cout << p << ' ' << *p; 55 | int* p_i; // we can declare a pointer without initialization, we DO NOT know where it is pointing. 56 | p_i = &x; // p_i now points to x 57 | int* p2; 58 | p2 = p_i; // p_i now points where p1 points 59 | // 60 | 61 | // all pointers have the same size in bytes. Enough to contain the largest possible address value. 62 | // The size actually depends on the platform. 63 | char c; 64 | double d; 65 | 66 | char* p_c = &c; 67 | double* d_p = &d; 68 | std::cout << "size of pointer to char: " << sizeof(p_c) 69 | << "bytes (which is " << sizeof(p_c) * 8 << "bits)" 70 | << std::endl; 71 | std::cout << "size of pointer to int: " << sizeof(p_i) 72 | << "bytes (which is " << sizeof(p_i) * 8 << "bits)" 73 | << std::endl; 74 | std::cout << "size of pointer to double: " << sizeof(d_p) 75 | << "bytes (which is " << sizeof(d_p) * 8 << "bits)" 76 | << std::endl; 77 | std::cout << std::endl; 78 | // 79 | 80 | // usage of the swap function with pointers 81 | int z = 10, y = 27; 82 | std::cout << "z and y before swapping them: " << z << ' ' << y << std::endl; 83 | swap_with_ptr(&z, &y); 84 | std::cout << "z and y after swapping them: " << z << ' ' << y << std::endl; 85 | // 86 | 87 | 88 | // all possible combination of const and * 89 | int* ptr_to_int; // normal pointer to integer 90 | const int* ptr_to_const_int; // pointer to a constant integer (we can't change the pointed value!) 91 | // same as int const* p; 92 | 93 | // constant pointer to integer. 94 | // we CANNOT redirect the pointer, but we CAN change the pointed value. 95 | int* const const_ptr_to_int = ptr_to_int; 96 | 97 | const int c_int = 10; 98 | // constant pointer to a constant integer. 99 | // The most restricted, NOTHING can be changed. 100 | const int* const const_ptr_to_const_int = &c_int; 101 | 102 | return 0; 103 | } 104 | 105 | 106 | // As we know all function parameters are passed by copy. 107 | // That is why the standard version won't work - it will only swap the LOCAL COPIES. 108 | // But we can achieve the swap using pointers. 109 | // `a` is a pointer to the first variable, `b` to the other. 110 | void swap_with_ptr(int* a, int* b) { 111 | // `t` is a normal integer 112 | int t = *a; // assign `t` the value of the pointed by `a` variable 113 | *a = *b; // assign the pointed by `a` variable the value of the pointed by `b` 114 | *b = t; // assign the pointed by `b` variable the value of `t` 115 | } 116 | -------------------------------------------------------------------------------- /09_memory_management/seminar/references_basics.cpp: -------------------------------------------------------------------------------- 1 | /**************************************************************************** 2 | * This file is part of the "Introduction to programming" course. FMI 2019/20 3 | *****************************************************************************/ 4 | 5 | /** 6 | * @file references_basics.cpp 7 | * @author Ivan Filipov 8 | * @date 12.2019 9 | * @brief Example syntax and usage of references. 10 | */ 11 | 12 | #include 13 | 14 | // forward declaration, see below for details. 15 | void swap_with_ref(int& a, int& b); 16 | 17 | int main() { 18 | // each variable has: 19 | // - type 20 | // - name 21 | // - value 22 | // - address (where in the memory it is) 23 | // - storage type (type of memory) 24 | int x = 11; 25 | std::cout << "x: " << x << " at " 26 | << &x << std::endl; 27 | 28 | // References have the meaning of (different name for an existing object). 29 | // references are syntax sugar for constant pointer (pointers, which CANNOT be redirected). 30 | // but with a few key differences: 31 | // - there is NOT a NULL value for references. 32 | // - a reference SHOULD always be initialized (there is no such rule for pointers). 33 | // - a reference CANNOT be redirected (it is a different name for a single object). 34 | int& x_ref = x; // x_ref is a reference to x 35 | 36 | std::cout << "x_ref: " << x_ref << " at " 37 | << &x_ref << std::endl; 38 | std::cout << std::endl; 39 | 40 | x_ref = 23; // change the value though the reference 41 | 42 | std::cout << "x: " << x << " at " 43 | << &x << std::endl; 44 | std::cout << "x_ref: " << x_ref << " at " 45 | << &x_ref << std::endl; 46 | std::cout << std::endl; 47 | 48 | /* 49 | There is no standard rule how 50 | references should be implemented and 51 | what their sizes are. 52 | */ 53 | 54 | 55 | // we can have a reference to constant variable, 56 | // which means we CANNOT change the referred value. 57 | const int& c_x_ref = x; 58 | 59 | 60 | // usage of the swap function with references 61 | int z = 10, y = 27; 62 | std::cout << "z and y before swapping them: " << z << ' ' << y << std::endl; 63 | swap_with_ref(z, y); 64 | std::cout << "z and y after swapping them: " << z << ' ' << y << std::endl; 65 | // 66 | 67 | // References are extremely useful for: 68 | // avoiding copies, write functions which change their parameters and etc. 69 | // But they are much more limited compared to pointers. 70 | 71 | return 0; 72 | } 73 | 74 | // unlike the pointers, the syntax here is much simpler. 75 | void swap_with_ref(int& a, int& b) { 76 | int t = a; 77 | a = b; 78 | b = t; 79 | } 80 | -------------------------------------------------------------------------------- /10_strings/practice/strings_advanced/one_time_pad.txt: -------------------------------------------------------------------------------- 1 | 32 2 | 0x64 0x62 0x66 0x62 0x32 0x36 0x62 0x66 3 | 0x39 0x32 0x61 0x35 0x39 0x34 0x30 0x33 4 | 0x36 0x35 0x63 0x30 0x65 0x36 0x65 0x62 5 | 0x32 0x61 0x33 0x61 0x38 0x33 0x39 0x63 6 | -------------------------------------------------------------------------------- /10_strings/practice/strings_advanced/solution_01.cpp: -------------------------------------------------------------------------------- 1 | /**************************************************************************** 2 | * This file is part of the "Introduction to programming" course. FMI 2019/20 3 | *****************************************************************************/ 4 | 5 | /** 6 | * @file solution_01.cpp 7 | * @author Ivan Filipov 8 | * @author Kristian Krastev 9 | * @date 01.2020 10 | * @brief Solution for task 1 from advanced_string tasks (practice 11). 11 | */ 12 | 13 | #include // cin, cout 14 | #include // strlen, strcat 15 | 16 | const unsigned int WORD_CNT = 3; 17 | const unsigned int MAX_INPUT = 1024; 18 | 19 | bool check_dic(const char* dic[], const char* word) { 20 | for (size_t i = 0; i < WORD_CNT; i++) 21 | if (std::strcmp(word, dic[i]) == 0) // if the word on position i 22 | return true; // in the dictionary is as same as the given one 23 | 24 | return false; 25 | } 26 | 27 | int main() { 28 | 29 | const char* dic[] = { "cats", "dogs", "animals" }; 30 | 31 | char input[MAX_INPUT]; // "it is raining cats and dogs"; 32 | 33 | std::cin.getline(input, MAX_INPUT); //reading the whole input 34 | 35 | // for each word form it, check into the dictionary 36 | 37 | // takes the first word 38 | char* curr_word = std::strtok(input, " "); 39 | unsigned int how_many = 0; 40 | while (curr_word != nullptr) { 41 | if (check_dic(dic, curr_word)) 42 | how_many++; 43 | // takes the next word form input string 44 | curr_word = std::strtok(nullptr, " "); 45 | } 46 | 47 | std::cout << how_many << std::endl; 48 | 49 | return 0; 50 | } 51 | -------------------------------------------------------------------------------- /10_strings/practice/strings_advanced/solution_02.cpp: -------------------------------------------------------------------------------- 1 | /**************************************************************************** 2 | * This file is part of the "Introduction to programming" course. FMI 2019/20 3 | *****************************************************************************/ 4 | 5 | /** 6 | * @file solution_02.cpp 7 | * @author Ivan Filipov 8 | * @date 01.2020 9 | * @brief Solution for task 2 from advanced_string tasks (practice 11). 10 | */ 11 | 12 | #include 13 | #include // strtok, strlen, strcpy 14 | #include // time 15 | #include // rand 16 | 17 | const unsigned int MAX_INPUT = 1024; 18 | 19 | // how many spaces are out there + 1 20 | size_t how_many_words(const char* str) { 21 | 22 | if (str == nullptr) 23 | return 0; 24 | 25 | size_t cnt = 1, i = 0; // at least one word 26 | 27 | while (str[i] != '\0') { 28 | if (str[i] == ' ') 29 | cnt++; 30 | i++; 31 | } 32 | 33 | return cnt; 34 | } 35 | 36 | void free_words(char**& words, size_t size) { 37 | 38 | for (size_t i = 0; i < size; i++) 39 | delete[] words[i]; 40 | 41 | delete words; 42 | 43 | words = nullptr; 44 | } 45 | 46 | void yoda_talks(char** words, size_t size) { 47 | 48 | // here we will check the taken words 49 | bool* is_taken_word = new (std::nothrow) bool[size]; 50 | 51 | if (is_taken_word == nullptr) 52 | return; 53 | 54 | // mark all as untaken 55 | for (size_t i = 0; i < size; i++) 56 | is_taken_word[i] = false; 57 | 58 | size_t num_taken = 0; 59 | size_t index; 60 | 61 | // while there is untaken word 62 | while (num_taken < size) { 63 | index = std::rand() % size; // trying to take this word 64 | 65 | while (is_taken_word[index]) 66 | index = (index + 1) % size; // try the next one, if outsize array, start from the beg 67 | 68 | // mark it as taken 69 | is_taken_word[index] = true; 70 | num_taken++; 71 | 72 | // print it 73 | std::cout << words[index]; 74 | 75 | if(num_taken != size) // no space after the last word 76 | std::cout << ' '; 77 | } 78 | 79 | delete[] is_taken_word; 80 | } 81 | 82 | int main() { 83 | 84 | char buff[MAX_INPUT]; 85 | 86 | std::cin.getline(buff, MAX_INPUT); 87 | 88 | size_t words_cnt = how_many_words(buff); 89 | 90 | // allocating pointer for each string ( word ) 91 | char** words = new (std::nothrow) char*[words_cnt]; 92 | if (!words) return 1; 93 | 94 | // taking the first word from the buff 95 | char* word = std::strtok(buff, " "); 96 | 97 | int i = 0; 98 | while (word != nullptr) { 99 | // allocating memory for the current word 100 | words[i] = new (std::nothrow) char[std::strlen(word) + 1]; 101 | 102 | if (words[i] == nullptr) { 103 | std::cerr << "can't allocate memory :( !\n"; 104 | free_words(words, i - 1); 105 | return 1; 106 | } 107 | 108 | // copying its content 109 | strcpy(words[i], word); 110 | 111 | i++; 112 | 113 | // taking the next word 114 | word = std::strtok(nullptr, " "); 115 | } 116 | 117 | // makes us sure that all the memory is successfully allocated and copied 118 | // for (int j = 0; j < i; j++) 119 | // std::cout << words[j] << std::endl; 120 | 121 | std::srand(std::time(nullptr)); 122 | 123 | yoda_talks(words, words_cnt); 124 | 125 | free_words(words, words_cnt); 126 | 127 | return 0; 128 | } 129 | -------------------------------------------------------------------------------- /10_strings/practice/strings_advanced/solution_03.cpp: -------------------------------------------------------------------------------- 1 | /**************************************************************************** 2 | * This file is part of the "Introduction to programming" course. FMI 2019/20 3 | *****************************************************************************/ 4 | 5 | /** 6 | * @file solution_03.cpp 7 | * @author Ivan Filipov 8 | * @author Kristian Krastev 9 | * @author Vasilena Peycheva 10 | * @date 01.2020 11 | * @brief Solution for task 3 from advanced_string tasks (practice 11). 12 | */ 13 | 14 | #include 15 | 16 | const int MAX = 16; 17 | 18 | // fill the crossword puzzle with words 19 | void fill(char cross[][MAX], int size) { 20 | 21 | for (size_t i = 0; i < size - 1 ; i++) 22 | std::cin >> cross[i]; 23 | } 24 | 25 | void print(char cross[][MAX], int size) { 26 | 27 | for (size_t i = 0; i < size - 1; i++) { 28 | for (size_t j = 0; j < size; j++) 29 | std::cout << cross[i][j]; 30 | 31 | std::cout << '\n'; 32 | } 33 | } 34 | 35 | // check if given row and column are filled with the same elements 36 | bool check_word(char cross[][MAX], int size, int row, int col) { 37 | 38 | for (size_t i = 0; i < size -1; i++) 39 | if (cross[row][i] != cross[i][col]) 40 | return false; 41 | 42 | return true; 43 | } 44 | 45 | // check how many rows and columns match 46 | int check_cross(char cross[][MAX], int size) { 47 | 48 | int result = 0; 49 | for (size_t i = 0; i < size - 1; i++) { 50 | for (size_t j = 0; j < size - 1; j++) 51 | if (check_word(cross, size, i, j)) 52 | result++; 53 | } 54 | 55 | return result; 56 | } 57 | 58 | int main() { 59 | 60 | char cross[MAX][MAX]; 61 | int size; 62 | std::cin >> size; 63 | fill(cross, size); 64 | 65 | std::cout << "\nThe cross looks: \n"; 66 | print(cross, size); 67 | std::cout << "\nYou have: " << check_cross(cross, size) << " matching words! \n"; 68 | 69 | return 0; 70 | } 71 | -------------------------------------------------------------------------------- /10_strings/practice/strings_advanced/solution_04.cpp: -------------------------------------------------------------------------------- 1 | /**************************************************************************** 2 | * This file is part of the "Introduction to programming" course. FMI 2019/20 3 | *****************************************************************************/ 4 | 5 | /** 6 | * @file solution_04.cpp 7 | * @author Ivan Filipov 8 | * @author Kristian Krastev 9 | * @author Vasilena Peycheva 10 | * @date 01.2020 11 | * @brief Solution for task 4 from advanced_string tasks (practice 11). 12 | */ 13 | 14 | #include 15 | #include 16 | 17 | // gets the number of same symbols from the beginning of str 18 | // ex: 111321 -> 3 (we have there ones) 19 | size_t get_same_symb_cnt(const char* str) { 20 | 21 | size_t cnt = 1; 22 | while (*str != '\0' && *str == *(str + 1)) { 23 | ++str; 24 | ++cnt; 25 | } 26 | 27 | return cnt; 28 | } 29 | 30 | // add number and symbol to a string 31 | // 112 -> append 3, 2 times -> 11223 32 | bool append_chars(char*& str, size_t cnt, char c) { 33 | 34 | if (str == nullptr) { 35 | str = new (std::nothrow) char[3]; // cnt, char, '\0' 36 | if (!str) return false; 37 | str[0] = '0' + cnt; 38 | str[1] = c; 39 | str[2] = '\0'; 40 | return true; 41 | } 42 | 43 | // allocate enough memory 44 | size_t old_len = strlen(str); 45 | size_t new_len = old_len + cnt + 1; 46 | char* new_mem = new (std::nothrow) char[new_len + 1]; 47 | if (!new_mem) return false; 48 | // copy the old contain 49 | std::strcpy(new_mem, str); 50 | // append the new characters 51 | char addends[] = { (char)('0' + cnt), c, '\0' }; 52 | std::strcat(new_mem, addends); 53 | // release the old memory 54 | delete[] str; 55 | // redirect str to the new memory 56 | str = new_mem; 57 | return true; 58 | } 59 | 60 | // by a sequence 11213, allocate new string having 21121113 (the step of look and say) 61 | char* look_and_say_step(const char* old_sequence) { 62 | 63 | char* res = nullptr; 64 | 65 | while (*old_sequence) { 66 | size_t cnt = get_same_symb_cnt(old_sequence); 67 | if (!append_chars(res, cnt, *old_sequence)) { 68 | delete[] res; 69 | return nullptr; 70 | } 71 | old_sequence += cnt; 72 | } 73 | 74 | return res; 75 | } 76 | 77 | char* get_nth_look_and_say(size_t n) { 78 | 79 | char* init_member = new (std::nothrow) char[2]; 80 | init_member[0] = '1'; 81 | init_member[1] = '\0'; 82 | 83 | char* old_member = init_member; 84 | char* new_member = nullptr; 85 | while (n--) { 86 | // on each step -> create new string using the old one 87 | new_member = look_and_say_step(old_member); 88 | // release the memory for the old one 89 | delete[] old_member; 90 | // error check 91 | if (!new_member) return nullptr; 92 | // save the new member 93 | old_member = new_member; 94 | } 95 | 96 | return old_member; 97 | } 98 | 99 | int main() { 100 | 101 | char* seq = get_nth_look_and_say(6); 102 | if (!seq) return 1; 103 | std::cout << "Sixth member: " << seq << std::endl; 104 | 105 | char* next = look_and_say_step(seq); 106 | if (!next) return 1; 107 | std::cout << "Seventh member: " << next << std::endl; 108 | 109 | delete[] seq; 110 | delete[] next; 111 | 112 | return 0; 113 | } 114 | -------------------------------------------------------------------------------- /10_strings/practice/strings_advanced/solution_05.cpp: -------------------------------------------------------------------------------- 1 | /**************************************************************************** 2 | * This file is part of the "Introduction to programming" course. FMI 2019/20 3 | *****************************************************************************/ 4 | 5 | /** 6 | * @file solution_05.cpp 7 | * @author Ivan Filipov 8 | * @date 01.2020 9 | * @brief Solution for task 5 from advanced_string tasks (practice 11). 10 | */ 11 | 12 | #include 13 | #include 14 | 15 | bool check_pattern(const char* str, const char* pattern) { 16 | 17 | if (!str || !pattern) return false; 18 | 19 | while (*pattern) { 20 | char cur_sym = *pattern; 21 | if (cur_sym == '?') { 22 | // if we got at least one symbol in the string, just consume it 23 | if (!(*str)) return false; 24 | ++pattern; 25 | ++str; 26 | } else if (cur_sym == '*') { 27 | char next_sym = *(pattern + 1); 28 | if (next_sym == '\0') // the pattern has come the it's end 29 | return true; 30 | if (next_sym == '?' || next_sym == '*') { // *? => ? and ** => * 31 | ++pattern; 32 | } else { 33 | // we should find the next occurrence of `next_sym` in str 34 | str = std::strchr(str, next_sym); 35 | if (!str) return false; 36 | pattern += 2; 37 | ++str; 38 | } 39 | } else { 40 | // just an ordinary symbol 41 | if (cur_sym != *str) 42 | return false; 43 | ++pattern; 44 | ++str; 45 | } 46 | } 47 | 48 | return *str == '\0'; 49 | } 50 | 51 | int main() { 52 | 53 | const char* pattern = "te?t.*"; 54 | std::cout << "Checking with pattern: " << pattern << std::endl; 55 | 56 | const char* test_strings[] = { "test.txt", "text.pdf", "tekt.sad", "teqt.qwerty", "baba" }; 57 | size_t cnt = sizeof(test_strings) / sizeof(char*); 58 | 59 | for (size_t i = 0; i < cnt; i++) { 60 | std::cout << test_strings[i] << ": " 61 | << std::boolalpha 62 | << check_pattern(test_strings[i], pattern) 63 | << std::endl; 64 | } 65 | 66 | std::cout << "testing \"test.txt\" with pattern \"*.?x?*\": " 67 | << std::boolalpha 68 | << check_pattern("test.txt", "*.?x?*") 69 | << std::endl; 70 | 71 | return 0; 72 | } 73 | -------------------------------------------------------------------------------- /10_strings/practice/strings_advanced/задачи.md: -------------------------------------------------------------------------------- 1 | # **Задачи - Символни низове част втора** 2 | 3 | 1. Напишете програма dictionary, която по предварително известен речник
4 | от думи и въведено изречение от потребителя казва колко от въведените
5 | думи се съдържат в речника.
6 | 7 | Пример: 8 | ``` 9 | const char* dictionary[] = {“cats”, “dogs”}; 10 | Вход: it’s raining cats and dogs 11 | Изход: 2 12 | ``` 13 | # 14 | 2. Реализирайте програмата “речта на Йода”, която по въведено изречение
15 | в прав текст, отпечатва на екрана примерен вариант за това как Йода
16 | би изрекал това изречение. (Йода (герой от StarWars) говори с разместен словоред).
17 | Опитайте се да не заделяте повече памет от необходимата за всяка
18 | една от въведените думи от изречението. От програмата Ви се очаква
19 | при две различни пускания с еднакво изречение за вход, да отпечатва
20 | различен изход. 21 | 22 | Пример: 23 | ``` 24 | Вход: "Young student the Force is strong with you!" 25 | Изход: "the Young strong student is you! with Force" 26 | ``` 27 | # 28 | 3. Напишете програмата crossword, която кара потребителя да въведе
29 | цяло положително число N <= 16, след това на N-1 последователни
30 | реда от думи с дължина точно N-1 (разчитаме на верен вход).
31 | След това програмата трябва да изведе броя на думите, които се срещат
32 | и в редовете, и в колоните.
33 | 34 | Примери: 35 | ``` 36 | Вход: 4 37 | abc 38 | bca 39 | cba 40 | 41 | Изход: 1 (abc се среща в първия ред и в първата колона) 42 | ``` 43 | 44 | ``` 45 | Вход: 4 46 | abc 47 | bcb 48 | cbi 49 | 50 | Изход: 3 51 | (abc се среща в първия ред и в първата колона, 52 | bcb във втория ред и втората колона, cbi в третия ред с третата колона) 53 | ``` 54 | # 55 | 4. Разгледайте редицата: 1, 11, 21, 1211, 111221, 312211, 13112221, 1113213211
56 | Намерете зависимостта между членовете. Имплементирайте функция, която генерира
57 | n-тия член на редицата и то с точно заделена памет.
58 | # 59 | 5. Напишете функция, която по шаблон и низ казва дали низа отговаря на шаблона.
60 | В шаблона могат да участват всички ASCII символи,
61 | а пък следните два имат специално предназначение: 62 | - '\?' - е символ "жокер", той може да се замести с кой да е друг символ. 63 | - '\*' - последователност от произволни символи от нула до неограничен брой.
64 | 65 | Пример: 66 | ``` 67 | Вход: pattern - "te?t.*" 68 | string - "test.txt" (още примери: "text.pdf", "tekt.sad", "teqt.qwerty") 69 | ``` 70 | # 71 | 72 | 6. Ще разработим приложение за управление на пароли (по поръчка от FMIValut, разбира се).
73 | Вашата програма трябва да поддържа 3 различни режима на работа (в кой режим да работи приложението 74 | се определя от аргумент на командния ред). Режимите са както следва: 75 | 76 | - `pass-check` - програмата ви трябва да прочете от стандартния си вход един символен низ -
77 | парола. След това програмата съветва потребителя какво още е нужно,
78 | за да стане тази парола "сигурна". Като правилата за "сигурна" парола са: 79 | - съдържа поне 12 символа
80 | - съдържа поне 1 буква и поне 1 цифра
81 | - съдържа както малки, така и главни букви
82 | - съдържа поне един символ (!, ?, #, @,...)
83 | 84 | Изведете подходящи съобщения, които да съветват потребиреля,
85 | какво не достига на паролата му за да бъде окачествена като сигурна.
86 | 87 | Пример: 88 | ``` 89 | Команден ред: $pass_app pass-check 90 | Вход: "11IztochihmeBANKOVATASmetkaNaYosif!11 91 | Изход: Your password is strong! 92 | ``` 93 | - `pass-encrypt ` - програмата прочита от стандартния си вход едно цяло число,
94 | след това толкова на брой байтове - тази информация служи за "криптираща таблица".
95 | Използвайки таблицата и побитова операция "изключващо или", програмата криптира низът
96 | ``. След това шифрованият стринг се извежда на екрана.
97 | 98 | - `pass-decrypt ` - отново се изчита таблицата от стандартния вход, след това
99 | низът `` се декриптира и изкарва на стандартния изход.
100 | 101 | *Съвет: пренасочете стандартния вход да бъде от файла **one_time_pad.txt**.*
102 | 103 | *Бонус: поддържайте аргументи на командия ред ([-h] и [help]) - извикана с тях,*
104 | *програмата ви, да извежда помощно съобщение - как се очаква да бъде използвана.*
105 | -------------------------------------------------------------------------------- /10_strings/practice/strings_basics/задачи.md: -------------------------------------------------------------------------------- 1 | # **Задачи - Символни низове** 2 | 3 | 1. Напишете функция is_alpha, която по подаден символ казва дали символът е буква или не.
4 | # 5 | 2. Напишете функция is_digit, която по подаден символ казва дали символът е цифра или не.
6 | # 7 | 3. Напишете функциите to_upper(to_lower), които съответно преобразуват всички букви
8 | на символен низ от малки в големи(големи в малки).
9 | 10 | Пример: 11 | ``` 12 | char str[] = “abcd56ABCD”; 13 | to_upper(str) -> ABCD56ABCD; 14 | to_lower(str) -> abcd56abcd 15 | ``` 16 | # 17 | 4. Реализирайте функция change_sp_symbol, която по подадени символен
18 | низ(s), символ, който ще променяме(c1) и символ за замяна(c2),
19 | заменя всяко срещане на c1 в s със c2.
20 | 21 | Пример: 22 | ``` 23 | char s[] = “a*b*c*d”; 24 | char c1 = ‘*’; 25 | char c2 = ‘1’; 26 | change_sp_symbol(s, c1, c2) -> “a1b1c1d” 27 | ``` 28 | # 29 | 5. Имплементирайте функцията atoi, която по подаден валиден стринг
30 | съдъжащ само цифри, връща цялото число, което се получава от символите на този стринг.
31 | 32 | *Oпитайте да поддържате и стрингове с "-" отпред “-123”.*
33 | 34 | Пример: 35 | ``` 36 | const char* s = “123”; 37 | int res = atoi(s); 38 | cout << res; // 123 39 | ``` 40 | # 41 | 6. Напишете функцията is_palindrome, която проверява дали даден стринг е палиндром.
42 | (Прочетен от ляво надясно и от дясно наляво е един и същ.)
43 | 44 | Пример: 45 | ``` 46 | const char* str = “a1b1a”; 47 | is_palindrome(str) -> true 48 | ``` 49 | # 50 | 7. Имплементирайте функцията reverse, която обръща подаден стринг.
51 | 52 | Пример: 53 | ``` 54 | char str[] = “abcd”; 55 | reverse(str); 56 | std::cout << str; // “dcba” 57 | ``` 58 | # 59 | 8. Реализирайте функция dynamic_concat, която конкатенира два низа, като
60 | обаче се грижи за паметта им. Може да използвате библиотечните strlen, strcpy, strcat.
61 | # 62 | 9. Имплементирайте функция compact, която премахва всички гласни букви от един стринг,
63 | след премахването стрингът да има точно заделена памет спрямо броя на символите в него.
64 | # 65 | 10. Реализирайте функцията most_common_alpha, която по подаден стринг
66 | отпечатва на стандартния изход коя е най-често срещаната буква в него
67 | и колко пъти се среща. 68 | 69 | *Забележка: Малки и големи букви считаме за еднакви.* 70 | 71 | Пример: 72 | ``` 73 | const char* str = “AaaaAaabBbCccc”; 74 | most_common_alpha(str); // a 7 75 | ``` 76 | # 77 | -------------------------------------------------------------------------------- /10_strings/seminar/materials.md: -------------------------------------------------------------------------------- 1 | ## C strings 2 | --- 3 | 4 | [C strings general](http://people.scs.carleton.ca/~dehne/projects/cpp-doc/tutorial/tut3-2.html) 5 | 6 | [Strings manipulation](https://en.wikibooks.org/wiki/C_Programming/String_manipulation) 7 | 8 | [C standard library](http://www.cplusplus.com/reference/cstring/) 9 | 10 | --- 11 | 12 | -------------------------------------------------------------------------------- /11_recursion/practice/recursion_advanced/solution_01.cpp: -------------------------------------------------------------------------------- 1 | /**************************************************************************** 2 | * This file is part of the "Introduction to programming" course. FMI 2019/20 3 | *****************************************************************************/ 4 | 5 | /** 6 | * @file solution_01.cpp 7 | * @author Ivan Filipov 8 | * @date 01.2020 9 | * @brief Solution for recursion task 01 from practice 13. 10 | */ 11 | 12 | #include 13 | 14 | bool push_back(int*& arr, size_t& size, int elem) { 15 | 16 | int* result = new (std::nothrow) int[size + 1]; 17 | if (!result) return false; 18 | for (size_t i = 0; i < size; i++) 19 | result[i] = arr[i]; 20 | 21 | result[size] = elem; 22 | delete[] arr; 23 | 24 | arr = result; 25 | size++; 26 | return true; 27 | } 28 | 29 | bool has_only_odd_digits(int num) { 30 | // only one digit case 31 | if (num < 10) 32 | return (num % 2 != 0); 33 | 34 | // here the recursion call will only be made, if the 35 | // last digit of num is odd 36 | return ((num % 10) % 2 != 0) && has_only_odd_digits(num / 10); 37 | } 38 | 39 | 40 | void filter_numbers_rec(int* arr, size_t arr_size, int*& out_arr, size_t& out_size) { 41 | // bottom -> no elements left in `arr` 42 | if (arr_size == 0) return; 43 | // add the element if it is matching the condition 44 | if (has_only_odd_digits(*arr)) { 45 | if(!push_back(out_arr, out_size, *arr)) { 46 | // clear on push_back error 47 | delete[] out_arr; 48 | out_arr = nullptr; 49 | out_size = 0; 50 | } 51 | } 52 | // move to the next element in `arr` 53 | filter_numbers_rec(arr + 1, arr_size - 1, out_arr, out_size); 54 | } 55 | 56 | int* filter_numbers(int* arr, size_t arr_size, size_t& out_size) { 57 | 58 | int* out_arr = nullptr; 59 | out_size = 0; 60 | 61 | filter_numbers_rec(arr, arr_size, out_arr, out_size); 62 | return out_arr; 63 | } 64 | 65 | int main() { 66 | 67 | int arr[] = { 11, 23, 57, 42, 71, 53 }; 68 | 69 | size_t res_size; 70 | int* res = filter_numbers(arr, sizeof(arr) / sizeof(int), res_size); 71 | 72 | if (res) { 73 | for (size_t i = 0; i < res_size; i++) 74 | std::cout << res[i] << ' '; 75 | std::cout << std::endl; 76 | } 77 | 78 | delete[] res; 79 | return 0; 80 | } 81 | 82 | 83 | 84 | 85 | 86 | -------------------------------------------------------------------------------- /11_recursion/practice/recursion_advanced/solution_02.cpp: -------------------------------------------------------------------------------- 1 | /**************************************************************************** 2 | * This file is part of the "Introduction to programming" course. FMI 2019/20 3 | *****************************************************************************/ 4 | 5 | /** 6 | * @file solution_02.cpp 7 | * @author Ivan Filipov 8 | * @date 01.2020 9 | * @brief Solution for recursion task 02 from practice 13. 10 | */ 11 | 12 | 13 | #include 14 | #include 15 | 16 | const unsigned int DIGITS_COUNT = 10; 17 | // --- WITH ARRAY ------- 18 | bool has_same_digits_arr_rec(unsigned int num, bool digits_seen[DIGITS_COUNT]) { 19 | 20 | // only one digit left 21 | if (num < 10) 22 | return digits_seen[num]; 23 | 24 | // more than one digit in the number 25 | // check the last one 26 | if (digits_seen[num % 10]) // if seen 27 | return true; 28 | 29 | // if not seen 30 | digits_seen[num % 10] = true; 31 | 32 | return has_same_digits_arr_rec(num / 10, digits_seen); 33 | } 34 | 35 | bool has_same_digits_arr(unsigned int num, bool digits_seen[DIGITS_COUNT]) { 36 | 37 | // ensure that all cell are marked as no such digit 38 | std::memset(digits_seen, false, DIGITS_COUNT * sizeof(bool)); 39 | 40 | return has_same_digits_arr_rec(num, digits_seen); 41 | } 42 | 43 | // --- WITHOUT ARRAY ------- 44 | 45 | bool has_same_digits_rec(unsigned int num, unsigned short cur_digit) { 46 | 47 | if (num < 10) // only one digit 48 | return num == cur_digit; 49 | 50 | if (num % 10 == cur_digit) // check the last one 51 | return true; 52 | 53 | if (has_same_digits_rec(num / 10, cur_digit)) // same digit in the rest of the number 54 | return true; 55 | else 56 | return has_same_digits_rec(num / 10, num % 10); // try with the next digit 57 | } 58 | 59 | bool has_same_digits(unsigned int num) { 60 | 61 | if (num < 10) 62 | return false; 63 | 64 | return has_same_digits_rec(num / 10, num % 10); 65 | } 66 | 67 | int main() { 68 | 69 | unsigned int num = 125453; 70 | 71 | std::cout << "Has same digits " << num << '?' << std::endl; 72 | 73 | // false there is not such digit 74 | // true there is 75 | bool digits_seen[DIGITS_COUNT] = { false, }; 76 | 77 | std::cout << "Answer with array: "; 78 | if (has_same_digits_arr(num, digits_seen)) 79 | std::cout << "yes" << std::endl; 80 | else 81 | std::cout << "no" << std::endl; 82 | 83 | std::cout << "Answer without array: "; 84 | if (has_same_digits(num)) 85 | std::cout << "yes" << std::endl; 86 | else 87 | std::cout << "no" << std::endl; 88 | 89 | return 0; 90 | } 91 | -------------------------------------------------------------------------------- /11_recursion/practice/recursion_advanced/solution_03.cpp: -------------------------------------------------------------------------------- 1 | /**************************************************************************** 2 | * This file is part of the "Introduction to programming" course. FMI 2019/20 3 | *****************************************************************************/ 4 | 5 | /** 6 | * @file solution_03.cpp 7 | * @author Ivan Filipov 8 | * @date 01.2020 9 | * @brief Solution for recursion task 03 from practice 13. 10 | */ 11 | 12 | 13 | #include 14 | 15 | /// maximum number of addends 16 | #define MAXN 100 17 | 18 | /// all addends -> addends[i] contains the "i" summand 19 | int addends[MAXN]; 20 | 21 | /// simple result output 22 | void print_sum(unsigned int len) { 23 | 24 | for (unsigned int i = 1; i < len; i++) 25 | std::cout << addends[i] << " + "; 26 | std::cout << addends[len] << std::endl; 27 | } 28 | 29 | /** 30 | * @brief recursive algorithms for generating all sums 31 | * @param[in] n: the number to be broke up into summands 32 | * @param[in] pos: which is the current summand's position 33 | * 34 | * The idea is simple: just using that recursive definition - 35 | * sum(0) = {} 36 | * sum(n) = {k} + sum(n-k), k = n, n-1,..., 1. 37 | */ 38 | void creat_next_sum(unsigned int n, int pos) { 39 | 40 | if (n == 0) { 41 | // bottom case 42 | print_sum(pos - 1); 43 | return; 44 | } 45 | 46 | for (unsigned int k = n; k >= 1; k--) { 47 | // get a smaller number 48 | addends[pos] = k; 49 | // represent the smaller number as sum, too. 50 | if (addends[pos] <= addends[pos - 1]) 51 | creat_next_sum(n - k, pos + 1); 52 | } 53 | } 54 | 55 | int main() { 56 | 57 | /* number to be split */ 58 | unsigned int n = 4; 59 | 60 | /* initialize step */ 61 | addends[0] = n + 1; 62 | 63 | /* run the algorithm */ 64 | creat_next_sum(n, 1); 65 | 66 | return 0; 67 | } 68 | -------------------------------------------------------------------------------- /11_recursion/practice/recursion_advanced/solution_04.cpp: -------------------------------------------------------------------------------- 1 | /**************************************************************************** 2 | * This file is part of the "Introduction to programming" course. FMI 2019/20 3 | *****************************************************************************/ 4 | 5 | /** 6 | * @file solution_04.cpp 7 | * @author Ivan Filipov 8 | * @date 01.2020 9 | * @brief Solution for recursion task 04 from practice 13. 10 | */ 11 | 12 | #include 13 | 14 | //@{ 15 | /** definitions for used and unused numbers */ 16 | #define USED true 17 | #define UNUSED false 18 | //@} 19 | 20 | /// the power of the set to permute 21 | #define MAXN 4 22 | 23 | /// the set we are permuting 24 | int given[MAXN] = { 3, 11, 23, 7}; 25 | 26 | /// buffer for generating the current permutation 27 | int cur_perm[MAXN]; 28 | 29 | /// markers for used in current permutation 30 | bool used[MAXN] = { UNUSED, }; 31 | 32 | /// outputs the current permutation 33 | void print_perm() { 34 | 35 | for (int i = 0; i < MAXN; i++) 36 | std::cout << cur_perm[i] << ' '; 37 | 38 | std::cout << std::endl; 39 | } 40 | 41 | /** 42 | * @brief Generates permutations recursively. 43 | * @param[in] i: element on which index we are permuting 44 | * 45 | * The following algorithm is implemented: 46 | * Place each possible element on the first position, then 47 | * permute the other n - 1 elements on the other positions, using 48 | * the same strategy. 49 | */ 50 | void perm(int i) { 51 | 52 | if (i >= MAXN) { 53 | // the bottom of the recursion, 54 | // when the last element is placed 55 | print_perm(); 56 | return; 57 | } 58 | 59 | for (int k = 0; k < MAXN; k++) { 60 | // trying to use the k-th element of the set 61 | if (used[k] == UNUSED) { 62 | used[k] = USED; // marking it as used 63 | cur_perm[i] = given[k]; // saving it's value 64 | perm(i + 1); // generating the n-1 permutation 65 | used[k] = UNUSED; // unmarking after coming back form the recursion call 66 | } 67 | } 68 | } 69 | 70 | int main() { 71 | 72 | /* run the algorithm stating from the element on index 0*/ 73 | perm(0); 74 | 75 | return 0; 76 | } 77 | 78 | -------------------------------------------------------------------------------- /11_recursion/practice/recursion_advanced/solution_05.cpp: -------------------------------------------------------------------------------- 1 | /**************************************************************************** 2 | * This file is part of the "Introduction to programming" course. FMI 2019/20 3 | *****************************************************************************/ 4 | 5 | /** 6 | * @file solution_05.cpp 7 | * @author Ivan Filipov 8 | * @date 01.2020 9 | * @brief Solution for recursion task 05 from practice 13. 10 | */ 11 | 12 | #include 13 | #include // setw 14 | 15 | const size_t MAXN = 100; 16 | const size_t NUM_TESTS = 10; 17 | 18 | // the focus it not on dynamic memory, so .. 19 | unsigned int matrix[MAXN][MAXN] = { 0 }; 20 | 21 | void print_matrix(size_t k) { 22 | 23 | for (size_t i = 0; i < k; i++) { 24 | for (size_t j = 0; j < k; j++) 25 | std::cout << std::setw(3) 26 | << matrix[i][j]; 27 | std::cout << std::endl; 28 | } 29 | 30 | std::cout << std::endl << std::endl 31 | << std::endl << std::endl; 32 | } 33 | 34 | void fill_matrix(const size_t k, size_t it, size_t cur_size) { 35 | 36 | // only one cell to go 37 | if (it == k * k) { 38 | matrix[k / 2][k / 2] = it; 39 | return; 40 | } 41 | 42 | // begin index 43 | size_t start_cell = (k - cur_size) / 2; 44 | // end index 45 | size_t border = start_cell + cur_size - 1; 46 | 47 | // down fill 48 | for (size_t i = 0; i < cur_size; i++) 49 | matrix[start_cell + i][start_cell] = it++; 50 | 51 | // right fill -> 52 | for (size_t i = 1; i < cur_size; i++) 53 | matrix[border][start_cell+ i] = it++; 54 | 55 | // up fill 56 | for (size_t i = border - 1; i > start_cell; i--) 57 | matrix[i][border] = it++; 58 | 59 | // left fill <- 60 | for (size_t i = border; i > start_cell; i--) 61 | matrix[start_cell][i] = it++; 62 | 63 | if (it <= k * k) 64 | fill_matrix(k, it, cur_size - 2); 65 | } 66 | 67 | int main() { 68 | 69 | unsigned int k = 1; 70 | 71 | while (k <= NUM_TESTS) { 72 | fill_matrix(k, 1, k); 73 | print_matrix(k); 74 | k++; 75 | } 76 | 77 | return 0; 78 | } 79 | -------------------------------------------------------------------------------- /11_recursion/practice/recursion_advanced/задачи.md: -------------------------------------------------------------------------------- 1 | # **Интересни Задачи - Рекурсия** 2 | 3 | 1. Напишете рекурсивно функция, която по подаден масив от цели числа
4 | да върне указател към нов масив (с точно заделена памет), чиито елементи са
5 | само числата, съставени само от нечетни цифри.
6 | 7 | Пример: 8 | ``` 9 | Вход: 11 23 57 42 71 53 10 | Изход: 11 57 71 53 11 | ``` 12 | # 13 | 2. Напишене рекурсивно функция, която проверява дали в записа на едно число някоя
14 | цифра се среща повече от веднъж.
15 | Помислете как можете да решите задачата без използване на допълнителна памет (масив)?
16 | 17 | Пример: 18 | ``` 19 | Вход: 1234 20 | Изход: No 21 | ``` 22 | ``` 23 | Вход: 1434 24 | Изход: Yes 25 | ``` 26 | # 27 | 3. Напишете програма, която изкарва на стандартния си изход всички представяния
28 | като сума от естествени числа на дадено естествено число.
29 | 30 | Пример: 31 | ``` 32 | Вход: 4 33 | Изход: 1 + 1 + 1 + 1 34 | 1 + 1 + 2 35 | 1 + 3 36 | 2 + 1 + 1 37 | 2 + 2 38 | 4 + 0 39 | ``` 40 | # 41 | 4. Напишете програма, която изкарва на стандартния изход си всички пермутации
42 | на дадено множество от естествени числа.
43 | `Забележка: числата съхранете в масив.` 44 | 45 | Пример: 46 | ``` 47 | Вход: 1 2 3 48 | Изход: 1 2 3 49 | 1 3 2 50 | 2 1 3 51 | 2 3 1 52 | 3 1 2 53 | 3 2 1 54 | ``` 55 | # 56 | 5. Напишете програма, която прочита цяло положително число K от стандартния си вход,
57 | след което отпечатва на екрана следната спираловидна матрица съдържаща числата от 1 до K^2.
58 | 59 | Пример: 60 | ``` 61 | Вход: 4 62 | Изход: 1 12 11 10 63 | 2 13 16 9 64 | 3 14 15 8 65 | 4 5 6 7 66 | # 67 | -------------------------------------------------------------------------------- /11_recursion/practice/recursion_basic/solutions_01-02.cpp: -------------------------------------------------------------------------------- 1 | /**************************************************************************** 2 | * This file is part of the "Introduction to programming" course. FMI 2019/20 3 | *****************************************************************************/ 4 | 5 | /** 6 | * @file solutions_01-02.cpp 7 | * @author Ivan Filipov 8 | * @author Kristian Krastev 9 | * @author Vasilena Peycheva 10 | * @date 01.2020 11 | * @brief Solution for recursion tasks from practice 12. 12 | */ 13 | 14 | #include 15 | #include 16 | 17 | const int MAX = 12; 18 | 19 | /*************** Task 1 ***************/ 20 | unsigned int factorial(unsigned int number) { 21 | //limit 22 | if (number > MAX) 23 | return 0; 24 | if (number == 0 || number == 1) 25 | return 1; 26 | return number * factorial(number - 1); 27 | } 28 | 29 | /*************** Task 2 ***************/ 30 | // main logic 31 | bool is_prime_rec(unsigned int number, unsigned int stop, unsigned int i) { 32 | 33 | if (number == 1 || number == 2) 34 | return true; 35 | if (number % i == 0) 36 | return false; 37 | if (i == stop) 38 | return true; 39 | 40 | return is_prime_rec(number, stop, i + 1); 41 | } 42 | 43 | // "wrapper function" is a function which wraps another function (in our example the recursive one). 44 | // It's essentially another function which calls the actual function. 45 | bool is_prime(unsigned int number) { 46 | 47 | return is_prime_rec(number, std::sqrt(number), 2); 48 | } 49 | 50 | int main() { 51 | unsigned int number; 52 | 53 | // task_01 54 | std::cout << "n = "; 55 | std::cin >> number; 56 | std::cout << number << "! = " 57 | << factorial(number) 58 | << std::endl; 59 | 60 | // task_02 61 | std::cout << "n = "; 62 | std::cin >> number; 63 | std::cout << "Is prime? - " 64 | << std::boolalpha 65 | << is_prime(number) 66 | << std::endl; 67 | 68 | return 0; 69 | } 70 | -------------------------------------------------------------------------------- /11_recursion/practice/recursion_basic/solutions_03-04.cpp: -------------------------------------------------------------------------------- 1 | /**************************************************************************** 2 | * This file is part of the "Introduction to programming" course. FMI 2019/20 3 | *****************************************************************************/ 4 | 5 | /** 6 | * @file solutions_03-04.cpp 7 | * @author Ivan Filipov 8 | * @author Kristian Krastev 9 | * @author Vasilena Peycheva 10 | * @date 01.2020 11 | * @brief Solution for recursion tasks from practice 12. 12 | */ 13 | 14 | #include 15 | 16 | /*************** Task 3 ***************/ 17 | // print the binary representation of a number 18 | // "actual function" 19 | void print_bits_rec(unsigned int number, unsigned int position) { 20 | 21 | unsigned int mask = 1 << (position - 1); 22 | std::cout << ((number & mask) ? "1" : "0"); 23 | 24 | if (position == 1) 25 | return; 26 | else 27 | return print_bits_rec(number, position - 1); 28 | } 29 | 30 | // example of a "wrapper function" 31 | // "wrapper function" is a function which wraps another function (in our example the recursive one). 32 | // It's essentially another function which calls the actual function. 33 | void print_bits(unsigned int number) { 34 | 35 | unsigned int position = sizeof(unsigned int) * 8; 36 | return print_bits_rec(number, position); 37 | } 38 | 39 | /*************** Task 4 ***************/ 40 | // print the number of zeros and ones in the binary representation of a number 41 | // main logic 42 | void count_bits_rec(unsigned int number, unsigned int position, int &zeroes, int &ones) { 43 | 44 | unsigned int mask = 1 << (position - 1); 45 | ((number&mask) ? ones++ : zeroes++); 46 | 47 | if (position == 1) 48 | return; 49 | 50 | else 51 | return count_bits_rec(number, position - 1, zeroes, ones); 52 | } 53 | 54 | void count_bits(unsigned int number) { 55 | 56 | int zeroes = 0; 57 | int ones = 0; 58 | unsigned int position = sizeof(unsigned int) * 8; 59 | count_bits_rec(number, position,zeroes,ones); 60 | std::cout << "In number: " << number << " we have " << zeroes << " zeroes and " << ones << " ones! \n"; 61 | } 62 | 63 | int main() { 64 | 65 | unsigned int number; 66 | std::cout << "N = "; 67 | std::cin >> number; 68 | // task_03 69 | print_bits(number); 70 | 71 | std::cout << std::endl; 72 | 73 | // task_04 74 | count_bits(number); 75 | std::cout << std::endl; 76 | 77 | return 0; 78 | } 79 | -------------------------------------------------------------------------------- /11_recursion/practice/recursion_basic/solutions_05-06.cpp: -------------------------------------------------------------------------------- 1 | /**************************************************************************** 2 | * This file is part of the "Introduction to programming" course. FMI 2019/20 3 | *****************************************************************************/ 4 | 5 | /** 6 | * @file solutions_05-06.cpp 7 | * @author Ivan Filipov 8 | * @author Kristian Krastev 9 | * @author Vasilena Peycheva 10 | * @date 01.2020 11 | * @brief Solution for recursion tasks from practice 12. 12 | */ 13 | 14 | #include 15 | 16 | // PAY ATTENTION how swapping two code lines changes the whole program 17 | /*************** Task 5 ***************/ 18 | void print_forward(unsigned int number) { 19 | 20 | if (number <= 0) return; 21 | 22 | print_forward(number / 10); 23 | std::cout << (number % 10) << " "; 24 | } 25 | 26 | /*************** Task 6 ***************/ 27 | void print_backward(unsigned int number) { 28 | 29 | if (number <= 0) return; 30 | 31 | std::cout << (number % 10) << " "; 32 | print_backward(number / 10); 33 | } 34 | 35 | int main() { 36 | 37 | unsigned int number; 38 | std::cout << "N = "; 39 | std::cin >> number; 40 | 41 | // task_05 42 | std::cout << "Forward: "; 43 | print_forward(number); 44 | std::cout << std::endl; 45 | 46 | // task_06 47 | std::cout << "Backward: "; 48 | print_backward(number); 49 | std::cout << std::endl; 50 | 51 | return 0; 52 | } 53 | -------------------------------------------------------------------------------- /11_recursion/practice/recursion_basic/solutions_07-08.cpp: -------------------------------------------------------------------------------- 1 | /**************************************************************************** 2 | * This file is part of the "Introduction to programming" course. FMI 2019/20 3 | *****************************************************************************/ 4 | 5 | /** 6 | * @file solutions_07-08.cpp 7 | * @author Ivan Filipov 8 | * @author Kristian Krastev 9 | * @author Vasilena Peycheva 10 | * @date 01.2020 11 | * @brief Solution for recursion tasks from practice 12. 12 | */ 13 | 14 | #include 15 | 16 | /*************** Task 7 ***************/ 17 | // the actual recursive function 18 | void print_line_rec(unsigned int k, unsigned int it, unsigned long long result) { 19 | 20 | std::cout << result << ' '; 21 | 22 | if (it < k) 23 | print_line_rec(k, it + 1, result * 10); 24 | 25 | std::cout << result << ' '; 26 | } 27 | 28 | // the wrapper 29 | void print_line(unsigned int k) { 30 | 31 | print_line_rec(k, 1, 10); 32 | } 33 | 34 | 35 | /*************** Task 8 ***************/ 36 | // just by following the recursive definition of the algorithm 37 | int gcd(int a, int b) { 38 | 39 | return (b == 0) ? a : gcd(b, a % b); 40 | } 41 | 42 | 43 | int main() { 44 | 45 | // task_07 output 46 | std::cout << "Enter a positive number k >= 1, k = "; 47 | unsigned int k; 48 | std::cin >> k; 49 | 50 | if (k < 1) 51 | std::cout << "cheater!" << std::endl; 52 | else { 53 | std::cout << "The line looks like:" << std::endl; 54 | print_line(k); 55 | } 56 | 57 | // task_08 output 58 | std::cout << std::endl << std::endl; 59 | std::cout << "Enter two numbers: "; 60 | int a, b; 61 | std::cin >> a >> b; 62 | std::cout << "gcd(" << a << ", " << b << ") = " 63 | << gcd(a, b) << std::endl; 64 | 65 | 66 | return 0; 67 | } 68 | -------------------------------------------------------------------------------- /11_recursion/practice/recursion_basic/задачи.md: -------------------------------------------------------------------------------- 1 | # **Задачи - Рекурсия** 2 | 3 | 1. Напишете рекурсивна функция, която по подадено цяло положително число n
4 | връща произведението на всички цели числа от 1 до n. (Факториел)
5 | 6 | Пример: 7 | ``` 8 | Вход: 5 9 | Изход: 120 10 | ``` 11 | # 12 | 2. Напишете рекурсивна функция, която по подадено цяло положително число n
13 | роверява дали числото е просто.
14 | 15 | Пример: 16 | ``` 17 | Вход: 10 18 | Изход: False (може да изкарате и само 0) 19 | ``` 20 | # 21 | 3. Напишете рекурсивна функция, която по подадено цяло положително число n
22 | изкарва битовете на числото на екрана.
23 | 24 | Пример: 25 | ``` 26 | Вход: 10 27 | Изход: 00000000000000000000000000001010 28 | ``` 29 | # 30 | 4. Напишете рекурсивна функция, която по подадено цяло положително число n
31 | изкарва съобщение за броя нули и единици в бинарното представяне на числото.
32 | 33 | Пример: 34 | ``` 35 | Вход: 10 36 | Изход: In number: 10 we have 30 zeroes and 2 ones! 37 | ``` 38 | # 39 | 5. Напишете рекурсивна функция, която по подадено цяло положително число n
40 | изкарва цифрите на числото.
41 | 42 | Пример: 43 | ``` 44 | Вход: 23453 45 | Изход: Forward: 2 3 4 5 3 46 | ``` 47 | # 48 | 6. Напишете рекурсивна функция, която по подадено цяло положително число n
49 | изкарва цифрите на числото наобратно.
50 | 51 | Пример: 52 | ``` 53 | Вход: 23453 54 | Изход: Backward: 3 5 4 3 2 55 | ``` 56 | # 57 | 7. Напишете рекурсивна функция, която по подадено цяло положително число k
58 | oтпечатва на екрана редицата: 10 100 1000 …. 10^(k-1) 10^k 10^k 10^(k-1) …. 10
59 | 60 | Пример: 61 | ``` 62 | Вход: 3 63 | Изход: 10 100 1000 1000 100 10 64 | ``` 65 | # 66 | 8. Реализирайте алгоритъма на Евклид за най-голям общ делител рекурсивно.
67 | # -------------------------------------------------------------------------------- /11_recursion/seminar/materials.md: -------------------------------------------------------------------------------- 1 | ## Recursion 2 | --- 3 | 4 | [Recursion in maths](https://en.wikibooks.org/wiki/Discrete_Mathematics/Recursion) 5 | 6 | [Recursion in nature](http://www.mi.sanu.ac.rs/vismath/bridges2005/burns/index.html) 7 | 8 | [Fractal](https://en.wikipedia.org/wiki/Fractal) 9 | 10 | [Recursion in art](https://en.wikipedia.org/wiki/Recursion#In_art) 11 | 12 | [Popular recursion acronyms](https://en.wikipedia.org/wiki/Recursive_acronym) 13 | 14 | --- 15 | 16 | [Recursion in general](https://en.wikipedia.org/wiki/Recursion) 17 | 18 | [Recursion types in programming](https://en.wikipedia.org/wiki/Recursion_(computer_science)) 19 | 20 | --- 21 | 22 | ### See also: 23 | Try to search for "recursion" in google. What do you get? 24 | -------------------------------------------------------------------------------- /11_recursion/seminar/recursion_basics.cpp: -------------------------------------------------------------------------------- 1 | /**************************************************************************** 2 | * This file is part of the "Introduction to programming" course. FMI 2019/20 3 | *****************************************************************************/ 4 | 5 | /** 6 | * @file recursion_basics.cpp 7 | * @author Ivan Filipov 8 | * @date 12.2019 9 | * @brief Example about recursions. 10 | */ 11 | 12 | /* 13 | Linear recursion - the function calls itself once only (in an execution branch). 14 | Tree recursion - more than one call. 15 | Indirect recursion - A calls B, B calls C, C calls A. 16 | */ 17 | 18 | #include 19 | 20 | /* Tail recursion (subclass of linear rec) <=> simulate loop */ 21 | void loop_simulate_recursion(int i) { 22 | 23 | if (i == 10) return; 24 | std::cout << "Rec call: " << i << std::endl; 25 | loop_simulate_recursion(i + 1); 26 | } 27 | 28 | 29 | /* Linear recursion */ 30 | int fact(int x) { 31 | 32 | if (x == 0) return 1; 33 | 34 | return x * fact(x - 1); 35 | } 36 | 37 | /* Tree recursion */ 38 | int fib(int n) { 39 | 40 | if (n == 0) return 0; 41 | if (n == 1) return 1; 42 | 43 | return fib(n - 1) + fib(n - 2); 44 | } 45 | 46 | /* Indirect recursion */ 47 | bool is_odd(int x); 48 | 49 | bool is_even(int x) { 50 | 51 | if (x == 0) return true; 52 | 53 | return is_odd(x - 1); 54 | } 55 | 56 | bool is_odd(int x) { 57 | 58 | return !is_even(x); 59 | } 60 | 61 | int main() { 62 | 63 | 64 | loop_simulate_recursion(0); 65 | 66 | std::cout << fact(5) << std::endl; 67 | std::cout << fib(6) << std::endl; 68 | std::cout << std::boolalpha << is_even(25); 69 | 70 | return 0; 71 | } 72 | -------------------------------------------------------------------------------- /11_recursion/seminar/recursive_binary_search.cpp: -------------------------------------------------------------------------------- 1 | /**************************************************************************** 2 | * This file is part of the "Introduction to programming" course. FMI 2019/20 3 | *****************************************************************************/ 4 | 5 | /** 6 | * @file recursive_binary_search.cpp 7 | * @author Ivan Filipov 8 | * @date 01.2020 9 | * @brief Example implementation of binary search - recursive variant. 10 | */ 11 | 12 | #include 13 | 14 | int binary_search_rec(int* arr, int left, int right, int elem) { 15 | //there is no such element 16 | if (left > right) 17 | return -1; 18 | // 19 | // calculate the middle index 20 | // int mid = (L + R) / 2; // <- a bug source, because L + R can easily overflow 21 | // solution is 22 | int mid = left + (right - left) / 2; 23 | // or even better int mid = L + (((unsigned int)R - (unsigned int)L) >> 1); 24 | // 25 | // is the search element on that index? 26 | if (arr[mid] == elem) 27 | return mid; 28 | // 29 | // grater than the middle element -> search in right 30 | if (arr[mid] > elem) 31 | return binary_search_rec(arr, left, mid - 1, elem); 32 | // 33 | // less than the middle element -> search in the left 34 | if (arr[mid] < elem) 35 | return binary_search_rec(arr, mid + 1, right, elem); 36 | // 37 | // won't reach here 38 | return -1; 39 | } 40 | 41 | // wrapper function 42 | int binary_search(int* arr, size_t size, int elem) { 43 | 44 | return binary_search_rec(arr, 0, (int)size - 1, elem); 45 | } 46 | 47 | // a variant which uses pointers arithmetic, 48 | // in order to avoid the passing of left and right, but just size 49 | // returns a pointer to the element, if found 50 | int* binary_search_rec_ptr(int* arr, size_t size, int elem) { 51 | 52 | if (size == 0 && arr[size] != elem) 53 | return nullptr; 54 | 55 | size_t mid = size / 2; 56 | 57 | if (arr[mid] == elem) 58 | return arr + mid; 59 | 60 | if (arr[mid] < elem) 61 | return binary_search_rec_ptr(arr + mid + 1, size - (mid + 1), elem); 62 | 63 | if (arr[mid] > elem) 64 | return binary_search_rec_ptr(arr, mid - 1, elem); 65 | } 66 | 67 | int main() { 68 | 69 | int sorted_arr[] = { -121, -9, 5, 11, 23, 48, 70 }; 70 | size_t size = sizeof(sorted_arr) / sizeof(int); 71 | 72 | int searched_el = -9; 73 | 74 | int index = binary_search(sorted_arr, size, searched_el); 75 | 76 | if (index != -1) { 77 | std::cout << "Found " << searched_el 78 | << " at index: " << index 79 | << std::endl; 80 | } else { 81 | std::cout << searched_el << " not found." << std::endl; 82 | } 83 | 84 | int* elem_ptr = binary_search_rec_ptr(sorted_arr, size, searched_el); 85 | 86 | if (elem_ptr) { 87 | std::cout << "Found " << *elem_ptr 88 | << " at index: " << (int)(elem_ptr - sorted_arr) 89 | << std::endl; 90 | } else { 91 | std::cout << searched_el << " not found." << std::endl; 92 | } 93 | 94 | return 0; 95 | } 96 | -------------------------------------------------------------------------------- /12_function_pointers/practice/solution_01.cpp: -------------------------------------------------------------------------------- 1 | /**************************************************************************** 2 | * This file is part of the "Introduction to programming" course. FMI 2019/20 3 | *****************************************************************************/ 4 | 5 | /** 6 | * @file solution_01.cpp 7 | * @author Ivan Filipov 8 | * @date 01.2020 9 | * @brief Solution for function pointers task 01 from practice 14. 10 | */ 11 | 12 | #include 13 | 14 | typedef bool(*pr_fptr)(int); 15 | 16 | bool is_even(int x) { 17 | 18 | return x % 2 == 0; 19 | } 20 | 21 | bool push_back(int*& arr, size_t& size, int elem) { 22 | 23 | int* result = new (std::nothrow) int[size + 1]; 24 | if (!result) return false; 25 | for (size_t i = 0; i < size; i++) 26 | result[i] = arr[i]; 27 | 28 | result[size] = elem; 29 | delete[] arr; 30 | 31 | arr = result; 32 | size++; 33 | return true; 34 | } 35 | 36 | int* filter_numbers(int* arr, size_t arr_size, size_t& out_size, pr_fptr pr) { 37 | 38 | int* out_arr = nullptr; 39 | out_size = 0; 40 | 41 | for (size_t i = 0; i < arr_size; i++) { 42 | if (pr(arr[i])) { 43 | if(!push_back(out_arr, out_size, arr[i])) { 44 | // clear on push_back error 45 | delete[] out_arr; 46 | out_arr = nullptr; 47 | out_size = 0; 48 | } 49 | } 50 | } 51 | 52 | return out_arr; 53 | } 54 | 55 | int main() { 56 | 57 | int arr[] = { 10, 23, 57, 42, 71 }; 58 | 59 | size_t res_size; 60 | int* res = filter_numbers(arr, sizeof(arr) / sizeof(int), res_size, is_even); 61 | 62 | if (res) { 63 | for (size_t i = 0; i < res_size; i++) 64 | std::cout << res[i] << ' '; 65 | std::cout << std::endl; 66 | } 67 | 68 | delete[] res; 69 | return 0; 70 | } 71 | -------------------------------------------------------------------------------- /12_function_pointers/practice/solution_02.cpp: -------------------------------------------------------------------------------- 1 | /**************************************************************************** 2 | * This file is part of the "Introduction to programming" course. FMI 2019/20 3 | *****************************************************************************/ 4 | 5 | /** 6 | * @file solution_02.cpp 7 | * @author Ivan Filipov 8 | * @date 01.2020 9 | * @brief Solution for function pointers task 02 from practice 14. 10 | */ 11 | 12 | #include 13 | 14 | typedef int(*math_func_fptr)(int); 15 | 16 | int id(int x) { 17 | 18 | return x; 19 | } 20 | 21 | int square(int x) { 22 | 23 | return x * x; 24 | } 25 | 26 | bool check_interval(int beg, int end, math_func_fptr mf) { 27 | 28 | for (int i = beg; i <= end - 1; i++) 29 | for (int j = i + 1; j <= end; j++) 30 | if (mf(i) == mf(j)) 31 | return true; 32 | 33 | return false; 34 | } 35 | 36 | int main() { 37 | 38 | 39 | std::cout << "Checking id(x) in the interval [-10; 10]:" << std::endl; 40 | std::cout << (check_interval(-10, 10, id) ? 41 | "There are two points with the same function value." : 42 | "There aren't such points!") 43 | << std::endl 44 | << std::endl; 45 | 46 | std::cout << "Checking square(x) in the interval [-10; 10]:" << std::endl; 47 | std::cout << (check_interval(-10, 10, square) ? 48 | "There are two points with the same function value." : 49 | "There aren't such points!") 50 | << std::endl; 51 | 52 | return 0; 53 | } 54 | -------------------------------------------------------------------------------- /12_function_pointers/practice/solution_03.cpp: -------------------------------------------------------------------------------- 1 | /**************************************************************************** 2 | * This file is part of the "Introduction to programming" course. FMI 2019/20 3 | *****************************************************************************/ 4 | 5 | /** 6 | * @file solution_03.cpp 7 | * @author Ivan Filipov 8 | * @date 01.2020 9 | * @brief Solution for function pointers task 03 from practice 14. 10 | */ 11 | 12 | #include 13 | 14 | typedef bool(*cmp_fptr)(int, int); 15 | 16 | void print_arr(int* arr_ptr, size_t size) { 17 | 18 | for (size_t i = 0; i < size; i++) 19 | std::cout << arr_ptr[i] << ' '; 20 | 21 | std::cout << std::endl; 22 | } 23 | 24 | bool greater(int x, int y) { 25 | 26 | return x > y; 27 | } 28 | 29 | bool less(int x, int y) { 30 | 31 | return x < y; 32 | } 33 | 34 | // the third argument is the function 35 | // which we will be using to compare the array's elements 36 | void selection_sort(int* arr, size_t size, cmp_fptr cmp) { 37 | 38 | size_t index; 39 | for (size_t i = 0; i < size - 1; i++) { 40 | index = i; 41 | for (size_t j = i + 1; j < size; j++) 42 | if (cmp(arr[index], arr[j])) // the slight difference is here 43 | index = j; 44 | std::swap(arr[i], arr[index]); 45 | } 46 | } 47 | 48 | int main() { 49 | 50 | int given_arr[] = { 1, 15, 23, 11, -125, 45, -9, 911 }; 51 | size_t size = sizeof(given_arr) / sizeof(int); 52 | 53 | std::cout << "given array:" << std::endl; 54 | print_arr(given_arr, size); 55 | 56 | selection_sort(given_arr, size, less); 57 | std::cout << "\nAfter sorting with lesser:" << std::endl; 58 | print_arr(given_arr, size); 59 | 60 | selection_sort(given_arr, size, greater); 61 | std::cout << "\nAfter sorting with greater:" << std::endl; 62 | print_arr(given_arr, size); 63 | 64 | return 0; 65 | } 66 | -------------------------------------------------------------------------------- /12_function_pointers/practice/solution_04.cpp: -------------------------------------------------------------------------------- 1 | /**************************************************************************** 2 | * This file is part of the "Introduction to programming" course. FMI 2019/20 3 | *****************************************************************************/ 4 | 5 | /** 6 | * @file solution_04.cpp 7 | * @author Ivan Filipov 8 | * @date 01.2020 9 | * @brief Solution for function pointers task 04 from practice 14. 10 | */ 11 | 12 | #include 13 | #include // std::qsort 14 | #include 15 | 16 | void print_arr(int* arr_ptr, size_t size) { 17 | 18 | for (size_t i = 0; i < size; i++) 19 | std::cout << arr_ptr[i] << ' '; 20 | 21 | std::cout << std::endl; 22 | } 23 | 24 | int greater(const void* rhs, const void* lhs) { 25 | 26 | int rhs_v = *((int*)rhs); 27 | int lhs_v = *((int*)lhs); 28 | 29 | return rhs_v - lhs_v; 30 | } 31 | 32 | int str_cmp(const void* rhs, const void* lhs) { 33 | 34 | return strcmp((*(const char**)rhs), (*(const char**)lhs)); 35 | } 36 | 37 | int main() { 38 | 39 | int given_arr[] = { 1, 15, 23, 11, -125, 45, -9, 911 }; 40 | size_t size = sizeof(given_arr) / sizeof(int); 41 | 42 | 43 | std::cout << "given array:" << std::endl; 44 | print_arr(given_arr, size); 45 | 46 | std::qsort(given_arr, size, sizeof(int), greater); 47 | std::cout << "\nAfter sorting with greater:" << std::endl; 48 | print_arr(given_arr, size); 49 | std::cout << std::endl; 50 | 51 | 52 | const char* str_arr[] = { "again", "Great", "FMI", "Make" }; 53 | size = sizeof(str_arr) / sizeof(const char*); 54 | std::cout << "Some strings: " << std::endl; 55 | for (size_t i = 0; i < size; i++) 56 | std::cout << str_arr[i] << std::endl; 57 | std::cout << std::endl << std::endl; 58 | 59 | std::qsort(str_arr, size, sizeof(const char*), str_cmp); 60 | std::cout << "After sorting them: " << std::endl; 61 | for (size_t i = 0; i < size; i++) 62 | std::cout << str_arr[i] << std::endl; 63 | std::cout << std::endl; 64 | } 65 | 66 | 67 | -------------------------------------------------------------------------------- /12_function_pointers/practice/задачи.md: -------------------------------------------------------------------------------- 1 | # **Задачи - Указатели към функции** 2 | 3 | 1. Напишете функция, която по подаден масив от цели числа
4 | и предикат да върне указател към нов масив, чиито елементи са
5 | само числата, за които е изпълнен предиката.
6 | `Предикат - функция от вида F:N -> {0, 1}`
7 | Пример: 8 | ``` 9 | Вход: 10 23 57 42 71 10 | Изход: 10 42 (след прилагане на предикат четно число - (number % 2 == 0)) 11 | ``` 12 | # 13 | 2. Напишете функция, която приема три аргумента
14 | a - начално на интервал, b - край на интервал a < b
15 | и трети аргумент математическа функция F,
16 | от вида F : Z -> Z. Вашата функция трябва да отговори на 17 | въпроса дали функцията F има две еднакви
18 | стойности в интервала [a; b].
19 | # 20 | 3. Напишете сортировка по избор, която да получава като
21 | аргумент булева функция, която да служи за сравнения между
22 | елементите на даден масив.
23 | # 24 | 4. Използвайки `qsort` от стандартната C библиотека, сортирайте масиви
25 | от `int` и от `const char*` (стрингове).
26 | # 27 | -------------------------------------------------------------------------------- /12_function_pointers/seminar/basic_example.cpp: -------------------------------------------------------------------------------- 1 | /**************************************************************************** 2 | * This file is part of the "Introduction to programming" course. FMI 2019/20 3 | *****************************************************************************/ 4 | 5 | /** 6 | * @file basic_example.cpp 7 | * @author Ivan Filipov 8 | * @date 01.2020 9 | * @brief The most basic example about function pointers in C/C++. 10 | */ 11 | 12 | #include 13 | 14 | // a simple function 15 | int sum(int x, int y) { 16 | 17 | return x + y; 18 | } 19 | 20 | int main() { 21 | // the most basic example 22 | // foo is a pointer to function, 23 | // which takes 0 arguments and returns nothing (void) 24 | void(*foo)(); 25 | 26 | // sum_fptr is a pointer to function which takes two integers 27 | // and returns an integer 28 | int(*sum_fptr)(int, int); 29 | 30 | // sum_fptr now points to the function "sum" 31 | sum_fptr = sum; // we can skip the '&' from [sum_fptr = ∑] 32 | 33 | // now we can invoke the function through the pointer 34 | std::cout << sum_fptr(1, 2); // same as (*sum_fptr)(1, 2) 35 | 36 | return 0; 37 | } 38 | -------------------------------------------------------------------------------- /12_function_pointers/seminar/calculator.cpp: -------------------------------------------------------------------------------- 1 | /**************************************************************************** 2 | * This file is part of the "Introduction to programming" course. FMI 2019/20 3 | *****************************************************************************/ 4 | 5 | /** 6 | * @file basic_example.cpp 7 | * @author Ivan Filipov 8 | * @date 01.2020 9 | * @brief Example implementation of calculator using function pointers. 10 | */ 11 | 12 | #include 13 | 14 | // typedef for function pointers has special meaning: 15 | // operation_fptr now is a type - a pointer to function, that 16 | // takes two ints and returns int 17 | // typedef makes our code cleaner and easier to maintain 18 | typedef int(*operation_fptr)(int, int); 19 | 20 | int add(int x, int y) { 21 | 22 | return x + y; 23 | } 24 | 25 | int subtract(int x, int y) { 26 | 27 | return x - y; 28 | } 29 | 30 | int mul(int x, int y) { 31 | 32 | return x * y; 33 | } 34 | 35 | // will return a pointer to function 36 | // depending on the character we have received 37 | operation_fptr select_operation(char op_code) { 38 | 39 | switch (op_code) { 40 | case '+' : 41 | return add; 42 | case '-' : 43 | return subtract; 44 | case '*' : 45 | return mul; 46 | default: 47 | return nullptr; // unknown operation 48 | } 49 | } 50 | 51 | // calculate an operation on lhs and rhs 52 | int eval(char op_code, int lhs, int rhs) { 53 | 54 | // which function to be applied 55 | operation_fptr operation = select_operation(op_code); 56 | 57 | if (operation == nullptr) { 58 | std::cout << "Invalid operation, can't evaluate!" << std::endl; 59 | return 0; 60 | } 61 | 62 | // the real evaluation is done here, 63 | // by invoking the right function though the pointer 64 | return operation(lhs, rhs); 65 | } 66 | 67 | int main() { 68 | 69 | std::cout << "*********Usage*********" << std::endl 70 | << "please use the following format:" << std::endl 71 | << " "<< std::endl 72 | << "example : 5 + 3" << std::endl 73 | << "**********************" 74 | << std::endl 75 | << std::endl 76 | << std::endl; 77 | 78 | int op1, op2, result; 79 | char op_code, choice; 80 | 81 | while (true) { 82 | 83 | std::cout << "Now enter the wanted calculation:" << std::endl; 84 | std::cin >> op1 >> op_code >> op2; 85 | 86 | result = eval(op_code, op1, op2); 87 | std::cout << "Result = " << result << std::endl; 88 | 89 | std::cout << "New calculation - (y\\n)?" << std::endl; 90 | std::cin >> choice; 91 | 92 | if (choice == 'n' || choice == 'N') 93 | break; 94 | } 95 | 96 | std::cout << "Goodbye!" << std::endl; 97 | return 0; 98 | } 99 | -------------------------------------------------------------------------------- /12_function_pointers/seminar/materials.md: -------------------------------------------------------------------------------- 1 | ## Function pointers 2 | --- 3 | 4 | [Function pointers](https://en.wikipedia.org/wiki/Function_pointer) 5 | 6 | [Benefits](https://www.quora.com/What-are-the-advantages-of-function-pointers-in-C) 7 | 8 | [Directly Executing Chunks Of Memory](https://hackaday.com/2018/05/02/directly-executing-chunks-of-memory-function-pointers-in-c/) 9 | 10 | -------------------------------------------------------------------------------- /12_function_pointers/seminar/pipeline.cpp: -------------------------------------------------------------------------------- 1 | /**************************************************************************** 2 | * This file is part of the "Introduction to programming" course. FMI 2019/20 3 | *****************************************************************************/ 4 | 5 | /** 6 | * @file basic_example.cpp 7 | * @author Ivan Filipov 8 | * @date 01.2020 9 | * @brief Example implementation of pipeline using function pointers. 10 | */ 11 | 12 | #include 13 | #include 14 | 15 | // how many manipulators are there 16 | const size_t MANIP_CNT = 5; 17 | 18 | // a pointer to function, which takes 19 | // char* as an argument and returns char* 20 | typedef char* (*string_manip_fptr)(char*); 21 | 22 | // allocate heap memory for a string with precise size 23 | char* alloc_from_input(char* input) { 24 | 25 | if (input == nullptr) 26 | return nullptr; 27 | 28 | char* res = new (std::nothrow) char[strlen(input) + 1]; 29 | 30 | if (res == nullptr) 31 | return nullptr; 32 | 33 | strcpy(res, input); 34 | 35 | return res; 36 | } 37 | 38 | // free allocated memory for a string 39 | char* free_memory(char* str) { 40 | // delete on nullptr is safe 41 | delete[] str; 42 | return nullptr; 43 | } 44 | 45 | // change each digit in a string to a letter 46 | char* map_digit_alpha(char* str) { 47 | 48 | if (str == nullptr) 49 | return nullptr; 50 | 51 | char* beg = str; 52 | 53 | while (*str != '\0') { 54 | if (isdigit(*str)) 55 | *str = 'A' + (*str - '0'); 56 | str++; 57 | } 58 | 59 | return beg; 60 | } 61 | 62 | // add 11 to every second char 63 | char* put_some_salt(char* str) { 64 | 65 | if (str == nullptr) 66 | return nullptr; 67 | 68 | char* beg = str; 69 | while (*str != '\0') { 70 | *str += 11; 71 | str++; 72 | if (*str == '\0') 73 | break; 74 | str++; 75 | } 76 | 77 | return beg; 78 | } 79 | 80 | // just output a string 81 | char* print_result(char* str) { 82 | 83 | if (str == nullptr) 84 | return nullptr; 85 | 86 | std::cout << str; 87 | 88 | return str; 89 | } 90 | 91 | 92 | int main() { 93 | 94 | // the idea here is to have a number of serial manipulations, 95 | // where the input of each manipulation is the output of the previous one 96 | string_manip_fptr manipulators[MANIP_CNT] = { 97 | alloc_from_input, 98 | map_digit_alpha, 99 | put_some_salt, 100 | print_result, 101 | free_memory 102 | }; 103 | 104 | // read the STDIN 105 | char buff[1024]; 106 | std::cin.get(buff, 1024); 107 | 108 | char* res = buff; 109 | // go through the manipulators 110 | for (int i = 0; i < MANIP_CNT; i++) { 111 | res = manipulators[i](res); // input for each manipulator is the output from the previous one 112 | } 113 | 114 | return 0; 115 | } 116 | -------------------------------------------------------------------------------- /13_preprocessor_cmd_line/command_line.cpp: -------------------------------------------------------------------------------- 1 | /**************************************************************************** 2 | * This file is part of the "Introduction to programming" course. FMI 2019/20 3 | *****************************************************************************/ 4 | 5 | /** 6 | * @file command_line.cpp 7 | * @author Ivan Filipov 8 | * @date 01.2020 9 | * @brief Basic example for program <=> command line interaction. 10 | */ 11 | 12 | #include 13 | 14 | /* 15 | First of all compile the example. 16 | Then go to directory with the executable file. 17 | run you preferred shell (CLI). 18 | ----------------------------------------------------- 19 | From the command line: 20 | 21 | WINDOWS LINUX 22 | >command_line.exe $./command_line 23 | 24 | Will start your program without parameters and with the default 25 | I/Os: output[both STDOUT/STDERR]: screen (aka the console) 26 | input[STDIN]: keyboard 27 | ----------------------------------------------------- 28 | Passing parameters 29 | Write from the command line: 30 | 31 | >command_line.exe argument_1 argument_2 32 | 33 | The strings argument_1 and argument_2 will be passed 34 | into our main function as argv[1] and argv[2]. 35 | 36 | In Visual Studio you can pass parameter while debugging 37 | your program. Follow these steps : 38 | right click on you project -> Properties -> 39 | Configuration Properties -> Debugging -> Command Line Arguments 40 | write into the input box your desired arguments. 41 | ----------------------------------------------------- 42 | Redirecting the STDIN/STDOUT/STDERR 43 | you can easily redirect all standard I/Os 44 | by using the following syntax: 45 | 46 | >command_line.exe > outputfile.txt | will redirect the STDOUT to outputfile.txt 47 | >command_line.exe < input.txt | will redirect the STDIN from input.txt 48 | >command_line.exe 2> errors.txt | will redirect the STDERR to errors.txt 49 | 50 | You can combine the redirections: 51 | 52 | >command_line.exe < input.txt > output.txt | STDIN now is input.txt, STDOUT is output.txt 53 | >command_line.exe < input.txt > output.txt 2> errors.txt | all at once 54 | */ 55 | 56 | // output all the arguments , which have been passed through the command line - 57 | // from your cmd, shell, PowerShell and etc. 58 | int main(int argc , char* argv []) { 59 | 60 | // first one ALWAYS is the path to the executable file 61 | if (argc == 1) { 62 | std::cout << "No arguments have been passed only the executable file path:" 63 | << std::endl 64 | << argv[0] 65 | << std::endl; 66 | } 67 | 68 | // prints all other arguments 69 | for (int i = 1; i < argc ; i++) { 70 | std::cout << "argument " << i << " is: "; 71 | std::cout << argv[i] << std::endl; 72 | } 73 | 74 | int a, b, c; 75 | // reading three numbers from STDIN [ standard input ] 76 | std::cin >> a >> b >> c; 77 | // check the condition of the input stream (was the reading successful?) 78 | if (!std::cin) { 79 | // outputs to STDERR [ standard error output ] 80 | std::cerr << "An error occur: wrong input format!" << std::endl; 81 | return 1; // this return is our exit code 82 | // (can be used by other programs, to see if ours has ran successfully) 83 | } 84 | 85 | // outputs to STDOUT [ standard output ] 86 | std::cout << a * a << std::endl; 87 | std::cout << 2 * b << std::endl; 88 | std::cout << c - a << std::endl; 89 | 90 | return 0; 91 | } 92 | -------------------------------------------------------------------------------- /13_preprocessor_cmd_line/materials.md: -------------------------------------------------------------------------------- 1 | ## Command line 2 | --- 3 | 4 | [CLI](https://en.wikipedia.org/wiki/Command-line_interface) 5 | 6 | [Shell](https://en.wikipedia.org/wiki/Shell_(computing)) 7 | 8 | [I/O redirection](https://www.tldp.org/LDP/abs/html/io-redirection.html) 9 | 10 | [WIN CMD I/O redirection](https://ss64.com/nt/syntax-redirection.html) 11 | 12 | --- 13 | ## C/C++ Preprocessor 14 | 15 | [C Preprocessor](https://en.wikipedia.org/wiki/C_preprocessor) 16 | 17 | [Directives and macros](https://en.wikibooks.org/wiki/C_Programming/Preprocessor_directives_and_macros) 18 | 19 | [Preprocessor](https://en.cppreference.com/w/c/preprocessor) 20 | -------------------------------------------------------------------------------- /13_preprocessor_cmd_line/predefined_macros.cpp: -------------------------------------------------------------------------------- 1 | /**************************************************************************** 2 | * This file is part of the "Introduction to programming" course. FMI 2019/20 3 | *****************************************************************************/ 4 | 5 | /** 6 | * @file predefined_macros.cpp 7 | * @author Ivan Filipov 8 | * @date 01.2020 9 | * @brief Some predefined macros. 10 | * @see https://gcc.gnu.org/onlinedocs/gcc-3.0.2/cpp_3.html#SEC20 11 | */ 12 | 13 | #include 14 | 15 | int main() { 16 | 17 | std::cout << "This is the line number " << __LINE__; 18 | std::cout << " of file " << __FILE__ << ".\n"; 19 | std::cout << "It's compilation began on " << __DATE__; 20 | std::cout << " at " << __TIME__ << ".\n"; 21 | std::cout << "C++ version: " << __cplusplus << std::endl; 22 | 23 | return 0; 24 | } 25 | -------------------------------------------------------------------------------- /13_preprocessor_cmd_line/preprocessor.cpp: -------------------------------------------------------------------------------- 1 | /**************************************************************************** 2 | * This file is part of the "Introduction to programming" course. FMI 2019/20 3 | *****************************************************************************/ 4 | 5 | /** 6 | * @file preprocessor.cpp 7 | * @author Ivan Filipov 8 | * @date 01.2020 9 | * @brief Some use cases of the C preprocessor. 10 | * @see https://gcc.gnu.org/onlinedocs/gcc-3.0.2/cpp.html#SEC_Top 11 | */ 12 | 13 | //include is a preprocessor's directive, which tells 14 | // "just paste this file's content" 15 | #include 16 | 17 | // macro as a constant 18 | #define MAX_SIZE 24 19 | int arr[MAX_SIZE]; // we can use it as an ordinary constant 20 | 21 | // if directive 22 | #if MAX_SIZE > 16 // MAX_SIZE should be defined, only constant expressions here are allowed 23 | // redefining 24 | #undef MAX_SIZE 25 | #define MAX_SIZE 16 26 | 27 | int arr1[MAX_SIZE]; 28 | #endif 29 | 30 | // macros as functions 31 | // Notice the large amount of brackets used 32 | // in order to do the right job, if 33 | // expression is passed not only a variable. 34 | #define min(a,b) (((a) > (b)) ? (b) : (a)) 35 | 36 | #define max(a,b) (((a) > (b)) ? (a) : (b)) 37 | 38 | #define sq(x) (x)*(x) 39 | 40 | #define bug_sq(x) x*x // try this with bug_sq(x + 3), what will happen? 41 | 42 | // multi-line macros 43 | #define abs(x) \ 44 | ((x > 0) ? \ 45 | (x) : \ 46 | ((-1)*(x))) 47 | 48 | // just a definition (see below for usage) 49 | #define DEBUG 50 | 51 | // argument to string macro 52 | #define to_string(x) #x 53 | 54 | // concatenation macro 55 | #define concat(x,y) x##y 56 | 57 | int main() { 58 | 59 | // conditional include 60 | #ifdef DEBUG // if defined 61 | // will include these lines if only 62 | // DEBUG is defined 63 | std::cout << "Debug mode on" << std::endl; 64 | #endif // DEBUG 65 | 66 | int a = 10, b = 15; 67 | int x = -11; 68 | 69 | // macros function usage 70 | std::cout << to_string(MAX_SIZE) << MAX_SIZE << std::endl; 71 | std::cout << to_string(max(a, b) = ) << max(a, b) << std::endl; 72 | std::cout << to_string(min(a, b) = ) << min(a, b) << std::endl; 73 | std::cout << to_string(abs(x) = ) << abs(x) << std::endl; 74 | std::cout << to_string(sq(x) = ) << sq(x) << std::endl; 75 | 76 | std::concat(c, out) << "wow how is this even possible?!\n"; 77 | int cat_num = concat(10, 11); 78 | std::cout << cat_num; 79 | 80 | return 0; 81 | } 82 | -------------------------------------------------------------------------------- /14_small_project/helpers.h: -------------------------------------------------------------------------------- 1 | /**************************************************************************** 2 | * This file is part of the "Introduction to programming" course. FMI 2019/20 3 | *****************************************************************************/ 4 | 5 | /** 6 | * @file helpers.h 7 | * @author Ivan Filipov 8 | * @date 01.2020 9 | * @brief A header file, which contains some function declarations and constants. 10 | */ 11 | 12 | // include guards, read about them in the seminar #13 13 | #ifndef HELPERS_H_INCLUDED 14 | #define HELPERS_H_INCLUDED 15 | 16 | #define START_X 0 //!< player's start x coordinate 17 | #define START_Y 0 //!< player's start y coordinate 18 | 19 | // Notice: here we have only DECLARATIONs of functions 20 | 21 | /// initialize maze's cells 22 | /// with 66% change -> available cell (UNVGND) 23 | /// with 33% change -> unavailable cell (LAVA) 24 | /// @param[out] target_x: where is the target (x coordinate) 25 | /// @param[out] target_y: where is the target (y coordinate) 26 | void init_maze(int& target_x, int& target_y); 27 | 28 | 29 | /// simply outputs the maze content 30 | void print_maze(bool is_iteractive = false); 31 | 32 | /** 33 | * @brief Runs recursively DFS into the generated maze. 34 | * @param[in] x: current x coordinate 35 | * @param[in] y: current y coordinate 36 | * @param[in] target_x: target x coordinate 37 | * @param[in] target_y: target y coordinate 38 | */ 39 | bool dfs_find(int x, int y, int target_x, int target_y); 40 | 41 | /// Let the user control the game 42 | void play_interactive(int x, int y); 43 | 44 | #endif // HELPERS_H_INCLUDED 45 | -------------------------------------------------------------------------------- /14_small_project/materials.md: -------------------------------------------------------------------------------- 1 | ## Small project 2 | --- 3 | 4 | We are going to implement a very simple, but still quite handy game.
5 | It's going to be a 2D maze with a player and a goal within it. The player's task is
6 | to reach the target, but there are a few obstacles - some of the maze's cells
7 | are covert in lava. The game will have two modes:
8 | * automatic - the computer will play by it's own 9 |
(Lol, is this an AI?! No, but backtracking algorithm.) 10 | * interactive - we are going to use the arrows as an input - to control the hero.
11 | 12 | --- 13 | 14 | [C I/O](https://en.wikibooks.org/wiki/C_Programming/Simple_input_and_output) 15 | 16 | [Header files](https://data-flair.training/blogs/header-files-in-c-cpp/) 17 | 18 | --- 19 | 20 | [Maze generation](https://en.wikipedia.org/wiki/Maze_generation_algorithm) 21 | 22 | [Backtracking](https://en.wikipedia.org/wiki/Backtracking) 23 | 24 | 25 | --- 26 | 27 | [ANSI escape codes](https://en.wikipedia.org/wiki/ANSI_escape_code#Unix-like_systems) 28 | 29 | [WIN set cursor](https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-setcursorpos) 30 | -------------------------------------------------------------------------------- /14_small_project/maze.cpp: -------------------------------------------------------------------------------- 1 | /**************************************************************************** 2 | * This file is part of the "Introduction to programming" course. FMI 2019/20 3 | *****************************************************************************/ 4 | 5 | /** 6 | * @file maze.cpp 7 | * @author Ivan Filipov 8 | * @date 01.2020 9 | * @brief A simple console game, with two modes - interactive & automatic. 10 | */ 11 | 12 | #include // std::printf() 13 | #include // std::rand(), std::srand() 14 | #include // std::time() 15 | 16 | // include out custom header 17 | #include "helpers.h" 18 | 19 | int main() { 20 | 21 | /* initialize the random generator */ 22 | std::srand(std::time(nullptr)); 23 | /* create the maze and target coordinates */ 24 | int target_x, target_y; 25 | init_maze(target_x, target_y); 26 | 27 | /* read the running mode */ 28 | std::puts("Supported modes:"); 29 | std::puts("0 - automatic"); 30 | std::puts("1 - interactive"); 31 | std::printf("Enter mode: "); 32 | 33 | int mode; 34 | if ((scanf("%d", &mode) != 1) || 35 | (mode != 0 && mode != 1)) { 36 | std::puts("Invalid input!"); 37 | return 1; 38 | } 39 | 40 | /* output the starting maze */ 41 | print_maze(true); 42 | 43 | if (mode == 0) { 44 | /* run the algorithm */ 45 | if (dfs_find(START_X, START_Y, target_x, target_y)) 46 | std::puts("there is a path!"); 47 | else 48 | std::puts("there isn't a path!"); 49 | } else { 50 | /* start the interactive game */ 51 | play_interactive(START_X, START_Y); 52 | } 53 | 54 | return 0; 55 | } 56 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ФМИ - Увод в програмирането 2 | 3 | Код, задачи и материали от семинарите и практикумите по УП
4 | 2017-2020г. спец. Информатика, ФМИ, СУ 5 | 6 | Преподавателски състав:
7 | 2017-2018 - (ВИП) [Василена](https://www.linkedin.com/in/vasilena-peycheva-vpp/), [Иван](https://www.linkedin.com/in/ivan-filipov-v11/), [Пламен](https://www.linkedin.com/in/psminev/)
8 | 2019-2020 - [Иван](https://www.linkedin.com/in/ivan-filipov-v11/) и [Кристиан](https://www.linkedin.com/in/kristian-krastev-666649169/) 9 | 10 | ## Организация на хранилището: 11 | * `/XX_/` - поддиректории с примери, разделени по седмици и теми 12 | * `/seminar/`   - тук са теоритичните примери и ресурси 13 | * `/practice/` - условия на задачи и техните решения 14 | * `/practical_tips/` - разнообразни практически съвети и полезни умения 15 | 16 | * `разписание` - примерно разписание по седмици на обхванатите теми и допълнителна информация 17 | за съдържанието на цялостното изложение 18 | 19 | *всички примери са компилирани и тествани с компилаторите на GNU, MS и Apple (gcc, g++, VC++, clang) 20 | 21 | # FMI - Introduction to programming 22 | 23 | Source code, tasks and examples during the IP courses
@ Faculty of Mathematics and Informatics, Sofia University 24 | 25 | Team:
26 | 2017-2018 - (VIP edition) the course was held by 27 | [Vasilena](https://www.linkedin.com/in/vasilena-peycheva-vpp/), [Ivan](https://www.linkedin.com/in/ivan-filipov-v11/), [Plamen](https://www.linkedin.com/in/psminev/)
28 | 2019-2020 - [Ivan](https://www.linkedin.com/in/ivan-filipov-v11/) and [Kristian](https://www.linkedin.com/in/kristian-krastev-666649169/) 29 | 30 | ## Repository organization: 31 | * `/XX_/` - subdirectories, dividing the content into weeks and topics 32 | * `/seminar/`   - the theory examples and resources are located here 33 | * `/practice/` - tasks and their solutions 34 | * `/practical_tips/` - practical advices and useful skills 35 | 36 | * `schedule` - all the themes that are included + plan about when talking for them will be 37 | 38 | *all examples are compiled and run using GNU, MS and Apple compilers (gcc, g++, VC++, clang) 39 | -------------------------------------------------------------------------------- /practical_tips/debugging_tips/debugger.md: -------------------------------------------------------------------------------- 1 | # Debugging 2 | 3 | [Debugging Basics](https://docs.microsoft.com/en-us/visualstudio/debugger/debugging-absolute-beginners?view=vs-2019) 4 | 5 | --- 6 | 7 | [How to work with the debugger (MSVS)](https://docs.microsoft.com/en-us/visualstudio/debugger/debugger-feature-tour?view=vs-2019&fbclid=IwAR2jRhtIVDZXJzKH2X2LRmmxN1cT73xL74a9PYePzei-808_VigOD5WZuyI) 8 | 9 | --- 10 | 11 | [Debugging with Code::Blocks](http://wiki.codeblocks.org/index.php/Debugging_with_Code::Blocks) 12 | 13 | --- 14 | 15 | [Visual Studio Code C++ debugging](https://code.visualstudio.com/docs/cpp/cpp-debug) 16 | 17 | --- 18 | 19 | [![Why debugging is Important](http://i3.ytimg.com/vi/2yXYNxNgJek/maxresdefault.jpg)](https://www.youtube.com/watch?v=2yXYNxNgJek&fbclid=IwAR1kowqfq-HAaClhMP5jRZPf6X3wNFRSI0q_deyblTyLIdh13pL7KftNSZs) 20 | -------------------------------------------------------------------------------- /practical_tips/visual_studio_tips/vs-create-cpp-file.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/VasiPeycheva/Introduction-to-Programming--2017-2020/b4ea6adf9e76b55724d3b914900f953f416796be/practical_tips/visual_studio_tips/vs-create-cpp-file.gif -------------------------------------------------------------------------------- /practical_tips/visual_studio_tips/vs-create-project.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/VasiPeycheva/Introduction-to-Programming--2017-2020/b4ea6adf9e76b55724d3b914900f953f416796be/practical_tips/visual_studio_tips/vs-create-project.gif -------------------------------------------------------------------------------- /res/mushroom.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/VasiPeycheva/Introduction-to-Programming--2017-2020/b4ea6adf9e76b55724d3b914900f953f416796be/res/mushroom.png --------------------------------------------------------------------------------