Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*By Joseph.S Aspiring Engineer/Programmer
- __ __ _ _
- \ \ / / | | | |
- \ \ /\ / / ___ | | ___ ___ _ __ ___ ___ | |_ ___ _ __ ___ _ _
- \ \/ \/ / / _ \ | | / __| / _ \ | '_ ` _ \ / _ \ | __| / _ \ | '_ ` _ \ | | | |
- \ /\ / | __/ | | | (__ | (_) | | | | | | | | __/ | |_ | (_) | | | | | | | | |_| |
- \/ \/ \___| |_| \___| \___/ |_| |_| |_| \___| \__| \___/ |_| |_| |_| \__, |
- __/ |
- |___/
- _____ _ _ _
- / ____| _ _ | | (_) | |
- | | _| |_ _| |_ | | _ | |__ _ __ __ _ _ __ _ _
- | | |_ _| |_ _| | | | | | '_ \ | '__| / _` | | '__| | | | |
- | |____ |_| |_| | |____ | | | |_) | | | | (_| | | | | |_| |
- \_____| |______| |_| |_.__/ |_| \__,_| |_| \__, |
- __/ |
- |___/
- =====================================================================================================
- =====================================================================================================
- */
- /* _ _
- (_) | |
- _ _ __ | |_ _ __ ___
- | | '_ \| __| '__/ _ \
- | | | | | |_| | | (_) |
- |_|_| |_|\__|_| \___/
- ====================================================================================================
- */
- /*What is C++?
- C++ is a cross-platformed language that can be used to create sophisticated high-performance applications.
- C++ was developed by Bjarne Stroustrup at Bell labs in 1979, as an extension to the C language.
- C++ gives programmers a high level of control over system resources and memory.
- The language was updated 3 major times in 2011, 2014, and 2017 to C++11, C++14, and C++17.
- Why Use C++?
- C++ is one of the world's most popular programming languages.
- C++ can be found in today's operating systems, Graphical User Interfaces, and embedded systems.
- C++ is an object oriented language which gives a clear structure to programs and allows code to be reused, lowering development costs.
- C++ is portable and can be used to develop applications that can be adapted to multiple platforms.
- C++ is fun and easy to learn!
- As C++ is close to C# and Java, it makes it easy for programmers to switch to C++ or vice versa*/
- /*
- =====================================================================================================
- =====================================================================================================
- _____ _ _ _ _____ _ _ _
- / ____| | | | | (_) / ____| | | | | |
- | | __ ___| |_| |_ _ _ __ __ _ | (___ | |_ __ _ _ __| |_ ___ __| |
- | | |_ |/ _ \ __| __| | '_ \ / _` | \___ \| __/ _` | '__| __/ _ \/ _` |
- | |__| | __/ |_| |_| | | | | (_| | ____) | || (_| | | | || __/ (_| |
- \_____|\___|\__|\__|_|_| |_|\__, | |_____/ \__\__,_|_| \__\___|\__,_|
- __/ |
- |___/
- =====================================================================================================
- */
- /*
- C++ Get Started
- To start using C++, you need two things:
- A text editor, like Notepad, to write C++ code
- A compiler, like GCC, to translate the C++ code into a language that the computer will understand
- There are many text editors and compilers to choose from. In this tutorial, we will use an IDE (see below).
- C++ Install IDE
- An IDE (Integrated Development Environment) is used to edit AND compile the code.
- 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.
- Note: Web-based IDE's can work as well, but functionality is limited.
- We will use Code::Blocks in our tutorial, which we believe is a good place to start.
- 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.
- C++ Quickstart
- Let's create our first C++ file.
- Open Codeblocks and go to File > New > Empty File.
- Write the following C++ code and save the file as myfirstprogram.cpp (File > Save File as):
- myfirstprogram.cpp
- #include <iostream>
- using namespace std;
- int main() {
- cout << "Hello World!";
- return 0;
- }
- 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.
- In Codeblocks, it should look like this:
- Then, go to Build > Build and Run to run (execute) the program. The result will look something to this:
- Hello World!
- Process returned 0 (0x0) execution time : 0.011 s
- Press any key to continue.
- Congratulations! You have now written and executed your first C++ program.
- */
- /*
- =====================================================================================================
- =====================================================================================================
- _____ _
- / ____| | |
- | (___ _ _ _ __ | |_ __ ___ __
- \___ \| | | | '_ \| __/ _` \ \/ /
- ____) | |_| | | | | || (_| |> <
- |_____/ \__, |_| |_|\__\__,_/_/\_\
- __/ |
- |___/
- =====================================================================================================
- */
- /*
- C++ Syntax
- Let's break up the following code to understand it better:
- Example
- #include <iostream>
- using namespace std;
- int main() {
- cout << "Hello World!";
- return 0;
- }
- Example explained
- 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.
- Line 2: using namespace std means that we can use names for objects and variables from the standard library.
- 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.
- Line 3: A blank line. C++ ignores white space.
- 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.
- Line 5: cout (pronounced "see-out") is an object used to output/print text. In our example it will output "Hello World".
- Note: Every C++ statement ends with a semicolon ;.
- Note: The body of int main() could also been written as:
- int main () { cout << "Hello World! "; return 0; }
- Remember: The compiler ignores white spaces. However, multiple lines makes the code more readable.
- Line 6: return 0 ends the main function.
- Omitting Namespace
- 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:
- Example
- #include <iostream>
- int main() {
- std::cout << "Hello World!";
- return 0;
- }
- */
- /*
- =====================================================================================================
- =====================================================================================================
- ____ _ _ _______ _ _ _______ _ __
- / __ \ | | | | / / __ \ (_) | | |__ __| | |\ \
- | | | |_ _| |_ _ __ _ _| |_ | || |__) | __ _ _ __ | |_ | | _____ _| |_| |
- | | | | | | | __| '_ \| | | | __| | || ___/ '__| | '_ \| __| | |/ _ \ \/ / __| |
- | |__| | |_| | |_| |_) | |_| | |_ | || | | | | | | | | |_ | | __/> <| |_| |
- \____/ \__,_|\__| .__/ \__,_|\__| | ||_| |_| |_|_| |_|\__| |_|\___/_/\_\\__| |
- | | \_\ /_/
- |_|
- =====================================================================================================
- */
- /* #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.*/
- #include <iostream>
- using namespace std;
- // 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
- int add(int a, int b) {
- return a + b;
- };
- int main() {
- int num1;
- int num2;
- cout << "what is Variable a:";
- cin >> num1;
- cout << "what is Variable b:";
- cin >> num2;
- cout << add(num1, num2) <<endl;
- /*You can add as many cout objects as you want. However,
- note that it does not insert a new line at the end of the output:*/
- cout << "Hello im a string \n";
- // You can Use \n to break a line and to make a line space use it twice \n\n
- cout << "Hello World! \n\n";
- // or you can use a "end + LowerCase L" = endl
- cout << " there is a free line that is empty above me" << endl;
- //Both \n and endl are used to break lines. However, \n is used more often and is the preferred way.
- /*
- =====================================================================================================
- =====================================================================================================
- _____ _
- / ____| | |
- | | ___ _ __ ___ _ __ ___ ___ _ __ | |_ ___
- | | / _ \| '_ ` _ \| '_ ` _ \ / _ \ '_ \| __/ __|
- | |___| (_) | | | | | | | | | | | __/ | | | |_\__ \
- \_____\___/|_| |_| |_|_| |_| |_|\___|_| |_|\__|___/
- =====================================================================================================
- */
- /*
- single line Comments are written Using "// folloew by your comment"
- Multi-Line Comments are Made Using to slashes and 2 asterisks in the middle
- followed with your comment in the center
- /*your Comment Goes in here*/
- /*Using commenets to give reminders to you or other programmers so
- you can know what something does and figure it out l8ter*/
- /*
- =====================================================================================================
- =====================================================================================================
- __ __ _ _ _
- \ \ / / (_) | | | |
- \ \ / /_ _ _ __ _ __ _| |__ | | ___ ___
- \ \/ / _` | '__| |/ _` | '_ \| |/ _ \/ __|
- \ / (_| | | | | (_| | |_) | | __/\__ \
- \/ \__,_|_| |_|\__,_|_.__/|_|\___||___/
- =====================================================================================================
- */
- /*
- C++ Variables
- Variables are containers for storing data values.
- In C++, there are different types of variables (defined with different keywords), for example:
- int - stores integers (whole numbers), without decimals, such as 123 or -123
- double - stores floating point numbers, with decimals, such as 19.99 or -19.99
- char - stores single characters, such as 'a' or 'B'. Char values are surrounded by single quotes
- string - stores text, such as "Hello World". String values are surrounded by double quotes
- bool - stores values with two states: true or false
- C++ Identifiers
- All C++ variables must be identified with unique names.
- These unique names are called identifiers.
- Identifiers can be short names (like x and y) or more descriptive names (age, sum, totalVolume).
- Note: It is recommended to use descriptive names in order to create understandable and maintainable code.
- The general rules for constructing names for variables (unique identifiers) are:
- Names can contain letters, digits and underscores
- Names must begin with a letter or an underscore (_)
- Names are case sensitive (myVar and myvar are different variables)
- Names cannot contain whitespaces or special characters like !, #, %, etc.
- Reserved words (like C++ keywords, such as int) cannot be used as names
- Declaring (Creating) Variables
- To create a variable, you must specify the type and assign it a value:
- */
- int Name1 = 12;
- string Name2 = "A Value";
- double Name3 = 12.45;
- char Name4 = 'c'; char Name5 = 'h'; char Name6 = 'a'; char Name7 = 'r';
- bool Name8 = true; bool Name9 = false;
- cout << Name1 << endl << Name2 << endl << Name3 << endl << Name4 << Name5 << Name6 << Name7 << endl << Name8 << endl << Name9 << endl; ;
- // ps you can also declare variables beroe asiging a value
- string NovaluetillDeclared;
- NovaluetillDeclared = "i just assigned the value";
- //you can also change values by assigning a difeenet value using the naming conventions
- int value = 0;
- cout << "value:" << value<< endl;
- value = 1;
- cout << "value:"<<value<<endl;
- //if you need a value that is constant and unchanging , then delcare a variable with "const" in front of it
- const int value1 = 0;
- cout << "value:" << value1 << endl;
- value = 1;
- cout << "value:" << value1 << endl;
- // you can easily add,subtract,multiply,divide with variables lets practice with addition
- int x = 32;
- int y = 8;
- int xy = x + y;
- cout <<"x="<< x <<endl<< "y="<<y<<endl<<"x+y="<< xy << endl;
- /*
- =====================================================================================================
- =====================================================================================================
- _ _
- (_) | |
- _ _ ___ ___ _ __ _ _ __ _ __ _ _ | |_
- | | | | / __| / _ \ | '__| | | | '_ \ | '_ \ | | | | | __|
- | |_| | \__ \ | __/ | | | | | | | | | |_) | | |_| | | |_
- \__,_| |___/ \___| |_| |_| |_| |_| | .__/ \__,_| \__|
- | |
- |_|
- =====================================================================================================
- */
- /*
- C++ User Input
- You have already learned that cout is used to output (print) values. Now we will use cin to get user input.
- cin is a predefined variable that reads data from the keyboard with the extraction operator (>>).
- In the following example, the user can input a number, which is stored in the variable x. Then we print the value of x:
- */
- int inputvalue;
- cout << "type a number:";// Type a number and press enter
- cin >> inputvalue;// Get user input from the keyboard
- cout << "Your number is: " << inputvalue << endl;// Display the input value
- /*
- =====================================================================================================
- =====================================================================================================
- _ _ _
- | | | | | |
- __| | __ _| |_ __ _ | |_ _ _ _ __ ___ ___
- / _` |/ _` | __/ _` | | __| | | | '_ \ / _ \/ __|
- | (_| | (_| | || (_| | | |_| |_| | |_) | __/\__ \
- \__,_|\__,_|\__\__,_| \__|\__, | .__/ \___||___/
- __/ | |
- |___/|_|
- =====================================================================================================
- */
- /*
- C++ Data Types
- As explained in the Variables chapter, a variable in C++ must be a specified data type:
- Example
- int myNum = 5; // Integer (whole number)
- float myFloatNum = 5.99; // Floating point number
- double myDoubleNum = 9.98; // Floating point number
- char myLetter = 'D'; // Character
- bool myBoolean = true; // Boolean
- string myText = "Hello"; // String
- Basic Data Types
- The data type specifies the size and type of information the variable will store:
- Data Type Size Description
- int 4 bytes Stores whole numbers, without decimals
- float 4 bytes Stores fractional numbers, containing one or more decimals. Sufficient for storing 7 decimal digits
- double 8 bytes Stores fractional numbers, containing one or more decimals. Sufficient for storing 15 decimal digits
- boolean 1 byte Stores true or false values
- char 1 byte Stores a single character/letter/number, or ASCII values
- 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.
- int
- int myNum = 1000;
- cout << myNum;
- float
- float myNum = 5.75;
- cout << myNum;
- double
- double myNum = 19.99;
- cout << myNum;
- float vs. double
- 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.
- Scientific Numbers
- A floating point number can also be a scientific number with an "e" to indicate the power of 10:
- Example
- float f1 = 35e3;
- double d1 = 12E4;
- cout << f1;
- cout << d1;
- Booleans
- 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.
- Example
- bool isCodingFun = true;
- bool isFishTasty = false;
- cout << isCodingFun; // Outputs 1 (true)
- cout << isFishTasty; // Outputs 0 (false)
- Boolean values are mostly used for conditional testing, which you will learn more about in a later chapter.
- Characters
- The char data type is used to store a single character. The character must be surrounded by single quotes, like 'A' or 'c':
- Example
- char myGrade = 'B';
- cout << myGrade;
- Alternatively, you can use ASCII values to display certain characters:
- Example
- char a = 65, b = 66, c = 67;
- cout << a;
- cout << b;
- cout << c;
- Tip: A list of all ASCII values can be found in our ASCII Table Reference.
- Strings
- 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:
- Example
- string greeting = "Hello";
- cout << greeting;
- */
- /*
- =====================================================================================================
- =====================================================================================================
- ____ _
- / __ \ | |
- | | | |_ __ ___ _ __ __ _| |_ ___ _ __ ___
- | | | | '_ \ / _ \ '__/ _` | __/ _ \| '__/ __|
- | |__| | |_) | __/ | | (_| | || (_) | | \__ \
- \____/| .__/ \___|_| \__,_|\__\___/|_| |___/
- | |
- |_|
- =====================================================================================================
- */
- /*
- C++ Operators
- Operators are used to perform operations on variables and values.
- In the example below, we use the + operator to add together two values:
- Example
- int x = 100 + 50;
- 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:
- Example
- int sum1 = 100 + 50; // 150 (100 + 50)
- int sum2 = sum1 + 250; // 400 (150 + 250)
- int sum3 = sum2 + sum2; // 800 (400 + 400)
- C++ divides the operators into the following groups:
- Arithmetic operators
- Assignment operators
- Comparison operators
- Logical operators
- Bitwise operators
- Arithmetic Operators
- Arithmetic operators are used to perform common mathematical operations.
- Operator Name Description Example
- + Addition Adds together two values x + y
- - Subtraction Subtracts one value from another x - y
- * Multiplication Multiplies two values x * y
- / Division Divides one value from another x / y
- % Modulus Returns the division remainder x % y
- ++ Increment Increases the value of a variable by 1 ++x
- -- Decrement Decreases the value of a variable by 1 --x
- C++ Assignment Operators
- Assignment operators are used to assign values to variables.
- In the example below, we use the assignment operator (=) to assign the value 10 to a variable called x:
- Example
- int x = 10;
- The addition assignment operator (+=) adds a value to a variable:
- Example
- int x = 10;
- x += 5;
- A list of all assignment operators:
- Operator Example Same As
- = x = 5 x = 5
- += x += 3 x = x + 3
- -= x -= 3 x = x - 3
- *= x *= 3 x = x * 3
- /= x /= 3 x = x / 3
- %= x %= 3 x = x % 3
- &= x &= 3 x = x & 3
- |= x |= 3 x = x | 3
- ^= x ^= 3 x = x ^ 3
- >>= x >>= 3 x = x >> 3
- <<= x <<= 3 x = x << 3
- C++ Comparison Operators
- Comparison operators are used to compare two values.
- 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.
- Operator Name Example Try it
- == Equal to x == y
- != Not equal x != y
- > Greater than x > y
- < Less than x < y
- >= Greater than or equal to x >= y
- <= Less than or equal to x <= y
- */
- /*
- =====================================================================================================
- =====================================================================================================
- _____ _ _
- / ____| | (_)
- | (___ | |_ _ __ _ _ __ __ _ ___
- \___ \| __| '__| | '_ \ / _` / __|
- ____) | |_| | | | | | | (_| \__ \
- |_____/ \__|_| |_|_| |_|\__, |___/
- __/ |
- |___/
- =====================================================================================================
- */
- /*
- C++ Strings
- Strings are used for storing text.
- A string variable contains a collection of characters surrounded by double quotes:
- Example
- Create a variable of type string and assign it a value:
- string greeting = "Hello";
- To use strings, you must include an additional header file in the source code, the <string> library:
- Example
- // Include the string library
- #include <string>
- // Create a string variable
- string greeting = "Hello";
- String Concatenation
- The + operator can be used between strings to add them together to make a new string. This is called concatenation:
- Example
- string firstName = "John ";
- string lastName = "Doe";
- string fullName = firstName + lastName;
- cout << fullName;
- Note that we added a space after firstName to create a space between John and Doe on output.
- String Length
- 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:
- Example
- string txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
- cout << "The length of the txt string is: " << txt.length();
- Access Strings
- You can access the characters in a string by referring to its index number inside square brackets [].
- This example prints the first character in myString:
- Example
- string myString = "Hello";
- cout << myString[0];
- // Outputs H
- Note: String indexes start with 0: [0] is the first character. [1] is the second character, etc.
- This example prints the second character in myString:
- Example
- string myString = "Hello";
- cout << myString[1];
- // Outputs e
- Change String Characters
- To change the value of a specific character in a string, refer to the index number, and use single quotes:
- Example
- string myString = "Hello";
- myString[0] = 'J';
- cout << myString;
- // Outputs Jello instead of Hello
- User Input Strings
- It is possible to use the extraction operator >> on cin to display a string entered by a user:
- Example
- string firstName;
- cout << "Type your first name: ";
- cin >> firstName; // get user input from the keyboard
- cout << "Your name is: " << firstName;
- // Type your first name: John
- // Your name is: John
- 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):
- Example
- string fullName;
- cout << "Type your full name: ";
- cin >> fullName;
- cout << "Your name is: " << fullName;
- // Type your full name: John Doe
- // Your name is: John
- From the example above, you would expect the program to print "John Doe", but it only prints "John".
- 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:
- Example
- string fullName;
- cout << "Type your full name: ";
- getline (cin, fullName);
- cout << "Your name is: " << fullName;
- // Type your full name: John Doe
- // Your name is: John Doe
- Adding Numbers and Strings
- WARNING!
- C++ uses the + operator for both addition and concatenation.
- Numbers are added. Strings are concatenated.
- If you add two numbers, the result will be a number:
- Example
- int x = 10;
- int y = 20;
- int z = x + y; // z will be 30 (an integer)
- If you add two strings, the result will be a string concatenation:
- Example
- string x = "10";
- string y = "20";
- string z = x + y; // z will be 1020 (a string)
- If you try to add a number to a string, an error occurs:
- Example
- string x = "10";
- int y = 20;
- string z = x + y;
- Omitting Namespace
- 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:
- Example
- #include <iostream>
- #include <string>
- int main() {
- std::string greeting = "Hello";
- std::cout << greeting;
- return 0;
- }
- It is up to you if you want to include the standard namespace library or not.
- */
- /*
- =====================================================================================================
- =====================================================================================================
- _ _
- | | | |
- _ __ ___ __ _| |_| |__
- | '_ ` _ \ / _` | __| '_ \
- | | | | | | (_| | |_| | | |
- |_| |_| |_|\__,_|\__|_| |_|
- =====================================================================================================
- */
- /*
- C++ Math
- C++ has many functions that allows you to perform mathematical tasks on numbers.
- Max and min
- The max(x,y) function can be used to find the highest value of x and y:
- Example
- cout << max(5, 10);
- And the min(x,y) function can be used to find the lowest value of x and y:
- Example
- cout << min(5, 10);
- C++ <cmath> Header
- Other functions, such as sqrt (square root), round (rounds a number) and log (natural logarithm), can be found in the <cmath> header file:
- Example
- // Include the cmath library
- #include <cmath>
- cout << sqrt(64);
- cout << round(2.6);
- cout << log(2);
- Other Math Functions
- A list of other popular Math functions (from the <cmath> library) can be found in the table below:
- Function Description
- abs(x) Returns the absolute value of x
- acos(x) Returns the arccosine of x, in radians
- asin(x) Returns the arcsine of x, in radians
- atan(x) Returns the arctangent of x, in radians
- cbrt(x) Returns the cube root of x
- ceil(x) Returns the value of x rounded up to its nearest integer
- cos(x) Returns the cosine of x, in radians
- cosh(x) Returns the hyperbolic cosine of x, in radians
- exp(x) Returns the value of Ex
- expm1(x) Returns ex -1
- fabs(x) Returns the absolute value of a floating x
- fdim(x, y) Returns the positive difference between x and y
- floor(x) Returns the value of x rounded down to its nearest integer
- hypot(x, y) Returns sqrt(x2 +y2) without intermediate overflow or underflow
- fma(x, y, z) Returns x*y+z without losing precision
- fmax(x, y) Returns the highest value of a floating x and y
- fmin(x, y) Returns the lowest value of a floating x and y
- fmod(x, y) Returns the floating point remainder of x/y
- pow(x, y) Returns the value of x to the power of y
- sin(x) Returns the sine of x (x is in radians)
- sinh(x) Returns the hyperbolic sine of a double value
- tan(x) Returns the tangent of an angle
- tanh(x) Returns the hyperbolic tangent of a double value
- */
- /*
- =====================================================================================================
- =====================================================================================================
- ____ _
- | _ \ | |
- | |_) | ___ ___ | | ___ __ _ _ __ ___
- | _ < / _ \ / _ \| |/ _ \/ _` | '_ \/ __|
- | |_) | (_) | (_) | | __/ (_| | | | \__ \
- |____/ \___/ \___/|_|\___|\__,_|_| |_|___/
- =====================================================================================================
- */
- /*
- C++ Booleans
- Very often, in programming, you will need a data type that can only have one of two values, like:
- YES / NO
- ON / OFF
- TRUE / FALSE
- For this, C++ has a bool data type, which can take the values true (1) or false (0).
- Boolean Values
- A boolean variable is declared with the bool keyword and can only take the values true or false:
- Example
- bool isCodingFun = true;
- bool isFishTasty = false;
- cout << isCodingFun; // Outputs 1 (true)
- cout << isFishTasty; // Outputs 0 (false)
- From the example above, you can read that a true value returns 1, and false returns 0.
- However, it is more common to return boolean values from boolean expressions (see below).
- Boolean Expression
- A Boolean expression is a C++ expression that returns a boolean value: 1 (true) or 0 (false).
- You can use a comparison operator, such as the greater than (>) operator to find out if an expression (or a variable) is true:
- Example
- int x = 10;
- int y = 9;
- cout << (x > y); // returns 1 (true), because 10 is higher than 9
- Or even easier:
- Example
- cout << (10 > 9); // returns 1 (true), because 10 is higher than 9
- In the examples below, we use the equal to (==) operator to evaluate an expression:
- Example
- int x = 10;
- cout << (x == 10); // returns 1 (true), because the value of x is equal to 10
- Example
- cout << (10 == 15); // returns 0 (false), because 10 is not equal to 15
- Booleans are the basis for all C++ comparisons and conditions.
- You will learn more about conditions (if...else) in the next chapter.
- */
- /*
- =====================================================================================================
- =====================================================================================================
- _ __ __ _ _ __ __ _
- (_) / _| / / | | (_) / _| / / | |
- _ | |_ / / ___ | | ___ ___ _ | |_ / / ___ | | ___ ___
- | | | _| / / / _ \ | | / __| / _ \ | | | _| / / / _ \ | | / __| / _ \
- | | | | / / | __/ | | \__ \ | __/ | | | | / / | __/ | | \__ \ | __/
- |_| |_| /_/ \___| |_| |___/ \___| |_| |_| /_/ \___| |_| |___/ \___|
- =====================================================================================================
- */
- /*
- C++ Conditions and If Statements
- C++ supports the usual logical conditions from mathematics:
- Less than: a < b
- Less than or equal to: a <= b
- Greater than: a > b
- Greater than or equal to: a >= b
- Equal to a == b
- Not Equal to: a != b
- You can use these conditions to perform different actions for different decisions.
- C++ has the following conditional statements:
- Use if to specify a block of code to be executed, if a specified condition is true
- Use else to specify a block of code to be executed, if the same condition is false
- Use else if to specify a new condition to test, if the first condition is false
- Use switch to specify many alternative blocks of code to be executed
- The if Statement
- Use the if statement to specify a block of C++ code to be executed if a condition is true.
- Syntax
- if (condition) {
- // block of code to be executed if the condition is true
- }
- Note that if is in lowercase letters. Uppercase letters (If or IF) will generate an error.
- 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:
- Example
- if (20 > 18) {
- cout << "20 is greater than 18";
- }
- We can also test variables:
- Example
- int x = 20;
- int y = 18;
- if (x > y) {
- cout << "x is greater than y";
- }
- Example explained
- 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".
- The else Statement
- Use the else statement to specify a block of code to be executed if the condition is false.
- Syntax
- if (condition) {
- // block of code to be executed if the condition is true
- } else {
- // block of code to be executed if the condition is false
- }
- Example
- int time = 20;
- if (time < 18) {
- cout << "Good day.";
- } else {
- cout << "Good evening.";
- }
- // Outputs "Good evening."
- Example explained
- 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".
- The else if Statement
- Use the else if statement to specify a new condition if the first condition is false.
- Syntax
- if (condition1) {
- // block of code to be executed if condition1 is true
- } else if (condition2) {
- // block of code to be executed if the condition1 is false and condition2 is true
- } else {
- // block of code to be executed if the condition1 is false and condition2 is false
- }
- Example
- int time = 22;
- if (time < 10) {
- cout << "Good morning.";
- } else if (time < 20) {
- cout << "Good day.";
- } else {
- cout << "Good evening.";
- }
- // Outputs "Good evening."
- Example explained
- 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".
- However, if the time was 14, our program would print "Good day."
- Short Hand If...Else (Ternary Operator)
- 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:
- Syntax
- variable = (condition) ? expressionTrue : expressionFalse;
- Instead of writing:
- Example
- int time = 20;
- if (time < 18) {
- cout << "Good day.";
- } else {
- cout << "Good evening.";
- }
- You can simply write:
- Example
- int time = 20;
- string result = (time < 18) ? "Good day." : "Good evening.";
- cout << result;
- */
- if (10 == 10) {
- for (int i = 0; i > 5; i++) {
- cout << "my number is:" << i;
- }
- }
- else if (25 < 1.2) {
- int i = 33;
- cout << i << endl;
- }
- else {
- cout << "both if and else if are wrong false this code is now running" << endl;
- }
- int time = 20;
- string result = (time < 18) ? "Good day." : "Good evening.";
- cout << result;
- /*
- =====================================================================================================
- =====================================================================================================
- _ _ _ _ _ _
- (_) | | | | | | | | | |
- ___ __ __ _ | |_ ___ | |__ ___ | |_ __ _ | |_ ___ _ __ ___ ___ _ __ | |_ ___
- / __| \ \ /\ / / | | | __| / __| | '_ \ / __| | __| / _` | | __| / _ \ | '_ ` _ \ / _ \ | '_ \ | __| / __|
- \__ \ \ V V / | | | |_ | (__ | | | | \__ \ | |_ | (_| | | |_ | __/ | | | | | | | __/ | | | | | |_ \__ \
- |___/ \_/\_/ |_| \__| \___| |_| |_| |___/ \__| \__,_| \__| \___| |_| |_| |_| \___| |_| |_| \__| |___/
- =====================================================================================================
- */
- /*
- C++ Switch Statements
- Use the switch statement to select one of many code blocks to be executed.
- Syntax
- switch(expression) {
- case x:
- // code block
- break;
- case y:
- // code block
- break;
- default:
- // code block
- }
- This is how it works:
- The switch expression is evaluated once.
- The value of the expression is compared with the values of each case.
- If there is a match, the associated block of code is executed.
- The break and default keywords are optional, and will be described later in this chapter
- The example below uses the weekday number to calculate the weekday name:
- Example
- int day = 4;
- switch (day) {
- case 1:
- cout << "Monday";
- break;
- case 2:
- cout << "Tuesday";
- break;
- case 3:
- cout << "Wednesday";
- break;
- case 4:
- cout << "Thursday";
- break;
- case 5:
- cout << "Friday";
- break;
- case 6:
- cout << "Saturday";
- break;
- case 7:
- cout << "Sunday";
- break;
- }
- // Outputs "Thursday" (day 4)
- The break Keyword
- When C++ reaches a break keyword, it breaks out of the switch block.
- This will stop the execution of more code and case testing inside the block.
- When a match is found, and the job is done, it's time for a break. There is no need for more testing.
- 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.
- The default Keyword
- The default keyword specifies some code to run if there is no case match:
- Example
- int day = 4;
- switch (day) {
- case 6:
- cout << "Today is Saturday";
- break;
- case 7:
- cout << "Today is Sunday";
- break;
- default:
- cout << "Looking forward to the Weekend";
- }
- // Outputs "Looking forward to the Weekend"
- Note: The default keyword must be used as the last statement in the switch, and it does not need a break.
- */
- /*
- =====================================================================================================
- =====================================================================================================
- _ _ _ _
- | | (_) | | | |
- __ __ | |__ _ | | ___ | | ___ ___ _ __ ___
- \ \ /\ / / | '_ \ | | | | / _ \ | | / _ \ / _ \ | '_ \ / __|
- \ V V / | | | | | | | | | __/ | | | (_) | | (_) | | |_) | \__ \
- \_/\_/ |_| |_| |_| |_| \___| |_| \___/ \___/ | .__/ |___/
- | |
- |_|
- =====================================================================================================
- */
- /*
- C++ Loops
- Loops can execute a block of code as long as a specified condition is reached.
- Loops are handy because they save time, reduce errors, and they make code more readable.
- C++ While Loop
- The while loop loops through a block of code as long as a specified condition is true:
- Syntax
- while (condition) {
- // code block to be executed
- }
- 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:
- Example
- int i = 0;
- while (i < 5) {
- cout << i << "\n";
- i++;
- }
- Note: Do not forget to increase the variable used in the condition, otherwise the loop will never end!
- The Do/While Loop
- 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.
- Syntax
- do {
- // code block to be executed
- }
- while (condition);
- 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:
- Example
- int i = 0;
- do {
- cout << i << "\n";
- i++;
- }
- while (i < 5);
- Do not forget to increase the variable used in the condition, otherwise the loop will never end!
- */
- int nottrue = 0;
- while (nottrue < 35) {
- nottrue++;
- cout << nottrue<<endl;
- }
- nottrue = 0;
- do {
- cout << "this number increments to ten"<< endl;
- nottrue++;
- } while (nottrue <= 10);
- /*
- =====================================================================================================
- =====================================================================================================
- ______ _
- | ____| | |
- | |__ ___ _ __ | | ___ ___ _ __ ___
- | __| / _ \ | '__| | | / _ \ / _ \ | '_ \ / __|
- | | | (_) | | | | | | (_) | | (_) | | |_) | \__ \
- |_| \___/ |_| |_| \___/ \___/ | .__/ |___/
- | |
- |_|
- =====================================================================================================
- */
- /*
- C++ For Loop
- 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:
- Syntax
- for (statement 1; statement 2; statement 3) {
- // code block to be executed
- }
- Statement 1 is executed (one time) before the execution of the code block.
- Statement 2 defines the condition for executing the code block.
- Statement 3 is executed (every time) after the code block has been executed.
- The example below will print the numbers 0 to 4:
- Example
- for (int i = 0; i < 5; i++) {
- cout << i << "\n";
- }
- Example explained
- Statement 1 sets a variable before the loop starts (int i = 0).
- 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.
- Statement 3 increases a value (i++) each time the code block in the loop has been executed.
- Another Example
- This example will only print even values between 0 and 10:
- Example
- for (int i = 0; i <= 10; i = i + 2) {
- cout << i << "\n";
- }
- */
- /*
- =====================================================================================================
- =====================================================================================================
- ____ _ __ _____ _ _
- | _ \ | | / / / ____| | | (_)
- | |_) | _ __ ___ __ _ | | __ / / | | ___ _ __ | |_ _ _ __ _ _ ___
- | _ < | '__| / _ \ / _` | | |/ / / / | | / _ \ | '_ \ | __| | | | '_ \ | | | | / _ \
- | |_) | | | | __/ | (_| | | < / / | |____ | (_) | | | | | | |_ | | | | | | | |_| | | __/
- |____/ |_| \___| \__,_| |_|\_\ /_/ \_____| \___/ |_| |_| \__| |_| |_| |_| \__,_| \___|
- =====================================================================================================
- */
- /*
- C++ Break
- 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.
- The break statement can also be used to jump out of a loop.
- This example jumps out of the loop when i is equal to 4:
- Example
- for (int i = 0; i < 10; i++) {
- if (i == 4) {
- break;
- }
- cout << i << "\n";
- }
- C++ Continue
- The continue statement breaks one iteration (in the loop), if a specified condition occurs, and continues with the next iteration in the loop.
- This example skips the value of 4:
- Example
- for (int i = 0; i < 10; i++) {
- if (i == 4) {
- continue;
- }
- cout << i << "\n";
- */
- /*
- =====================================================================================================
- =====================================================================================================
- /\
- / \ _ __ _ __ __ _ _ _
- / /\ \ | '__| | '__| / _` | | | | |
- / ____ \ | | | | | (_| | | |_| |
- /_/ \_\ |_| |_| \__,_| \__, |
- __/ |
- |___/
- =====================================================================================================
- */
- /*
- C++ Arrays
- Arrays are used to store multiple values in a single variable, instead of declaring separate variables for each value.
- 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:
- string cars[4];
- 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:
- string cars[4] = {"Volvo", "BMW", "Ford", "Mazda"};
- To create an array of three integers, you could write:
- int myNum[3] = {10, 20, 30};
- Access the Elements of an Array
- You access an array element by referring to the index number.
- This statement accesses the value of the first element in cars:
- Example
- string cars[4] = {"Volvo", "BMW", "Ford", "Mazda"};
- cout << cars[0];
- // Outputs Volvo
- Note: Array indexes start with 0: [0] is the first element. [1] is the second element, etc.
- Change an Array Element
- To change the value of a specific element, refer to the index number:
- Example
- cars[0] = "Opel";
- Example
- string cars[4] = {"Volvo", "BMW", "Ford", "Mazda"};
- cars[0] = "Opel";
- cout << cars[0];
- // Now outputs Opel instead of Volvo
- Loop Through an Array
- You can loop through the array elements with the for loop.
- The following example outputs all elements in the cars array:
- Example
- string cars[4] = {"Volvo", "BMW", "Ford", "Mazda"};
- for(int i = 0; i < 4; i++) {
- cout << cars[i] << "\n";
- }
- Omit Array Size
- 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:
- string cars[] = {"Volvo", "BMW", "Ford"}; // size of array is always 3
- This is completely fine. However, the problem arise if you want extra space for future elements. Then you have to overwrite the existing values:
- string cars[] = {"Volvo", "BMW", "Ford"};
- string cars[] = {"Volvo", "BMW", "Ford", "Mazda", "Tesla"};
- If you specify the size however, the array will reserve the extra space:
- string cars[5] = {"Volvo", "BMW", "Ford"}; // size of array is 5, even though it's only three elements inside it
- Now you can add a fourth and fifth element without overwriting the others:
- string cars[3] = {"Mazda"};
- string cars[4] = {"Tesla"};
- Omit Elements on Declaration
- It is also possible to declare an array without specifying the elements on declaration, and add them later:
- string cars[5];
- cars[0] = {"Volvo"};
- cars[1] = {"BMW"};
- ...
- */
- /*
- =====================================================================================================
- =====================================================================================================
- __
- / _|
- _ __ ___ | |_ ___ _ __ ___ _ __ ___ ___ ___
- | '__| / _ \ | _| / _ \ | '__| / _ \ | '_ \ / __| / _ \ / __|
- | | | __/ | | | __/ | | | __/ | | | | | (__ | __/ \__ \
- |_| \___| |_| \___| |_| \___| |_| |_| \___| \___| |___/
- =====================================================================================================
- */
- /*
- C++ References
- Creating References
- A reference variable is a "reference" to an existing variable, and it is created with the & operator:
- string food = "Pizza"; // food variable
- string &meal = food; // reference to food
- Now, we can use either the variable name food or the reference name meal to refer to the food variable:
- Example
- string food = "Pizza";
- string &meal = food;
- cout << food << "\n"; // Outputs Pizza
- cout << meal << "\n"; // Outputs Pizza
- Memory Address
- 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.
- 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.
- To access it, use the & operator, and the result will represent where the variable is stored:
- Example
- string food = "Pizza";
- cout << &food; // Outputs 0x6dfed4
- Note: The memory address is in hexadecimal form (0x..). Note that you may not get the same result in your program.
- And why is it useful to know the memory address?
- 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.
- These two features are one of the things that make C++ stand out from other programming languages, like Python and Java.
- */
- /*
- =====================================================================================================
- =====================================================================================================
- _____ _ _
- | __ \ (_) | |
- | |__) | ___ _ _ __ | |_ ___ _ __ ___
- | ___/ / _ \ | | | '_ \ | __| / _ \ | '__| / __|
- | | | (_) | | | | | | | | |_ | __/ | | \__ \
- |_| \___/ |_| |_| |_| \__| \___| |_| |___/
- =====================================================================================================
- */
- /*
- C++ Pointers
- Creating Pointers
- You learned from the previous chapter, that we can get the memory address of a variable by using the & operator:
- Example
- string food = "Pizza"; // A food variable of type string
- cout << food; // Outputs the value of food (Pizza)
- cout << &food; // Outputs the memory address of food (0x6dfed4)
- A pointer however, is a variable that stores the memory address as its value.
- 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:
- Example
- string food = "Pizza"; // A food variable of type string
- string* ptr = &food; // A pointer variable, with the name ptr, that stores the address of food
- // Output the value of food (Pizza)
- cout << food << "\n";
- // Output the memory address of food (0x6dfed4)
- cout << &food << "\n";
- // Output the memory address of food with the pointer (0x6dfed4)
- cout << ptr << "\n";
- Example explained
- 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.
- Use the & operator to store the memory address of the variable called food, and assign it to the pointer.
- Now, ptr holds the value of food's memory address.
- Tip: There are three ways to declare pointer variables, but the first way is preferred:
- string* mystring; // Preferred
- string *mystring;
- string * mystring;
- Get Memory Address and Value
- 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):
- Example
- string food = "Pizza"; // Variable declaration
- string* ptr = &food; // Pointer declaration
- // Reference: Output the memory address of food with the pointer (0x6dfed4)
- cout << ptr << "\n";
- // Dereference: Output the value of food with the pointer (Pizza)
- cout << *ptr << "\n";
- Note that the * sign can be confusing here, as it does two different things in our code:
- When used in declaration (string* ptr), it creates a pointer variable.
- When not used in declaration, it act as a dereference operator.
- Modify the Pointer Value
- You can also change the pointer's value. But note that this will also change the value of the original variable:
- Example
- string food = "Pizza";
- string* ptr = &food;
- // Output the value of food (Pizza)
- cout << food << "\n";
- // Output the memory address of food (0x6dfed4)
- cout << &food << "\n";
- // Access the memory address of food and output its value (Pizza)
- cout << *ptr << "\n";
- // Change the value of the pointer
- *ptr = "Hamburger";
- // Output the new value of the pointer (Hamburger)
- cout << *ptr << "\n";
- // Output the new value of the food variable (Hamburger)
- cout << food << "\n";
- */
- return 0;
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement