commit ef5f055695b5e00d75476882dd3c651e08cb242a Author: Dan Cojocaru Date: Sun Mar 13 16:02:09 2022 +0200 Initial commit, solve Lab1 Slide11 diff --git a/Lab1/README.md b/Lab1/README.md new file mode 100644 index 0000000..f990c30 --- /dev/null +++ b/Lab1/README.md @@ -0,0 +1,28 @@ +# CCIoT Homework Lab 1 + +## Slide 11 + +### Problem + +```cpp +class Human +{ +public: + Human(); + ~Human(); + std::string name; + int age; +}; +``` + +Try this: + +1. Create 4 humans. +2. Give them names and ages. +3. Retrieve the data from all humans and print it to the screen. +4. Print the data for the youngest human. +5. Print all humans’ names in descending order by their names. + +### Solution + +See [slide11.cpp](./slide11.cpp). diff --git a/Lab1/slide11.cpp b/Lab1/slide11.cpp new file mode 100644 index 0000000..4961a1e --- /dev/null +++ b/Lab1/slide11.cpp @@ -0,0 +1,70 @@ +// For std::string +#include +// For std::cout +#include +// For std::sort +#include + +class Human +{ +public: + Human(); + ~Human(); + std::string name; + int age; +}; + +// Implementation +Human::Human() : name{}, age{} {} +Human::~Human() {} + +int main() { + // 1. Create 4 humans + Human humans[4]; + + // 2. Give them names and ages. + humans[0].name = "Joe"; + humans[0].age = 18; + humans[1].name = "Jane"; + humans[1].age = 19; + humans[2].name = "Jim"; + humans[2].age = 20; + humans[3].name = "John"; + humans[3].age = 21; + + // 3. Retrieve the data from all humans + // and print it to the screen. + for (int i = 0; i < 4; i++) { + std::cout + << "name=" << humans[i].name + << ", age=" << humans[i].age + << std::endl; + } + + // 4. Print the data for the youngest + // human. + Human& youngest = humans[0]; + for (int i = 1; i < 4; i++) { + if (humans[i].age < youngest.age) { + youngest = humans[i]; + } + } + std::cout + << "Youngest:" + << " name=" << youngest.name + << ", age=" << youngest.age + << std::endl; + + // 5. Print all humans' names in + // descending order by their + // names. + std::sort(humans, humans + 4, [](const Human &h1, const Human &h2) { + return h1.name <= h2.name; + }); + for (int i = 0; i < 4; i++) { + std::cout << humans[i].name << ", "; + } + std::cout << std::endl; + + return 0; +} diff --git a/README.md b/README.md new file mode 100644 index 0000000..73aefe4 --- /dev/null +++ b/README.md @@ -0,0 +1,3 @@ +# CCIoT Homework + +- [Lab1](./Lab1/)