Download as pdf or txt
Download as pdf or txt
You are on page 1of 14

1 // This is a comment

2 /*
3 * Multi-line comment
4 */
5
6 // Tells the compiler iostream library which contains the function cout
7 #include <iostream>
8
9 // Allows us to use vectors
10 #include <vector>
11
12 // Allows us to use strings
13 #include <string>
14
15 // Allow us to work with files
16 #include <fstream>
17
18 // Allows functions in the std namespace to be used without their prefix
19 // std::cout becomes cout
20 using namespace std;
21
22 // ---------- FUNCTIONS ----------
23 // The function has return type, function name and attributes with
24 // their data types
25 // The attribute data types must match the value passed in
26 // This data is passed by value
27 // You can define default values to attributes as long as they come last
28 // This is known as a function prototype
29 int addNumbers(int firstNum, int secondNum = 0){
30
31 int combinedValue = firstNum + secondNum;
32
33 return combinedValue;
34
35 }
36
37 // An overloaded function has the same name, but different attributes
38 int addNumbers(int firstNum, int secondNum, int thirdNum){
39
40 return firstNum + secondNum + thirdNum;
41
42 }
43
44 // A recursive function is one that calls itself
45
46 int getFactorial(int number){
47
48 int sum;
49 if(number == 1) sum = 1;
50 else sum = (getFactorial(number - 1) * number);
51 return sum;
52
53 // getFactorial(2) [Returns 2] * 3
54 // getFactorial(1) [Returns 1] * 2 <This value goes above>
55 // 2 * 3 = 6
56
57 }
58
59 // Doesn't have a return type so use void
60 // Since I'm getting a pointer use int*
61 // Refer to the referenced variable with *age
62 void makeMeYoung(int* age){
63
64 cout << "I used to be " << *age << endl;
65 *age = 21;
66
67 }
68
69 // A function that receives a reference can manipulate the value globally
70 void actYourAge(int& age){
71
72 age = 39;
73
74 }
75
76 // ---------- END OF FUNCTIONS ----------
77
78 // ---------- CLASSES ----------
79 // classes start with the name class
80
81 class Animal
82 {
83
84 // private variables are only available to methods in the class
85 private:
86 int height;
87 int weight;
88 string name;
89
90 // A static variable shares the same value with every object in the class
91 static int numOfAnimals;
92
93 // Public variables can be accessed by anything with access to the object
94 public:
95 int getHeight(){return height;}
96 int getWeight(){return weight;}
97 string getName(){return name;}
98 void setHeight(int cm){ height = cm; }
99 void setWeight(int kg){ weight = kg; }
100 void setName(string dogName){ name = dogName; }
101
102 // Declared as a prototype
103 void setAll(int, int, string);
104
105 // Declare the constructor
106 Animal(int, int, string);
107
108 // Declare the deconstructor
109 ~Animal();
110
111 // An overloaded constructor called when no data is passed
112 Animal();
113
114 // protected members are available to members of the same class and
115 // sub classes
116
117 // Static methods aren't attached to an object and can only access
118 // static member variables
119 static int getNumOfAnimals() { return numOfAnimals; }
120
121 // This method will be overwritten in Dog
122 void toString();
123
124 };
125
126 int Animal::numOfAnimals = 0;
127
128 // Define the protoype method setAll
129 void Animal::setAll(int height, int weight, string name){
130
131 // This is used to refer to an object created of this class type
132 this -> height = height;
133 this -> weight = weight;
134 this -> name = name;
135 Animal::numOfAnimals++;
136
137 }
138
139 // A constructor is called when an object is created
140 Animal::Animal(int height, int weight, string name) {
141
142 this -> height = height;
143 this -> weight = weight;
144 this -> name = name;
145
146 }
147
148 // The destructor is called when an object is destroyed
149 Animal::~Animal() {
150
151 cout << "Animal " << this -> name << " destroyed" << endl;
152
153 }
154
155 // A constructor called when no attributes are passed
156 Animal::Animal() {
157 numOfAnimals++;
158 }
159
160 // This method prints object info to screen and will be overwritten
161 void Animal::toString(){
162
163 cout << this -> name << " is " << this -> height << " cms tall and "
164 << this -> weight << " kgs in weight" << endl;
165
166 }
167
168 // We can inherit the variables and methods of other classes
169 class Dog : public Animal{
170
171 private:
172 string sound = "Woof";
173 public:
174 void getSound() { cout << sound << endl; }
175
176 // Declare the constructor
177 Dog(int, int, string, string);
178
179 // Declare the default constructor and call the default superclass
180 // constructor
181 Dog() : Animal(){};
182
183 // Overwrite toString
184 void toString();
185
186 };
187
188 // Dog constructor passes the right attributes to the superclass
189 // constructor and then handles the attribute bark that remains
190 Dog::Dog(int height, int weight, string name, string bark) :
191 Animal(height, weight, name){
192
193 this -> sound = bark;
194
195 }
196
197 // toString method overwritten
198 void Dog::toString(){
199
200 // Because the attributes were private in Animal they must be retrieved
201 // by called the get methods
202 cout << this -> getName() << " is " << this -> getHeight() <<
203 " cms tall and " << this -> getWeight() << " kgs in weight and says " <<
204 this -> sound << endl;
205
206 }
207
208 // ---------- END OF CLASSES ----------
209
210 // This is where execution begins. Attributes can be sent to main
211 int main() {
212
213 // cout outputs text and a carriage return with endl
214 // Statements must end with a semicolon
215 // Strings must be surrounded by "
216 // << sends the text via standard output to the screen
217 cout << "Hello Internet" << endl;
218
219 // ---------- VARIABLES / DATA TYPES ----------
220 // Variables start with a letter and can contain letters, numbers and _
221 // They are case sensitive
222
223 // A value that won't change is a constant
224 // Starts with const and it should be uppercase
225 const double PI = 3.1415926535;
226
227 // chars can contain 1 character that are surrounded with ' and is one byte in size
228 char myGrade = 'A';
229
230 // bools have the value of (true/1) or (false/0)
231 bool isHappy = true;
232
233 // ints are whole numbers
234 int myAge = 39;
235
236 // floats are floating point numbers accurate to about 6 decimals
237 float favNum = 3.141592;
238
239 // doubles are floating point numbers accurate to about 15 digits
240 double otherFavNum = 1.6180339887;
241
242 // You can output a variable value like this
243 cout << "Favorite Number " << favNum << endl;
244
245 // Other types include
246 // short int : At least 16 bits
247 // long int : At least 32 bits
248 // long long int : At least 64 bits
249 // unsigned int : Same size as signed version
250 // long double : Not less then double
251
252 // You can get the number of bytes for a data type with sizeof
253
254 cout << "Size of int " << sizeof(myAge) << endl;
255 cout << "Size of char " << sizeof(myGrade) << endl;
256 cout << "Size of bool " << sizeof(isHappy) << endl;
257 cout << "Size of float " << sizeof(favNum) << endl;
258 cout << "Size of double " << sizeof(otherFavNum) << endl;
259
260 int largestInt = 2147483647;
261
262 cout << "Largest int " << largestInt << endl;
263
264 // ---------- ARITHMETIC ----------
265 // The arithmetic operators are +, -, *, /, %, ++, --
266
267 cout << "5 + 2 = " << 5+2 << endl;
268 cout << "5 - 2 = " << 5-2 << endl;
269 cout << "5 * 2 = " << 5*2 << endl;
270 cout << "5 / 2 = " << 5/2 << endl;
271 cout << "5 % 2 = " << 5%2 << endl;
272
273 int five = 5;
274 cout << "5++ = " << five++ << endl;
275 cout << "++5 = " << ++five << endl;
276 cout << "5-- = " << five-- << endl;
277 cout << "--5 = " << --five << endl;
278
279 // Shorthand assignment operators
280 // a += b == a = a + b
281 // There is also -=, *=, /=, %=
282
283 // Order of Operation states * and / is performed before + and -
284
285 cout << "1 + 2 - 3 * 2 = " << 1 + 2 - 3 * 2 << endl;
286 cout << "(1 + 2 - 3) * 2 = " << (1 + 2 - 3) * 2 << endl;
287
288 // ---------- CASTING ----------
289 // You convert from one data type to another by casting
290 // char, int, float, double
291
292 cout << "4 / 5 = " << 4 / 5 << endl;
293 cout << "4 / 5 = " << (float) 4 / 5 << endl;
294
295 // ---------- IF STATEMENT ----------
296 // Executes different code depending upon a condition
297
298 // Comparison operators include ==, !=, >, <, >=, <=
299 // Will return true (1) if the comparison is true, or false (0)
300
301 // Logical operators include &&, ||, !
302 // Used to test 2 or more conditionals
303
304 int age = 70;
305 int ageAtLastExam = 16;
306 bool isNotIntoxicated = true;
307
308 if((age >= 1) && (age < 16)){
309 cout << "You can't drive" << endl;
310 } else if(!isNotIntoxicated){
311 cout << "You can't drive" << endl;
312 } else if(age >= 80 && ((age > 100) || ((age - ageAtLastExam) > 5))){
313 cout << "You can't drive" << endl;
314 } else {
315 cout << "You can drive" << endl;
316 }
317
318 // ---------- SWITCH STATEMENT ----------
319 // switch is used when you have a limited number of possible options
320
321 int greetingOption = 2;
322
323 switch(greetingOption){
324
325 case 1 :
326 cout << "bonjour" << endl;
327 break;
328
329 case 2 :
330 cout << "Hola" << endl;
331 break;
332
333 case 3 :
334 cout << "Hallo" << endl;
335 break;
336
337 default :
338 cout << "Hello" << endl;
339 }
340
341 // ---------- TERNARY OPERATOR ----------
342 // Performs an assignment based on a condition
343 // variable = (condition) ? if true : if false
344
345 int largestNum = (5 > 2) ? 5 : 2;
346
347 cout << "The biggest number is " << largestNum << endl;
348
349 // ---------- ARRAYS ----------
350 // Arrays store multiple values of the same type
351
352 // You must provide a data type and the size of the array
353 int myFavNums[5];
354
355 // You can declare and add values in one step
356 int badNums[5] = {4, 13, 14, 24, 34};
357
358 // The first item in the array has the label (index) of 0
359 cout << "Bad Number 1: " << badNums[0] << endl;
360
361 // You can create multidimensional arrays
362 char myName[5][5] = {{'D','e','r','e','k'},{'B','a','n','a','s'}};
363
364 cout << "2nd Letter in 2nd Array: " << myName[1][1] << endl;
365
366 // You can change a value in an array using its index
367 myName[0][2] = 'e';
368
369 cout << "New Value " << myName[0][2] << endl;
370
371 // ---------- FOR LOOP ----------
372 // Continues to execute code as long as a condition is true
373
374 for(int i = 1; i <= 10; i++){
375
376 cout << i << endl;
377
378 }
379
380 // You can also cycle through an array by nesting for loops
381 for(int j = 0; j < 5; j++){
382
383 for(int k = 0; k < 5; k++){
384 cout << myName[j][k];
385 }
386
387 cout << endl;
388
389 }
390
391 // ---------- WHILE LOOP ----------
392 // Use a while loop when you don't know ahead of time when a loop will end
393
394 // Generate a random number between 1 and 100
395 int randNum = (rand() % 100) + 1;
396
397 while(randNum != 100){
398
399 cout << randNum << ", ";
400
401 // Used to get you out of the loop
402 randNum = (rand() % 100) + 1;
403
404 }
405
406 cout << endl;
407
408 // You can do the same as the for loop like this
409 // Create an index to iterate out side the while loop
410 int index = 1;
411
412 while(index <= 10){
413
414 cout << index << endl;
415
416 // Increment inside the loop
417 index++;
418
419 }
420
421 // ---------- DO WHILE LOOP ----------
422 // Used when you want to execute what is in the loop at least once
423
424 // Used to store a series of characters
425 string numberGuessed;
426 int intNumberGuessed = 0;
427
428 do {
429 cout << "Guess between 1 and 10: ";
430
431 // Allows for user input
432 // Pass the source and destination of the input
433 getline (cin,numberGuessed);
434
435 // stoi converts the string into an integer
436 intNumberGuessed = stoi(numberGuessed);
437 cout << intNumberGuessed << endl;
438
439 // We'll continue looping until the number entered is 4
440 } while (intNumberGuessed != 4);
441
442 cout << "You Win" << endl;
443
444 // ---------- STRINGS ----------
445 // The string library class provides a string object
446 // You must always surround strings with "
447 // Unlike the char arrays in c, the string object automatically resizes
448
449 // The C way of making a string
450 char happyArray[6] = {'H', 'a', 'p', 'p', 'y', '\0'};
451
452 // The C++ way
453 string birthdayString = " Birthday";
454
455 // You can combine / concatenate strings with +
456 cout << happyArray + birthdayString << endl;
457
458 string yourName;
459 cout << "What is your name? ";
460 getline (cin,yourName);
461
462 cout << "Hello " << yourName << endl;
463
464 double eulersConstant = .57721;
465 string eulerGuess;
466 double eulerGuessDouble;
467 cout << "What is Euler's Constant? ";
468 getline (cin,eulerGuess);
469
470 // Converts a string into a double
471 // stof() for floats
472 eulerGuessDouble = stod(eulerGuess);
473
474 if(eulerGuessDouble == eulersConstant){
475
476 cout << "You are right" << endl;
477
478 } else {
479
480 cout << "You are wrong" << endl;
481
482 }
483
484 // Size returns the number of characters
485 cout << "Size of string " << eulerGuess.size() << endl;
486
487 // empty tells you if string is empty or not
488 cout << "Is string empty " << eulerGuess.empty() << endl;
489
490 // append adds strings together
491 cout << eulerGuess.append(" was your guess") << endl;
492
493 string dogString = "dog";
494 string catString = "cat";
495
496 // Compare returns a 0 for a match, 1 if less than, -1 if greater then
497 cout << dogString.compare(catString) << endl;
498 cout << dogString.compare(dogString) << endl;
499 cout << catString.compare(dogString) << endl;
500
501 // assign copies a value to another string
502 string wholeName = yourName.assign(yourName);
503 cout << wholeName << endl;
504
505 // You can get a substring as well by defining the starting index and the
506 // number of characters to copy
507 string firstName = wholeName.assign(wholeName, 0, 5);
508 cout << firstName << endl;
509
510 // find returns the index for the string your searching for starting
511 // from the index defined
512 int lastNameIndex = yourName.find("Banas", 0);
513 cout << "Index for last name " << lastNameIndex << endl;
514
515 // insert places a string in the index defined
516 yourName.insert(5, " Justin");
517 cout << yourName << endl;
518
519 // erase will delete 6 characters starting at index 7
520 yourName.erase(6,7);
521 cout << yourName << endl;
522
523 // replace 5 characters starting at index 6 with the string Maximus
524 yourName.replace(6,5,"Maximus");
525 cout << yourName << endl;
526
527 // ---------- VECTORS ----------
528 // Vectors are like arrays, but their size can change
529
530 vector <int> lotteryNumVect(10);
531
532 int lotteryNumArray[5] = {4, 13, 14, 24, 34};
533
534 // Add the array to the vector starting at the beginning of the vector
535 lotteryNumVect.insert(lotteryNumVect.begin(), lotteryNumArray, lotteryNumArray+3);
536
537 // Insert a value into the 5th index
538 lotteryNumVect.insert(lotteryNumVect.begin()+5, 44);
539
540 // at gets the value in the specified index
541 cout << "Value in 5 " << lotteryNumVect.at(5) << endl;
542
543 // push_back adds a value at the end of a vector
544 lotteryNumVect.push_back(64);
545
546 // back gets the value in the final index
547 cout << "Final Value " << lotteryNumVect.back() << endl;
548
549 // pop_back removes the final element
550 lotteryNumVect.pop_back();
551
552 // front returns the first element
553 cout << "First Element " << lotteryNumVect.front() << endl;
554
555 // back returns the last element
556 cout << "Last Element " << lotteryNumVect.back() << endl;
557
558 // empty tells you if the vector is empty
559 cout << "Vector Empty " << lotteryNumVect.empty() << endl;
560
561 // size returns the total number of elements
562 cout << "Number of Vector Elements " << lotteryNumVect.size() << endl;
563
564 // ---------- FUNCTIONS ----------
565 // Functions allow you to reuse and better organize your code
566
567 cout << addNumbers(1) << endl;
568
569 // You can't access values created in functions (Out of Scope)
570 // cout << combinedValue << endl;
571
572 cout << addNumbers(1, 5, 6) << endl;
573
574 cout << "The factorial of 3 is " << getFactorial(3) << endl;
575
576 // ---------- FILE I/O ----------
577 // We can read and write to files using text or machine readable binary
578
579 string steveQuote = "A day without sunshine is like, you know, night";
580
581 // Create an output filestream and if the file doesn't exist create it
582 ofstream writer("stevequote.txt");
583
584 // Verify that the file stream object was created
585 if(! writer){
586
587 cout << "Error opening file" << endl;
588
589 // Signal that an error occurred
590 return -1;
591
592 } else {
593
594 // Write the text to the file
595 writer << steveQuote << endl;
596
597 // Close the file
598 writer.close();
599
600 }
601
602 // Open a stream to append to whats there with ios::app
603 // ios::binary : Treat the file as binary
604 // ios::in : Open a file to read input
605 // ios::trunc : Default
606 // ios::out : Open a file to write output
607 ofstream writer2("stevequote.txt", ios::app);
608
609 if(! writer2){
610
611 cout << "Error opening file" << endl;
612
613 // Signal that an error occurred
614 return -1;
615
616 } else {
617
618 writer2 << "\n- Steve Martin" << endl;
619 writer2.close();
620
621 }
622
623 char letter;
624
625 // Read characters from a file using an input file stream
626 ifstream reader("stevequote.txt");
627
628 if(! reader){
629
630 cout << "Error opening file" << endl;
631 return -1;
632
633 } else {
634
635 // Read each character from the stream until end of file
636 for(int i = 0; ! reader.eof(); i++){
637
638 // Get the next letter and output it
639 reader.get(letter);
640 cout << letter;
641
642 }
643
644 cout << endl;
645 reader.close();
646
647 }
648
649 // ---------- EXCEPTION HANDLING ----------
650 // You can be prepared for potential problems with exception handling
651
652 int number = 0;
653
654 try{
655
656 if(number != 0){
657 cout << 2/number << endl;
658 } else throw(number);
659
660 }
661 catch(int number){
662
663 cout << number << " is not valid input" << endl;
664
665 }
666
667 // ---------- POINTERS ----------
668 // When data is stored it is stored in an appropriately sized box based
669 // on its data type
670
671 int myAge = 39;
672 char myGrade = 'A';
673
674 cout << "Size of int " << sizeof(myAge) << endl;
675 cout << "Size of char " << sizeof(myGrade) << endl;
676
677 // You can reference the box (memory address) where data is stored with
678 // the & reference operator
679
680 cout << "myAge is located at " << &myAge << endl;
681
682 // A pointer can store a memory address
683 // The data type must be the same as the data referenced and it is followed
684 // by a *
685
686 int* agePtr = &myAge;
687
688 // You can access the memory address and the data
689 cout << "Address of pointer " << agePtr << endl;
690
691 // * is the dereference or indirection operator
692 cout << "Data at memory address " << *agePtr << endl;
693
694 int badNums[5] = {4, 13, 14, 24, 34};
695 int* numArrayPtr = badNums;
696
697 // You can increment through an array using a pointer with ++ or --
698 cout << "Address " << numArrayPtr << " Value " << *numArrayPtr << endl;
699 numArrayPtr++;
700 cout << "Address " << numArrayPtr << " Value " << *numArrayPtr << endl;
701
702 // An array name is just a pointer to the array
703 cout << "Address " << badNums << " Value " << *badNums << endl;
704
705 // When you pass a variable to a function you are passing the value
706 // When you pass a pointer to a function you are passing a reference
707 // that can be changed
708
709 makeMeYoung(&myAge);
710
711 cout << "I'm " << myAge << " years old now" << endl;
712
713 // & denotes that ageRef will be a reference to the assigned variable
714 int& ageRef = myAge;
715
716 cout << "ageRef : " << ageRef << endl;
717
718 // It can manipulate the other variables data
719 ageRef++;
720
721 cout << "myAge : " << myAge << endl;
722
723 // You can pass the reference to a function
724 actYourAge(ageRef);
725
726 cout << "myAge : " << myAge << endl;
727
728 // When deciding on whether to use pointers or references
729 // Use Pointers if you don't want to initialize at declaration, or if
730 // you need to assign another variable
731 // otherwise use a reference
732
733 // ---------- CLASSES & OBJECTS ----------
734 // Classes are the blueprints for modeling real world objects
735 // Real world objects have attributes, classes have members / variables
736 // Real world objects have abilities, classes have methods / functions
737 // Classes believe in hiding data (encapsulation) from outside code
738
739 // Declare a Animal type object
740 Animal fred;
741
742 // Set the values for the Animal
743 fred.setHeight(33);
744 fred.setWeight(10);
745 fred.setName("Fred");
746
747 // Get the values for the Animal
748 cout << fred.getName() << " is " << fred.getHeight() << " cms tall and "
749 << fred.getWeight() << " kgs in weight" << endl;
750
751 fred.setAll(34, 12, "Fred");
752
753 cout << fred.getName() << " is " << fred.getHeight() << " cms tall and "
754 << fred.getWeight() << " kgs in weight" << endl;
755
756 // Creating an object using the constructor
757 Animal tom(36, 15, "Tom");
758
759 cout << tom.getName() << " is " << tom.getHeight() << " cms tall and "
760 << tom.getWeight() << " kgs in weight" << endl;
761
762 // Demonstrate the inheriting class Dog
763 Dog spot(38, 16, "Spot", "Woof");
764
765 // static methods are called by using the class name and the scope operator
766 cout << "Number of Animals " << Animal::getNumOfAnimals() << endl;
767
768 spot.getSound();
769
770 // Test the toString method that will be overwritten
771 tom.toString();
772 spot.toString();
773
774 // We can call the superclass version of a method with the class name
775 // and the scope operator
776 spot.Animal::toString();
777
778 // When a function finishes it must return an integer value
779 // Zero means that the function ended with success
780 return 0;
781 }

You might also like