diff --git a/notes/cpp.html b/notes/cpp.html index 7bfaeed..7863ce4 100644 --- a/notes/cpp.html +++ b/notes/cpp.html @@ -6,7 +6,7 @@ padding:0; } main { - margin:2em; + margin:0em 20em 0em 20em; } header { width: 100%; @@ -63,6 +63,13 @@
+ Loops are good when you need to repeat a segment of instruction multiple times. There are a few different types of loops to be aware of. +
int main() {
+ int x = true;
+ while (x == true) {
+ std::cout << "Hello!";
+ }
+}int main() {
+ int x = true;
+ do {
+ std::cout << "Hello!";
+ } while (x == false);
+}do { .. } so the condition gets checked after it executes.int main() {
+ int x = true;
+ for (int i = 0; i < 10; i++) {
+ std::cout << "Hello!";
+ }
+}i = 0, checks if i < 10, then outputs Hello!. Then i++ executes and i increases by 1. Then the loop repeats. The loop checks if i < 10. i is 1 now so this is true and the program outputs Hello!. This repeats until i < 10 is false which is when i = 10. Pretty simple stuff.
+
+ Now suppose you want to leave a loop before the condition is false or skip an iteration quickly. Then you can use the break and continue statements. break will BREAK out of a loop causing is to cease executing. continue will SKIP everthing after the continue and start back at the top of the loop.
+
+
+ Suppose you have a large array of if-else statements.
+
+ Instead of writing that, you could've used a switch:if (a == 1) {
+ ...
+} else if (a == 2) {
+ ...
+} else if (a == 3) {
+ ...
+} else if (a == 4) {
+ ...
+} else if (a == 5) {
+ ...
+} else if (a == 6) {
+ ...
+} else if (a == 7) {
+ ...
+} else { ... }
+
+ switch (a) {
+ case 1:
+ ...
+ break;
+ case 2:
+ ...
+ break;
+ case 3:
+ ...
+ break;
+ case 4:
+ ...
+ break;
+ case 5:
+ ...
+ break;
+ case 6:
+ ...
+ break;
+ case 7:
+ ...
+ break;
+ default:
+ ...
+ break;
+}
+
+ One caveat is that the case must be a literal value. It cannot be another value. Another is that a break; statement must be added to the end of every case or the statements will waterfall down from the case they started at to the next break statement. This is a feature of switches.
+
+ The ternary operator lets you condense a simple if-else statement into one line.
+
+ This means that if a is greater than b, assign x with 1. If a is not greater than b, assign x with 0. The ternary operator however needs the values in the if and else part to be of the same type. If they are not, the program will fail to compile.
+ x = (a > b) ? 1 : 0;