Advertisement
DeathToTheStadium

Tutorial C++

Jan 10th, 2020
3,089
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 52.15 KB | None | 0 0
  1. /*By Joseph.S Aspiring Engineer/Programmer
  2. __ __ _ _
  3. \ \ / / | | | |
  4. \ \ /\ / / ___ | | ___ ___ _ __ ___ ___ | |_ ___ _ __ ___ _ _
  5. \ \/ \/ / / _ \ | | / __| / _ \ | '_ ` _ \ / _ \ | __| / _ \ | '_ ` _ \ | | | |
  6. \ /\ / | __/ | | | (__ | (_) | | | | | | | | __/ | |_ | (_) | | | | | | | | |_| |
  7. \/ \/ \___| |_| \___| \___/ |_| |_| |_| \___| \__| \___/ |_| |_| |_| \__, |
  8. __/ |
  9. |___/
  10. _____ _ _ _
  11. / ____| _ _ | | (_) | |
  12. | | _| |_ _| |_ | | _ | |__ _ __ __ _ _ __ _ _
  13. | | |_ _| |_ _| | | | | | '_ \ | '__| / _` | | '__| | | | |
  14. | |____ |_| |_| | |____ | | | |_) | | | | (_| | | | | |_| |
  15. \_____| |______| |_| |_.__/ |_| \__,_| |_| \__, |
  16. __/ |
  17. |___/
  18. =====================================================================================================
  19. =====================================================================================================
  20. */
  21.  
  22. /* _ _
  23. (_) | |
  24. _ _ __ | |_ _ __ ___
  25. | | '_ \| __| '__/ _ \
  26. | | | | | |_| | | (_) |
  27. |_|_| |_|\__|_| \___/
  28. ====================================================================================================
  29. */
  30.  
  31. /*What is C++?
  32.  
  33. C++ is a cross-platformed language that can be used to create sophisticated high-performance applications.
  34.  
  35. C++ was developed by Bjarne Stroustrup at Bell labs in 1979, as an extension to the C language.
  36.  
  37. C++ gives programmers a high level of control over system resources and memory.
  38.  
  39. The language was updated 3 major times in 2011, 2014, and 2017 to C++11, C++14, and C++17.
  40.  
  41.  
  42.  
  43. Why Use C++?
  44.  
  45. C++ is one of the world's most popular programming languages.
  46.  
  47. C++ can be found in today's operating systems, Graphical User Interfaces, and embedded systems.
  48.  
  49. C++ is an object oriented language which gives a clear structure to programs and allows code to be reused, lowering development costs.
  50.  
  51. C++ is portable and can be used to develop applications that can be adapted to multiple platforms.
  52.  
  53. C++ is fun and easy to learn!
  54.  
  55. As C++ is close to C# and Java, it makes it easy for programmers to switch to C++ or vice versa*/
  56.  
  57. /*
  58. =====================================================================================================
  59. =====================================================================================================
  60.  
  61.  
  62. _____ _ _ _ _____ _ _ _
  63. / ____| | | | | (_) / ____| | | | | |
  64. | | __ ___| |_| |_ _ _ __ __ _ | (___ | |_ __ _ _ __| |_ ___ __| |
  65. | | |_ |/ _ \ __| __| | '_ \ / _` | \___ \| __/ _` | '__| __/ _ \/ _` |
  66. | |__| | __/ |_| |_| | | | | (_| | ____) | || (_| | | | || __/ (_| |
  67. \_____|\___|\__|\__|_|_| |_|\__, | |_____/ \__\__,_|_| \__\___|\__,_|
  68. __/ |
  69. |___/
  70. =====================================================================================================
  71. */
  72.  
  73. /*
  74. C++ Get Started
  75. To start using C++, you need two things:
  76.  
  77. A text editor, like Notepad, to write C++ code
  78. A compiler, like GCC, to translate the C++ code into a language that the computer will understand
  79. There are many text editors and compilers to choose from. In this tutorial, we will use an IDE (see below).
  80.  
  81. C++ Install IDE
  82. An IDE (Integrated Development Environment) is used to edit AND compile the code.
  83.  
  84. Popular IDE's include Code::Blocks, Eclipse, and Visual Studio. These are all free, and they can be used to both edit and debug C++ code.
  85.  
  86. Note: Web-based IDE's can work as well, but functionality is limited.
  87.  
  88. We will use Code::Blocks in our tutorial, which we believe is a good place to start.
  89.  
  90. You can find the latest version of Codeblocks at http://www.codeblocks.org/downloads/26. Download the mingw-setup.exe file, which will install the text editor with a compiler.
  91.  
  92. C++ Quickstart
  93. Let's create our first C++ file.
  94.  
  95. Open Codeblocks and go to File > New > Empty File.
  96.  
  97. Write the following C++ code and save the file as myfirstprogram.cpp (File > Save File as):
  98.  
  99. myfirstprogram.cpp
  100. #include <iostream>
  101. using namespace std;
  102.  
  103. int main() {
  104. cout << "Hello World!";
  105. return 0;
  106. }
  107. Don't worry if you don't understand the code above - we will discuss it in detail in later chapters. For now, focus on how to run the code.
  108.  
  109. In Codeblocks, it should look like this:
  110.  
  111.  
  112. Then, go to Build > Build and Run to run (execute) the program. The result will look something to this:
  113.  
  114. Hello World!
  115. Process returned 0 (0x0) execution time : 0.011 s
  116. Press any key to continue.
  117. Congratulations! You have now written and executed your first C++ program.
  118. */
  119.  
  120. /*
  121. =====================================================================================================
  122. =====================================================================================================
  123.  
  124.  
  125. _____ _
  126. / ____| | |
  127. | (___ _ _ _ __ | |_ __ ___ __
  128. \___ \| | | | '_ \| __/ _` \ \/ /
  129. ____) | |_| | | | | || (_| |> <
  130. |_____/ \__, |_| |_|\__\__,_/_/\_\
  131. __/ |
  132. |___/
  133.  
  134. =====================================================================================================
  135. */
  136.  
  137. /*
  138. C++ Syntax
  139. Let's break up the following code to understand it better:
  140.  
  141. Example
  142. #include <iostream>
  143. using namespace std;
  144.  
  145. int main() {
  146. cout << "Hello World!";
  147. return 0;
  148. }
  149. Example explained
  150. Line 1: #include <iostream> is a header file library that lets us work with input and output objects, such as cout (used in line 5). Header files add functionality to C++ programs.
  151.  
  152. Line 2: using namespace std means that we can use names for objects and variables from the standard library.
  153.  
  154. Don't worry if you don't understand how #include <iostream> and using namespace std works. Just think of it as something that (almost) always appears in your program.
  155.  
  156. Line 3: A blank line. C++ ignores white space.
  157.  
  158. Line 4: Another thing that always appear in a C++ program, is int main(). This is called a function. Any code inside its curly brackets {} will be executed.
  159.  
  160. Line 5: cout (pronounced "see-out") is an object used to output/print text. In our example it will output "Hello World".
  161.  
  162. Note: Every C++ statement ends with a semicolon ;.
  163.  
  164. Note: The body of int main() could also been written as:
  165. int main () { cout << "Hello World! "; return 0; }
  166.  
  167. Remember: The compiler ignores white spaces. However, multiple lines makes the code more readable.
  168.  
  169. Line 6: return 0 ends the main function.
  170.  
  171. Omitting Namespace
  172. You might see some C++ programs that runs without the standard namespace library. The using namespace std line can be omitted and replaced with the std keyword, followed by the :: operator for some objects:
  173.  
  174. Example
  175. #include <iostream>
  176.  
  177. int main() {
  178. std::cout << "Hello World!";
  179. return 0;
  180. }
  181. */
  182.  
  183. /*
  184. =====================================================================================================
  185. =====================================================================================================
  186.  
  187. ____ _ _ _______ _ _ _______ _ __
  188. / __ \ | | | | / / __ \ (_) | | |__ __| | |\ \
  189. | | | |_ _| |_ _ __ _ _| |_ | || |__) | __ _ _ __ | |_ | | _____ _| |_| |
  190. | | | | | | | __| '_ \| | | | __| | || ___/ '__| | '_ \| __| | |/ _ \ \/ / __| |
  191. | |__| | |_| | |_| |_) | |_| | |_ | || | | | | | | | | |_ | | __/> <| |_| |
  192. \____/ \__,_|\__| .__/ \__,_|\__| | ||_| |_| |_|_| |_|\__| |_|\___/_/\_\\__| |
  193. | | \_\ /_/
  194. |_|
  195. =====================================================================================================
  196. */
  197.  
  198. /* #include <iostream>is a header file library that lets us work with input and output objects
  199. , such as cout (used in line 5). Header files add functionality to C++ programs.*/
  200. #include <iostream>
  201. using namespace std;
  202. // make sure that you add a Semi Colon at the end of all your lines as its will note start a new line without it
  203. int add(int a, int b) {
  204. return a + b;
  205. };
  206. int main() {
  207. int num1;
  208. int num2;
  209. cout << "what is Variable a:";
  210. cin >> num1;
  211. cout << "what is Variable b:";
  212. cin >> num2;
  213. cout << add(num1, num2) <<endl;
  214. /*You can add as many cout objects as you want. However,
  215. note that it does not insert a new line at the end of the output:*/
  216. cout << "Hello im a string \n";
  217. // You can Use \n to break a line and to make a line space use it twice \n\n
  218. cout << "Hello World! \n\n";
  219. // or you can use a "end + LowerCase L" = endl
  220. cout << " there is a free line that is empty above me" << endl;
  221. //Both \n and endl are used to break lines. However, \n is used more often and is the preferred way.
  222.  
  223. /*
  224. =====================================================================================================
  225. =====================================================================================================
  226. _____ _
  227. / ____| | |
  228. | | ___ _ __ ___ _ __ ___ ___ _ __ | |_ ___
  229. | | / _ \| '_ ` _ \| '_ ` _ \ / _ \ '_ \| __/ __|
  230. | |___| (_) | | | | | | | | | | | __/ | | | |_\__ \
  231. \_____\___/|_| |_| |_|_| |_| |_|\___|_| |_|\__|___/
  232. =====================================================================================================
  233. */
  234.  
  235. /*
  236. single line Comments are written Using "// folloew by your comment"
  237.  
  238. Multi-Line Comments are Made Using to slashes and 2 asterisks in the middle
  239. followed with your comment in the center
  240.  
  241. /*your Comment Goes in here*/
  242.  
  243. /*Using commenets to give reminders to you or other programmers so
  244. you can know what something does and figure it out l8ter*/
  245.  
  246. /*
  247. =====================================================================================================
  248. =====================================================================================================
  249.  
  250. __ __ _ _ _
  251. \ \ / / (_) | | | |
  252. \ \ / /_ _ _ __ _ __ _| |__ | | ___ ___
  253. \ \/ / _` | '__| |/ _` | '_ \| |/ _ \/ __|
  254. \ / (_| | | | | (_| | |_) | | __/\__ \
  255. \/ \__,_|_| |_|\__,_|_.__/|_|\___||___/
  256. =====================================================================================================
  257. */
  258. /*
  259. C++ Variables
  260. Variables are containers for storing data values.
  261.  
  262. In C++, there are different types of variables (defined with different keywords), for example:
  263.  
  264. int - stores integers (whole numbers), without decimals, such as 123 or -123
  265. double - stores floating point numbers, with decimals, such as 19.99 or -19.99
  266. char - stores single characters, such as 'a' or 'B'. Char values are surrounded by single quotes
  267. string - stores text, such as "Hello World". String values are surrounded by double quotes
  268. bool - stores values with two states: true or false
  269.  
  270.  
  271.  
  272.  
  273. C++ Identifiers
  274. All C++ variables must be identified with unique names.
  275.  
  276. These unique names are called identifiers.
  277.  
  278. Identifiers can be short names (like x and y) or more descriptive names (age, sum, totalVolume).
  279.  
  280. Note: It is recommended to use descriptive names in order to create understandable and maintainable code.
  281.  
  282. The general rules for constructing names for variables (unique identifiers) are:
  283.  
  284. Names can contain letters, digits and underscores
  285. Names must begin with a letter or an underscore (_)
  286. Names are case sensitive (myVar and myvar are different variables)
  287. Names cannot contain whitespaces or special characters like !, #, %, etc.
  288. Reserved words (like C++ keywords, such as int) cannot be used as names
  289.  
  290. Declaring (Creating) Variables
  291. To create a variable, you must specify the type and assign it a value:
  292. */
  293. int Name1 = 12;
  294. string Name2 = "A Value";
  295. double Name3 = 12.45;
  296. char Name4 = 'c'; char Name5 = 'h'; char Name6 = 'a'; char Name7 = 'r';
  297. bool Name8 = true; bool Name9 = false;
  298.  
  299. cout << Name1 << endl << Name2 << endl << Name3 << endl << Name4 << Name5 << Name6 << Name7 << endl << Name8 << endl << Name9 << endl; ;
  300. // ps you can also declare variables beroe asiging a value
  301. string NovaluetillDeclared;
  302. NovaluetillDeclared = "i just assigned the value";
  303. //you can also change values by assigning a difeenet value using the naming conventions
  304. int value = 0;
  305. cout << "value:" << value<< endl;
  306. value = 1;
  307. cout << "value:"<<value<<endl;
  308.  
  309. //if you need a value that is constant and unchanging , then delcare a variable with "const" in front of it
  310. const int value1 = 0;
  311. cout << "value:" << value1 << endl;
  312. value = 1;
  313. cout << "value:" << value1 << endl;
  314.  
  315. // you can easily add,subtract,multiply,divide with variables lets practice with addition
  316. int x = 32;
  317. int y = 8;
  318. int xy = x + y;
  319. cout <<"x="<< x <<endl<< "y="<<y<<endl<<"x+y="<< xy << endl;
  320.  
  321.  
  322. /*
  323. =====================================================================================================
  324. =====================================================================================================
  325. _ _
  326. (_) | |
  327. _ _ ___ ___ _ __ _ _ __ _ __ _ _ | |_
  328. | | | | / __| / _ \ | '__| | | | '_ \ | '_ \ | | | | | __|
  329. | |_| | \__ \ | __/ | | | | | | | | | |_) | | |_| | | |_
  330. \__,_| |___/ \___| |_| |_| |_| |_| | .__/ \__,_| \__|
  331. | |
  332. |_|
  333.  
  334. =====================================================================================================
  335. */
  336.  
  337. /*
  338.  
  339. C++ User Input
  340. You have already learned that cout is used to output (print) values. Now we will use cin to get user input.
  341.  
  342. cin is a predefined variable that reads data from the keyboard with the extraction operator (>>).
  343.  
  344. In the following example, the user can input a number, which is stored in the variable x. Then we print the value of x:
  345. */
  346. int inputvalue;
  347. cout << "type a number:";// Type a number and press enter
  348. cin >> inputvalue;// Get user input from the keyboard
  349. cout << "Your number is: " << inputvalue << endl;// Display the input value
  350.  
  351. /*
  352. =====================================================================================================
  353. =====================================================================================================
  354.  
  355. _ _ _
  356. | | | | | |
  357. __| | __ _| |_ __ _ | |_ _ _ _ __ ___ ___
  358. / _` |/ _` | __/ _` | | __| | | | '_ \ / _ \/ __|
  359. | (_| | (_| | || (_| | | |_| |_| | |_) | __/\__ \
  360. \__,_|\__,_|\__\__,_| \__|\__, | .__/ \___||___/
  361. __/ | |
  362. |___/|_|
  363. =====================================================================================================
  364. */
  365.  
  366. /*
  367. C++ Data Types
  368. As explained in the Variables chapter, a variable in C++ must be a specified data type:
  369.  
  370. Example
  371. int myNum = 5; // Integer (whole number)
  372. float myFloatNum = 5.99; // Floating point number
  373. double myDoubleNum = 9.98; // Floating point number
  374. char myLetter = 'D'; // Character
  375. bool myBoolean = true; // Boolean
  376. string myText = "Hello"; // String
  377. Basic Data Types
  378. The data type specifies the size and type of information the variable will store:
  379.  
  380. Data Type Size Description
  381. int 4 bytes Stores whole numbers, without decimals
  382. float 4 bytes Stores fractional numbers, containing one or more decimals. Sufficient for storing 7 decimal digits
  383. double 8 bytes Stores fractional numbers, containing one or more decimals. Sufficient for storing 15 decimal digits
  384. boolean 1 byte Stores true or false values
  385. char 1 byte Stores a single character/letter/number, or ASCII values
  386. Use int when you need to store a whole number without decimals, like 35 or 1000, and float or double when you need a floating point number (with decimals), like 9.99 or 3.14515.
  387.  
  388. int
  389. int myNum = 1000;
  390. cout << myNum;
  391. float
  392. float myNum = 5.75;
  393. cout << myNum;
  394. double
  395. double myNum = 19.99;
  396. cout << myNum;
  397. float vs. double
  398.  
  399. The precision of a floating point value indicates how many digits the value can have after the decimal point. The precision of float is only six or seven decimal digits, while double variables have a precision of about 15 digits. Therefore it is safer to use double for most calculations.
  400.  
  401. Scientific Numbers
  402. A floating point number can also be a scientific number with an "e" to indicate the power of 10:
  403.  
  404. Example
  405. float f1 = 35e3;
  406. double d1 = 12E4;
  407. cout << f1;
  408. cout << d1;
  409. Booleans
  410. A boolean data type is declared with the bool keyword and can only take the values true or false. When the value is returned, true = 1 and false = 0.
  411.  
  412. Example
  413. bool isCodingFun = true;
  414. bool isFishTasty = false;
  415. cout << isCodingFun; // Outputs 1 (true)
  416. cout << isFishTasty; // Outputs 0 (false)
  417. Boolean values are mostly used for conditional testing, which you will learn more about in a later chapter.
  418.  
  419. Characters
  420. The char data type is used to store a single character. The character must be surrounded by single quotes, like 'A' or 'c':
  421.  
  422. Example
  423. char myGrade = 'B';
  424. cout << myGrade;
  425. Alternatively, you can use ASCII values to display certain characters:
  426.  
  427. Example
  428. char a = 65, b = 66, c = 67;
  429. cout << a;
  430. cout << b;
  431. cout << c;
  432. Tip: A list of all ASCII values can be found in our ASCII Table Reference.
  433.  
  434. Strings
  435. The string type is used to store a sequence of characters (text). This is not a built-in type, but it behaves like one in its most basic usage. String values must be surrounded by double quotes:
  436.  
  437. Example
  438. string greeting = "Hello";
  439. cout << greeting;
  440.  
  441. */
  442. /*
  443. =====================================================================================================
  444. =====================================================================================================
  445. ____ _
  446. / __ \ | |
  447. | | | |_ __ ___ _ __ __ _| |_ ___ _ __ ___
  448. | | | | '_ \ / _ \ '__/ _` | __/ _ \| '__/ __|
  449. | |__| | |_) | __/ | | (_| | || (_) | | \__ \
  450. \____/| .__/ \___|_| \__,_|\__\___/|_| |___/
  451. | |
  452. |_|
  453. =====================================================================================================
  454. */
  455.  
  456. /*
  457. C++ Operators
  458. Operators are used to perform operations on variables and values.
  459.  
  460. In the example below, we use the + operator to add together two values:
  461.  
  462. Example
  463. int x = 100 + 50;
  464. Although the + operator is often used to add together two values, like in the example above, it can also be used to add together a variable and a value, or a variable and another variable:
  465.  
  466. Example
  467. int sum1 = 100 + 50; // 150 (100 + 50)
  468. int sum2 = sum1 + 250; // 400 (150 + 250)
  469. int sum3 = sum2 + sum2; // 800 (400 + 400)
  470. C++ divides the operators into the following groups:
  471.  
  472. Arithmetic operators
  473. Assignment operators
  474. Comparison operators
  475. Logical operators
  476. Bitwise operators
  477. Arithmetic Operators
  478. Arithmetic operators are used to perform common mathematical operations.
  479.  
  480. Operator Name Description Example
  481. + Addition Adds together two values x + y
  482. - Subtraction Subtracts one value from another x - y
  483. * Multiplication Multiplies two values x * y
  484. / Division Divides one value from another x / y
  485. % Modulus Returns the division remainder x % y
  486. ++ Increment Increases the value of a variable by 1 ++x
  487. -- Decrement Decreases the value of a variable by 1 --x
  488.  
  489. C++ Assignment Operators
  490. Assignment operators are used to assign values to variables.
  491.  
  492. In the example below, we use the assignment operator (=) to assign the value 10 to a variable called x:
  493.  
  494. Example
  495. int x = 10;
  496. The addition assignment operator (+=) adds a value to a variable:
  497.  
  498. Example
  499. int x = 10;
  500. x += 5;
  501. A list of all assignment operators:
  502.  
  503. Operator Example Same As
  504. = x = 5 x = 5
  505. += x += 3 x = x + 3
  506. -= x -= 3 x = x - 3
  507. *= x *= 3 x = x * 3
  508. /= x /= 3 x = x / 3
  509. %= x %= 3 x = x % 3
  510. &= x &= 3 x = x & 3
  511. |= x |= 3 x = x | 3
  512. ^= x ^= 3 x = x ^ 3
  513. >>= x >>= 3 x = x >> 3
  514. <<= x <<= 3 x = x << 3
  515.  
  516. C++ Comparison Operators
  517. Comparison operators are used to compare two values.
  518.  
  519. Tip: The return value is either true (1) or false (0). You will learn more about them and how to use them in a later chapter.
  520.  
  521. Operator Name Example Try it
  522. == Equal to x == y
  523. != Not equal x != y
  524. > Greater than x > y
  525. < Less than x < y
  526. >= Greater than or equal to x >= y
  527. <= Less than or equal to x <= y
  528. */
  529.  
  530. /*
  531. =====================================================================================================
  532. =====================================================================================================
  533. _____ _ _
  534. / ____| | (_)
  535. | (___ | |_ _ __ _ _ __ __ _ ___
  536. \___ \| __| '__| | '_ \ / _` / __|
  537. ____) | |_| | | | | | | (_| \__ \
  538. |_____/ \__|_| |_|_| |_|\__, |___/
  539. __/ |
  540. |___/
  541. =====================================================================================================
  542. */
  543.  
  544. /*
  545. C++ Strings
  546. Strings are used for storing text.
  547.  
  548. A string variable contains a collection of characters surrounded by double quotes:
  549.  
  550. Example
  551. Create a variable of type string and assign it a value:
  552.  
  553. string greeting = "Hello";
  554. To use strings, you must include an additional header file in the source code, the <string> library:
  555.  
  556. Example
  557. // Include the string library
  558. #include <string>
  559.  
  560. // Create a string variable
  561. string greeting = "Hello";
  562. String Concatenation
  563. The + operator can be used between strings to add them together to make a new string. This is called concatenation:
  564.  
  565. Example
  566. string firstName = "John ";
  567. string lastName = "Doe";
  568. string fullName = firstName + lastName;
  569. cout << fullName;
  570. Note that we added a space after firstName to create a space between John and Doe on output.
  571.  
  572. String Length
  573. A string in C++ is actually an object, which contain functions that can perform certain operations on strings. For example, the length of a string can be found with the length() function:
  574.  
  575. Example
  576. string txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
  577. cout << "The length of the txt string is: " << txt.length();
  578. Access Strings
  579. You can access the characters in a string by referring to its index number inside square brackets [].
  580.  
  581. This example prints the first character in myString:
  582.  
  583. Example
  584. string myString = "Hello";
  585. cout << myString[0];
  586. // Outputs H
  587. Note: String indexes start with 0: [0] is the first character. [1] is the second character, etc.
  588.  
  589. This example prints the second character in myString:
  590.  
  591. Example
  592. string myString = "Hello";
  593. cout << myString[1];
  594. // Outputs e
  595. Change String Characters
  596. To change the value of a specific character in a string, refer to the index number, and use single quotes:
  597.  
  598. Example
  599. string myString = "Hello";
  600. myString[0] = 'J';
  601. cout << myString;
  602. // Outputs Jello instead of Hello
  603. User Input Strings
  604. It is possible to use the extraction operator >> on cin to display a string entered by a user:
  605.  
  606. Example
  607. string firstName;
  608. cout << "Type your first name: ";
  609. cin >> firstName; // get user input from the keyboard
  610. cout << "Your name is: " << firstName;
  611.  
  612. // Type your first name: John
  613. // Your name is: John
  614. However, cin considers a space (whitespace, tabs, etc) as a terminating character, which means that it can only display a single word (even if you type many words):
  615.  
  616. Example
  617. string fullName;
  618. cout << "Type your full name: ";
  619. cin >> fullName;
  620. cout << "Your name is: " << fullName;
  621.  
  622. // Type your full name: John Doe
  623. // Your name is: John
  624. From the example above, you would expect the program to print "John Doe", but it only prints "John".
  625.  
  626. That's why, when working with strings, we often use the getline() function to read a line of text. It takes cin as the first parameter, and the string variable as second:
  627.  
  628. Example
  629. string fullName;
  630. cout << "Type your full name: ";
  631. getline (cin, fullName);
  632. cout << "Your name is: " << fullName;
  633.  
  634. // Type your full name: John Doe
  635. // Your name is: John Doe
  636. Adding Numbers and Strings
  637. WARNING!
  638.  
  639. C++ uses the + operator for both addition and concatenation.
  640.  
  641. Numbers are added. Strings are concatenated.
  642.  
  643. If you add two numbers, the result will be a number:
  644.  
  645. Example
  646. int x = 10;
  647. int y = 20;
  648. int z = x + y; // z will be 30 (an integer)
  649. If you add two strings, the result will be a string concatenation:
  650.  
  651. Example
  652. string x = "10";
  653. string y = "20";
  654. string z = x + y; // z will be 1020 (a string)
  655. If you try to add a number to a string, an error occurs:
  656.  
  657. Example
  658. string x = "10";
  659. int y = 20;
  660. string z = x + y;
  661. Omitting Namespace
  662. You might see some C++ programs that runs without the standard namespace library. The using namespace std line can be omitted and replaced with the std keyword, followed by the :: operator for string (and cout) objects:
  663.  
  664. Example
  665. #include <iostream>
  666. #include <string>
  667.  
  668. int main() {
  669. std::string greeting = "Hello";
  670. std::cout << greeting;
  671. return 0;
  672. }
  673. It is up to you if you want to include the standard namespace library or not.
  674. */
  675.  
  676. /*
  677. =====================================================================================================
  678. =====================================================================================================
  679.  
  680. _ _
  681. | | | |
  682. _ __ ___ __ _| |_| |__
  683. | '_ ` _ \ / _` | __| '_ \
  684. | | | | | | (_| | |_| | | |
  685. |_| |_| |_|\__,_|\__|_| |_|
  686.  
  687. =====================================================================================================
  688. */
  689.  
  690. /*
  691. C++ Math
  692. C++ has many functions that allows you to perform mathematical tasks on numbers.
  693.  
  694. Max and min
  695. The max(x,y) function can be used to find the highest value of x and y:
  696.  
  697. Example
  698. cout << max(5, 10);
  699. And the min(x,y) function can be used to find the lowest value of x and y:
  700.  
  701. Example
  702. cout << min(5, 10);
  703. C++ <cmath> Header
  704. Other functions, such as sqrt (square root), round (rounds a number) and log (natural logarithm), can be found in the <cmath> header file:
  705.  
  706. Example
  707. // Include the cmath library
  708. #include <cmath>
  709.  
  710. cout << sqrt(64);
  711. cout << round(2.6);
  712. cout << log(2);
  713. Other Math Functions
  714. A list of other popular Math functions (from the <cmath> library) can be found in the table below:
  715.  
  716. Function Description
  717. abs(x) Returns the absolute value of x
  718. acos(x) Returns the arccosine of x, in radians
  719. asin(x) Returns the arcsine of x, in radians
  720. atan(x) Returns the arctangent of x, in radians
  721. cbrt(x) Returns the cube root of x
  722. ceil(x) Returns the value of x rounded up to its nearest integer
  723. cos(x) Returns the cosine of x, in radians
  724. cosh(x) Returns the hyperbolic cosine of x, in radians
  725. exp(x) Returns the value of Ex
  726. expm1(x) Returns ex -1
  727. fabs(x) Returns the absolute value of a floating x
  728. fdim(x, y) Returns the positive difference between x and y
  729. floor(x) Returns the value of x rounded down to its nearest integer
  730. hypot(x, y) Returns sqrt(x2 +y2) without intermediate overflow or underflow
  731. fma(x, y, z) Returns x*y+z without losing precision
  732. fmax(x, y) Returns the highest value of a floating x and y
  733. fmin(x, y) Returns the lowest value of a floating x and y
  734. fmod(x, y) Returns the floating point remainder of x/y
  735. pow(x, y) Returns the value of x to the power of y
  736. sin(x) Returns the sine of x (x is in radians)
  737. sinh(x) Returns the hyperbolic sine of a double value
  738. tan(x) Returns the tangent of an angle
  739. tanh(x) Returns the hyperbolic tangent of a double value
  740.  
  741. */
  742.  
  743. /*
  744. =====================================================================================================
  745. =====================================================================================================
  746. ____ _
  747. | _ \ | |
  748. | |_) | ___ ___ | | ___ __ _ _ __ ___
  749. | _ < / _ \ / _ \| |/ _ \/ _` | '_ \/ __|
  750. | |_) | (_) | (_) | | __/ (_| | | | \__ \
  751. |____/ \___/ \___/|_|\___|\__,_|_| |_|___/
  752.  
  753.  
  754.  
  755. =====================================================================================================
  756.  
  757. */
  758.  
  759. /*
  760. C++ Booleans
  761. Very often, in programming, you will need a data type that can only have one of two values, like:
  762.  
  763. YES / NO
  764. ON / OFF
  765. TRUE / FALSE
  766. For this, C++ has a bool data type, which can take the values true (1) or false (0).
  767.  
  768. Boolean Values
  769. A boolean variable is declared with the bool keyword and can only take the values true or false:
  770.  
  771. Example
  772. bool isCodingFun = true;
  773. bool isFishTasty = false;
  774. cout << isCodingFun; // Outputs 1 (true)
  775. cout << isFishTasty; // Outputs 0 (false)
  776. From the example above, you can read that a true value returns 1, and false returns 0.
  777.  
  778. However, it is more common to return boolean values from boolean expressions (see below).
  779.  
  780. Boolean Expression
  781. A Boolean expression is a C++ expression that returns a boolean value: 1 (true) or 0 (false).
  782.  
  783. You can use a comparison operator, such as the greater than (>) operator to find out if an expression (or a variable) is true:
  784.  
  785. Example
  786. int x = 10;
  787. int y = 9;
  788. cout << (x > y); // returns 1 (true), because 10 is higher than 9
  789. Or even easier:
  790.  
  791. Example
  792. cout << (10 > 9); // returns 1 (true), because 10 is higher than 9
  793. In the examples below, we use the equal to (==) operator to evaluate an expression:
  794.  
  795. Example
  796. int x = 10;
  797. cout << (x == 10); // returns 1 (true), because the value of x is equal to 10
  798. Example
  799. cout << (10 == 15); // returns 0 (false), because 10 is not equal to 15
  800. Booleans are the basis for all C++ comparisons and conditions.
  801.  
  802. You will learn more about conditions (if...else) in the next chapter.
  803. */
  804.  
  805. /*
  806. =====================================================================================================
  807. =====================================================================================================
  808. _ __ __ _ _ __ __ _
  809. (_) / _| / / | | (_) / _| / / | |
  810. _ | |_ / / ___ | | ___ ___ _ | |_ / / ___ | | ___ ___
  811. | | | _| / / / _ \ | | / __| / _ \ | | | _| / / / _ \ | | / __| / _ \
  812. | | | | / / | __/ | | \__ \ | __/ | | | | / / | __/ | | \__ \ | __/
  813. |_| |_| /_/ \___| |_| |___/ \___| |_| |_| /_/ \___| |_| |___/ \___|
  814. =====================================================================================================
  815. */
  816.  
  817. /*
  818. C++ Conditions and If Statements
  819. C++ supports the usual logical conditions from mathematics:
  820.  
  821. Less than: a < b
  822. Less than or equal to: a <= b
  823. Greater than: a > b
  824. Greater than or equal to: a >= b
  825. Equal to a == b
  826. Not Equal to: a != b
  827. You can use these conditions to perform different actions for different decisions.
  828.  
  829. C++ has the following conditional statements:
  830.  
  831. Use if to specify a block of code to be executed, if a specified condition is true
  832. Use else to specify a block of code to be executed, if the same condition is false
  833. Use else if to specify a new condition to test, if the first condition is false
  834. Use switch to specify many alternative blocks of code to be executed
  835. The if Statement
  836. Use the if statement to specify a block of C++ code to be executed if a condition is true.
  837.  
  838. Syntax
  839. if (condition) {
  840. // block of code to be executed if the condition is true
  841. }
  842. Note that if is in lowercase letters. Uppercase letters (If or IF) will generate an error.
  843.  
  844. In the example below, we test two values to find out if 20 is greater than 18. If the condition is true, print some text:
  845.  
  846. Example
  847. if (20 > 18) {
  848. cout << "20 is greater than 18";
  849. }
  850. We can also test variables:
  851.  
  852. Example
  853. int x = 20;
  854. int y = 18;
  855. if (x > y) {
  856. cout << "x is greater than y";
  857. }
  858. Example explained
  859. In the example above we use two variables, x and y, to test whether x is greater than y (using the > operator). As x is 20, and y is 18, and we know that 20 is greater than 18, we print to the screen that "x is greater than y".
  860.  
  861.  
  862. The else Statement
  863. Use the else statement to specify a block of code to be executed if the condition is false.
  864.  
  865. Syntax
  866. if (condition) {
  867. // block of code to be executed if the condition is true
  868. } else {
  869. // block of code to be executed if the condition is false
  870. }
  871. Example
  872. int time = 20;
  873. if (time < 18) {
  874. cout << "Good day.";
  875. } else {
  876. cout << "Good evening.";
  877. }
  878. // Outputs "Good evening."
  879. Example explained
  880. In the example above, time (20) is greater than 18, so the condition is false. Because of this, we move on to the else condition and print to the screen "Good evening". If the time was less than 18, the program would print "Good day".
  881.  
  882. The else if Statement
  883. Use the else if statement to specify a new condition if the first condition is false.
  884.  
  885. Syntax
  886. if (condition1) {
  887. // block of code to be executed if condition1 is true
  888. } else if (condition2) {
  889. // block of code to be executed if the condition1 is false and condition2 is true
  890. } else {
  891. // block of code to be executed if the condition1 is false and condition2 is false
  892. }
  893. Example
  894. int time = 22;
  895. if (time < 10) {
  896. cout << "Good morning.";
  897. } else if (time < 20) {
  898. cout << "Good day.";
  899. } else {
  900. cout << "Good evening.";
  901. }
  902. // Outputs "Good evening."
  903. Example explained
  904. In the example above, time (22) is greater than 10, so the first condition is false. The next condition, in the else if statement, is also false, so we move on to the else condition since condition1 and condition2 is both false - and print to the screen "Good evening".
  905.  
  906. However, if the time was 14, our program would print "Good day."
  907.  
  908. Short Hand If...Else (Ternary Operator)
  909. There is also a short-hand if else, which is known as the ternary operator because it consists of three operands. It can be used to replace multiple lines of code with a single line. It is often used to replace simple if else statements:
  910.  
  911. Syntax
  912. variable = (condition) ? expressionTrue : expressionFalse;
  913. Instead of writing:
  914.  
  915. Example
  916. int time = 20;
  917. if (time < 18) {
  918. cout << "Good day.";
  919. } else {
  920. cout << "Good evening.";
  921. }
  922. You can simply write:
  923.  
  924. Example
  925. int time = 20;
  926. string result = (time < 18) ? "Good day." : "Good evening.";
  927. cout << result;
  928. */
  929.  
  930. if (10 == 10) {
  931. for (int i = 0; i > 5; i++) {
  932. cout << "my number is:" << i;
  933. }
  934. }
  935. else if (25 < 1.2) {
  936. int i = 33;
  937. cout << i << endl;
  938. }
  939. else {
  940. cout << "both if and else if are wrong false this code is now running" << endl;
  941. }
  942.  
  943. int time = 20;
  944. string result = (time < 18) ? "Good day." : "Good evening.";
  945. cout << result;
  946.  
  947. /*
  948. =====================================================================================================
  949. =====================================================================================================
  950. _ _ _ _ _ _
  951. (_) | | | | | | | | | |
  952. ___ __ __ _ | |_ ___ | |__ ___ | |_ __ _ | |_ ___ _ __ ___ ___ _ __ | |_ ___
  953. / __| \ \ /\ / / | | | __| / __| | '_ \ / __| | __| / _` | | __| / _ \ | '_ ` _ \ / _ \ | '_ \ | __| / __|
  954. \__ \ \ V V / | | | |_ | (__ | | | | \__ \ | |_ | (_| | | |_ | __/ | | | | | | | __/ | | | | | |_ \__ \
  955. |___/ \_/\_/ |_| \__| \___| |_| |_| |___/ \__| \__,_| \__| \___| |_| |_| |_| \___| |_| |_| \__| |___/
  956. =====================================================================================================
  957.  
  958. */
  959.  
  960. /*
  961. C++ Switch Statements
  962. Use the switch statement to select one of many code blocks to be executed.
  963.  
  964. Syntax
  965. switch(expression) {
  966. case x:
  967. // code block
  968. break;
  969. case y:
  970. // code block
  971. break;
  972. default:
  973. // code block
  974. }
  975. This is how it works:
  976.  
  977. The switch expression is evaluated once.
  978. The value of the expression is compared with the values of each case.
  979. If there is a match, the associated block of code is executed.
  980. The break and default keywords are optional, and will be described later in this chapter
  981. The example below uses the weekday number to calculate the weekday name:
  982.  
  983. Example
  984. int day = 4;
  985. switch (day) {
  986. case 1:
  987. cout << "Monday";
  988. break;
  989. case 2:
  990. cout << "Tuesday";
  991. break;
  992. case 3:
  993. cout << "Wednesday";
  994. break;
  995. case 4:
  996. cout << "Thursday";
  997. break;
  998. case 5:
  999. cout << "Friday";
  1000. break;
  1001. case 6:
  1002. cout << "Saturday";
  1003. break;
  1004. case 7:
  1005. cout << "Sunday";
  1006. break;
  1007. }
  1008. // Outputs "Thursday" (day 4)
  1009. The break Keyword
  1010. When C++ reaches a break keyword, it breaks out of the switch block.
  1011.  
  1012. This will stop the execution of more code and case testing inside the block.
  1013.  
  1014. When a match is found, and the job is done, it's time for a break. There is no need for more testing.
  1015.  
  1016. A break can save a lot of execution time because it "ignores" the execution of all the rest of the code in the switch block.
  1017.  
  1018.  
  1019. The default Keyword
  1020. The default keyword specifies some code to run if there is no case match:
  1021.  
  1022. Example
  1023. int day = 4;
  1024. switch (day) {
  1025. case 6:
  1026. cout << "Today is Saturday";
  1027. break;
  1028. case 7:
  1029. cout << "Today is Sunday";
  1030. break;
  1031. default:
  1032. cout << "Looking forward to the Weekend";
  1033. }
  1034. // Outputs "Looking forward to the Weekend"
  1035. Note: The default keyword must be used as the last statement in the switch, and it does not need a break.
  1036. */
  1037.  
  1038. /*
  1039. =====================================================================================================
  1040. =====================================================================================================
  1041.  
  1042. _ _ _ _
  1043. | | (_) | | | |
  1044. __ __ | |__ _ | | ___ | | ___ ___ _ __ ___
  1045. \ \ /\ / / | '_ \ | | | | / _ \ | | / _ \ / _ \ | '_ \ / __|
  1046. \ V V / | | | | | | | | | __/ | | | (_) | | (_) | | |_) | \__ \
  1047. \_/\_/ |_| |_| |_| |_| \___| |_| \___/ \___/ | .__/ |___/
  1048. | |
  1049. |_|
  1050. =====================================================================================================
  1051. */
  1052. /*
  1053. C++ Loops
  1054. Loops can execute a block of code as long as a specified condition is reached.
  1055.  
  1056. Loops are handy because they save time, reduce errors, and they make code more readable.
  1057.  
  1058. C++ While Loop
  1059. The while loop loops through a block of code as long as a specified condition is true:
  1060.  
  1061. Syntax
  1062. while (condition) {
  1063. // code block to be executed
  1064. }
  1065. In the example below, the code in the loop will run, over and over again, as long as a variable (i) is less than 5:
  1066.  
  1067. Example
  1068. int i = 0;
  1069. while (i < 5) {
  1070. cout << i << "\n";
  1071. i++;
  1072. }
  1073. Note: Do not forget to increase the variable used in the condition, otherwise the loop will never end!
  1074.  
  1075. The Do/While Loop
  1076. The do/while loop is a variant of the while loop. This loop will execute the code block once, before checking if the condition is true, then it will repeat the loop as long as the condition is true.
  1077.  
  1078. Syntax
  1079. do {
  1080. // code block to be executed
  1081. }
  1082. while (condition);
  1083. The example below uses a do/while loop. The loop will always be executed at least once, even if the condition is false, because the code block is executed before the condition is tested:
  1084.  
  1085. Example
  1086. int i = 0;
  1087. do {
  1088. cout << i << "\n";
  1089. i++;
  1090. }
  1091. while (i < 5);
  1092. Do not forget to increase the variable used in the condition, otherwise the loop will never end!
  1093. */
  1094. int nottrue = 0;
  1095. while (nottrue < 35) {
  1096. nottrue++;
  1097. cout << nottrue<<endl;
  1098. }
  1099. nottrue = 0;
  1100. do {
  1101. cout << "this number increments to ten"<< endl;
  1102. nottrue++;
  1103.  
  1104. } while (nottrue <= 10);
  1105.  
  1106. /*
  1107. =====================================================================================================
  1108. =====================================================================================================
  1109. ______ _
  1110. | ____| | |
  1111. | |__ ___ _ __ | | ___ ___ _ __ ___
  1112. | __| / _ \ | '__| | | / _ \ / _ \ | '_ \ / __|
  1113. | | | (_) | | | | | | (_) | | (_) | | |_) | \__ \
  1114. |_| \___/ |_| |_| \___/ \___/ | .__/ |___/
  1115. | |
  1116. |_|
  1117. =====================================================================================================
  1118. */
  1119.  
  1120. /*
  1121. C++ For Loop
  1122. When you know exactly how many times you want to loop through a block of code, use the for loop instead of a while loop:
  1123.  
  1124. Syntax
  1125. for (statement 1; statement 2; statement 3) {
  1126. // code block to be executed
  1127. }
  1128. Statement 1 is executed (one time) before the execution of the code block.
  1129.  
  1130. Statement 2 defines the condition for executing the code block.
  1131.  
  1132. Statement 3 is executed (every time) after the code block has been executed.
  1133.  
  1134. The example below will print the numbers 0 to 4:
  1135.  
  1136. Example
  1137. for (int i = 0; i < 5; i++) {
  1138. cout << i << "\n";
  1139. }
  1140. Example explained
  1141. Statement 1 sets a variable before the loop starts (int i = 0).
  1142.  
  1143. Statement 2 defines the condition for the loop to run (i must be less than 5). If the condition is true, the loop will start over again, if it is false, the loop will end.
  1144.  
  1145. Statement 3 increases a value (i++) each time the code block in the loop has been executed.
  1146.  
  1147. Another Example
  1148. This example will only print even values between 0 and 10:
  1149.  
  1150. Example
  1151. for (int i = 0; i <= 10; i = i + 2) {
  1152. cout << i << "\n";
  1153. }
  1154. */
  1155. /*
  1156. =====================================================================================================
  1157. =====================================================================================================
  1158. ____ _ __ _____ _ _
  1159. | _ \ | | / / / ____| | | (_)
  1160. | |_) | _ __ ___ __ _ | | __ / / | | ___ _ __ | |_ _ _ __ _ _ ___
  1161. | _ < | '__| / _ \ / _` | | |/ / / / | | / _ \ | '_ \ | __| | | | '_ \ | | | | / _ \
  1162. | |_) | | | | __/ | (_| | | < / / | |____ | (_) | | | | | | |_ | | | | | | | |_| | | __/
  1163. |____/ |_| \___| \__,_| |_|\_\ /_/ \_____| \___/ |_| |_| \__| |_| |_| |_| \__,_| \___|
  1164. =====================================================================================================
  1165. */
  1166.  
  1167. /*
  1168. C++ Break
  1169. You have already seen the break statement used in an earlier chapter of this tutorial. It was used to "jump out" of a switch statement.
  1170.  
  1171. The break statement can also be used to jump out of a loop.
  1172.  
  1173. This example jumps out of the loop when i is equal to 4:
  1174.  
  1175. Example
  1176. for (int i = 0; i < 10; i++) {
  1177. if (i == 4) {
  1178. break;
  1179. }
  1180. cout << i << "\n";
  1181. }
  1182. C++ Continue
  1183. The continue statement breaks one iteration (in the loop), if a specified condition occurs, and continues with the next iteration in the loop.
  1184.  
  1185. This example skips the value of 4:
  1186.  
  1187. Example
  1188. for (int i = 0; i < 10; i++) {
  1189. if (i == 4) {
  1190. continue;
  1191. }
  1192. cout << i << "\n";
  1193. */
  1194. /*
  1195. =====================================================================================================
  1196. =====================================================================================================
  1197. /\
  1198. / \ _ __ _ __ __ _ _ _
  1199. / /\ \ | '__| | '__| / _` | | | | |
  1200. / ____ \ | | | | | (_| | | |_| |
  1201. /_/ \_\ |_| |_| \__,_| \__, |
  1202. __/ |
  1203. |___/
  1204. =====================================================================================================
  1205. */
  1206. /*
  1207. C++ Arrays
  1208. Arrays are used to store multiple values in a single variable, instead of declaring separate variables for each value.
  1209.  
  1210. To declare an array, define the variable type, specify the name of the array followed by square brackets and specify the number of elements it should store:
  1211.  
  1212. string cars[4];
  1213. We have now declared a variable that holds an array of four strings. To insert values to it, we can use an array literal - place the values in a comma-separated list, inside curly braces:
  1214.  
  1215. string cars[4] = {"Volvo", "BMW", "Ford", "Mazda"};
  1216. To create an array of three integers, you could write:
  1217.  
  1218. int myNum[3] = {10, 20, 30};
  1219. Access the Elements of an Array
  1220. You access an array element by referring to the index number.
  1221.  
  1222. This statement accesses the value of the first element in cars:
  1223.  
  1224. Example
  1225. string cars[4] = {"Volvo", "BMW", "Ford", "Mazda"};
  1226. cout << cars[0];
  1227. // Outputs Volvo
  1228. Note: Array indexes start with 0: [0] is the first element. [1] is the second element, etc.
  1229.  
  1230. Change an Array Element
  1231. To change the value of a specific element, refer to the index number:
  1232.  
  1233. Example
  1234. cars[0] = "Opel";
  1235. Example
  1236. string cars[4] = {"Volvo", "BMW", "Ford", "Mazda"};
  1237. cars[0] = "Opel";
  1238. cout << cars[0];
  1239. // Now outputs Opel instead of Volvo
  1240. Loop Through an Array
  1241. You can loop through the array elements with the for loop.
  1242.  
  1243. The following example outputs all elements in the cars array:
  1244.  
  1245. Example
  1246. string cars[4] = {"Volvo", "BMW", "Ford", "Mazda"};
  1247. for(int i = 0; i < 4; i++) {
  1248. cout << cars[i] << "\n";
  1249. }
  1250. Omit Array Size
  1251. You don't have to specify the size of the array. But if you don't, it will only be as big as the elements that are inserted into it:
  1252.  
  1253. string cars[] = {"Volvo", "BMW", "Ford"}; // size of array is always 3
  1254. This is completely fine. However, the problem arise if you want extra space for future elements. Then you have to overwrite the existing values:
  1255.  
  1256. string cars[] = {"Volvo", "BMW", "Ford"};
  1257. string cars[] = {"Volvo", "BMW", "Ford", "Mazda", "Tesla"};
  1258. If you specify the size however, the array will reserve the extra space:
  1259.  
  1260. string cars[5] = {"Volvo", "BMW", "Ford"}; // size of array is 5, even though it's only three elements inside it
  1261. Now you can add a fourth and fifth element without overwriting the others:
  1262.  
  1263. string cars[3] = {"Mazda"};
  1264. string cars[4] = {"Tesla"};
  1265. Omit Elements on Declaration
  1266. It is also possible to declare an array without specifying the elements on declaration, and add them later:
  1267.  
  1268. string cars[5];
  1269. cars[0] = {"Volvo"};
  1270. cars[1] = {"BMW"};
  1271. ...
  1272. */
  1273.  
  1274. /*
  1275. =====================================================================================================
  1276. =====================================================================================================
  1277. __
  1278. / _|
  1279. _ __ ___ | |_ ___ _ __ ___ _ __ ___ ___ ___
  1280. | '__| / _ \ | _| / _ \ | '__| / _ \ | '_ \ / __| / _ \ / __|
  1281. | | | __/ | | | __/ | | | __/ | | | | | (__ | __/ \__ \
  1282. |_| \___| |_| \___| |_| \___| |_| |_| \___| \___| |___/
  1283.  
  1284. =====================================================================================================
  1285. */
  1286.  
  1287. /*
  1288. C++ References
  1289. Creating References
  1290. A reference variable is a "reference" to an existing variable, and it is created with the & operator:
  1291.  
  1292. string food = "Pizza"; // food variable
  1293. string &meal = food; // reference to food
  1294. Now, we can use either the variable name food or the reference name meal to refer to the food variable:
  1295.  
  1296. Example
  1297. string food = "Pizza";
  1298. string &meal = food;
  1299.  
  1300. cout << food << "\n"; // Outputs Pizza
  1301. cout << meal << "\n"; // Outputs Pizza
  1302. Memory Address
  1303. In the example above, the & operator was used to create a reference variable. But it can also be used to get the memory address of a variable, which is the location of where the variable is stored on the computer.
  1304.  
  1305. When a variable is created in C++, a memory address is assigned to the variable. And when we assign a value to the variable, it is stored in this memory address.
  1306.  
  1307. To access it, use the & operator, and the result will represent where the variable is stored:
  1308.  
  1309. Example
  1310. string food = "Pizza";
  1311.  
  1312. cout << &food; // Outputs 0x6dfed4
  1313. Note: The memory address is in hexadecimal form (0x..). Note that you may not get the same result in your program.
  1314.  
  1315. And why is it useful to know the memory address?
  1316. References and Pointers (which you will learn about in the next chapter) are important in C++, because they give you the ability to manipulate the data in the computer's memory - which can reduce the code and improve the perfomance.
  1317.  
  1318. These two features are one of the things that make C++ stand out from other programming languages, like Python and Java.
  1319. */
  1320.  
  1321.  
  1322.  
  1323.  
  1324.  
  1325. /*
  1326. =====================================================================================================
  1327. =====================================================================================================
  1328. _____ _ _
  1329. | __ \ (_) | |
  1330. | |__) | ___ _ _ __ | |_ ___ _ __ ___
  1331. | ___/ / _ \ | | | '_ \ | __| / _ \ | '__| / __|
  1332. | | | (_) | | | | | | | | |_ | __/ | | \__ \
  1333. |_| \___/ |_| |_| |_| \__| \___| |_| |___/
  1334. =====================================================================================================
  1335. */
  1336. /*
  1337. C++ Pointers
  1338. Creating Pointers
  1339. You learned from the previous chapter, that we can get the memory address of a variable by using the & operator:
  1340.  
  1341. Example
  1342. string food = "Pizza"; // A food variable of type string
  1343.  
  1344. cout << food; // Outputs the value of food (Pizza)
  1345. cout << &food; // Outputs the memory address of food (0x6dfed4)
  1346. A pointer however, is a variable that stores the memory address as its value.
  1347.  
  1348. A pointer variable points to a data type (like int or string) of the same type, and is created with the * operator. The address of the variable you're working with is assigned to the pointer:
  1349.  
  1350. Example
  1351. string food = "Pizza"; // A food variable of type string
  1352. string* ptr = &food; // A pointer variable, with the name ptr, that stores the address of food
  1353.  
  1354. // Output the value of food (Pizza)
  1355. cout << food << "\n";
  1356.  
  1357. // Output the memory address of food (0x6dfed4)
  1358. cout << &food << "\n";
  1359.  
  1360. // Output the memory address of food with the pointer (0x6dfed4)
  1361. cout << ptr << "\n";
  1362. Example explained
  1363. Create a pointer variable with the name ptr, that points to a string variable, by using the asterisk sign * (string* ptr). Note that the type of the pointer has to match the type of the variable you're working with.
  1364.  
  1365. Use the & operator to store the memory address of the variable called food, and assign it to the pointer.
  1366.  
  1367. Now, ptr holds the value of food's memory address.
  1368.  
  1369. Tip: There are three ways to declare pointer variables, but the first way is preferred:
  1370.  
  1371. string* mystring; // Preferred
  1372. string *mystring;
  1373. string * mystring;
  1374. Get Memory Address and Value
  1375. In the example above, we used the pointer variable to get the memory address of a variable (used together with the & reference operator). However, you can also use the pointer to get the value of the variable, by using the * operator (the dereference operator):
  1376.  
  1377. Example
  1378. string food = "Pizza"; // Variable declaration
  1379. string* ptr = &food; // Pointer declaration
  1380.  
  1381. // Reference: Output the memory address of food with the pointer (0x6dfed4)
  1382. cout << ptr << "\n";
  1383.  
  1384. // Dereference: Output the value of food with the pointer (Pizza)
  1385. cout << *ptr << "\n";
  1386. Note that the * sign can be confusing here, as it does two different things in our code:
  1387.  
  1388. When used in declaration (string* ptr), it creates a pointer variable.
  1389. When not used in declaration, it act as a dereference operator.
  1390. Modify the Pointer Value
  1391. You can also change the pointer's value. But note that this will also change the value of the original variable:
  1392.  
  1393. Example
  1394. string food = "Pizza";
  1395. string* ptr = &food;
  1396.  
  1397. // Output the value of food (Pizza)
  1398. cout << food << "\n";
  1399.  
  1400. // Output the memory address of food (0x6dfed4)
  1401. cout << &food << "\n";
  1402.  
  1403. // Access the memory address of food and output its value (Pizza)
  1404. cout << *ptr << "\n";
  1405.  
  1406. // Change the value of the pointer
  1407. *ptr = "Hamburger";
  1408.  
  1409. // Output the new value of the pointer (Hamburger)
  1410. cout << *ptr << "\n";
  1411.  
  1412. // Output the new value of the food variable (Hamburger)
  1413. cout << food << "\n";
  1414. */
  1415.  
  1416. return 0;
  1417. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement