CE 101 Algorithms and Programming I PDF
Document Details
Uploaded by PalatialHummingbird159
Tags
Summary
This document provides notes on C++ programming, covering topics such as basic concepts, literals, strings, and operators. It includes examples and illustrations to aid understanding.
Full Transcript
CE 101 Algorithms and Programming I Basics of C++ (Cont.) Initialization of variables int a, b, result; float num; When the variables are declared, they have an undetermined value until they are assigned a value for the first time. But it is possible for a variable t...
CE 101 Algorithms and Programming I Basics of C++ (Cont.) Initialization of variables int a, b, result; float num; When the variables are declared, they have an undetermined value until they are assigned a value for the first time. But it is possible for a variable to have a specific value from the moment it is declared. This is called the initialization of the variable. In C++, there are three ways to initialize variables. They are all equivalent: Initialization of variables 1. c-like initialization (because it is inherited from the C language) 2. constructor initialization (introduced by the C++ language) 3. uniform initialization, similar to the above, but using curly braces ({}) instead of parentheses (this was introduced by the revision of the C++ standard, in 2011) Type deduction: auto and decltype When a new variable is initialized, the compiler can figure out what the type of the variable is automatically by the initializer. For this, it suffices to use auto as the type specifier for the variable: bar is declared as having an auto type; therefore, the type of bar is the type of the value used to initialize it: in this case it uses the type of foo, which is int. Variables that are not initialized can also make use of type deduction with the decltype specifier: bar is declared as having the same type as foo. Type deduction: auto and decltype auto and decltype are powerful features recently added to the language. Use type deduction features either when the type cannot be obtained by other means or when using it improves code readability. Introduction to strings Fundamental types represent the most basic types handled by the machines where the code may run. But one of the major strengths of the C++ language is its rich set of compound types, of which the fundamental types are mere building blocks. An example of compound type is the string class. Variables of this type are able to store sequences of characters, such as words or sentences. A very useful feature! A first difference with fundamental data types is that in order to declare and use objects (variables) of this type, the program needs to include the header where the type is defined within the standard library (header ): strings can be initialized with any valid string literal, just like numerical type variables can be initialized to any valid numerical literal. As with fundamental types, all initialization formats are valid with strings: Strings Strings can also perform all the other basic operations that fundamental data types can, like being declared without an initial value and change its value during execution: Note: inserting the endl manipulator ends the line (printing a newline character and flushing the stream). Constants Constants are expressions with a fixed value. Literals the most obvious kind of constants. used to express particular values within the source code of a program. We have already used some in previous examples to give specific values to variables or to express messages we wanted our programs to print out, for example, when we wrote: The 5 in this piece of code was a literal constant. Literal constants can be classified into: integer, floating-point, characters, strings, Boolean, pointers, and user-defined literals. Constants In addition to decimal numbers (those that most of us use every day), C++ allows the use of octal numbers (base 8) and hexadecimal numbers (base 16) as literal constants. For octal literals, the digits are preceded with a 0 (zero) character. And for hexadecimal, they are preceded by the characters 0x (zero, x). For example, the following literal constants are all equivalent to each other: Constants Literal constants have a type, just like variables. By default, integer literals are of type int. However, certain suffixes may be appended to an integer literal to specify a different integer type: Constants Unsigned may be combined with any of the other two in any order to form unsigned long. In all the cases above, the suffix can be specified using either upper or lowercase letters. Floating Point Numerals They express real values, with decimals and/or exponents. They can include either a decimal point, an e character (that expresses "by ten at the Xth height", where X is an integer value that follows the e character), or both a decimal point and an e character: These are four valid numbers with decimals expressed in C++. The first number is PI, the second one is the number of Avogadro, the third is the electric charge of an electron (an extremely small number) -all of them approximated-, and the last one is the number three expressed as a floating-point numeric literal. Floating Point Numerals The default type for floating-point literals is double. Floating-point literals of type float or long double can be specified by adding one of the following suffixes: For example: Any of the letters that can be part of a floating-point numerical constant (e, f, l) can be written using either lower or uppercase letters with no difference in meaning. Character and string literals They are enclosed in quotes: The first two expressions represent single-character literals, and the following two represent string literals composed of several characters. Notice that to represent a single character, enclose it between single quotes ('), and to express a string we enclose the characters between double quotes ("). Character and string literals Both single-character and string literals require quotation marks surrounding them to distinguish them from possible variable identifiers or reserved keywords. Notice the difference between these two expressions: Here, x alone would refer to an identifier, such as the name of a variable or a compound type, whereas 'x' (enclosed within single quotation marks) would refer to the character literal 'x' (the character that represents a lowercase x letter). Character and string literals Character and string literals can also represent special characters that are difficult or impossible to express otherwise in the source code of a program, like newline (\n) or tab (\t). These special characters are all of them preceded by a backslash character (\). A list of the single character escape codes is given on the right hand side: Several string literals can be concatenated to form a single string literal simply by separating them by one or more blank spaces, including tabs, newlines, and other valid blank characters. For example: The above is a string literal equivalent to: Note how spaces within the quotes are part of the literal, while those outside them are not. Character and string literals Some programmers also use a trick to include long string literals in multiple lines: In C++, a backslash (\) at the end of line is considered a line- continuation character that merges both that line and the next into a single line. Therefore the following code: is equivalent to: Character and string literals All the character literals and string literals described so far are made of characters of type char. A different character type can be specified by using one of the following prefixes: Note that, unlike type suffixes for integer literals, these prefixes are case sensitive: lowercase for char16_t and uppercase for char32_t and wchar_t. Other literals Three keyword literals exist in C++: true, false and nullptr: true and false are the two possible values for variables of type bool. nullptr is the null pointer value. Typed constant expressions Sometimes, it is just convenient to give a name to a constant value: We can then use these names instead of the literals they were defined to. Preprocessor definitions (#define) Another mechanism to name constant values is the use of preprocessor definitions. They have the following form: After this directive, any occurrence of identifier in the code is interpreted as replacement, where replacement is any sequence of characters (until the end of the line). This replacement is performed by the preprocessor, and happens before the program is compiled, thus causing a sort of blind replacement: the validity of the types or syntax involved is not checked in any way. Note that the #define lines are preprocessor directives, and as such are single-line instructions that -unlike C++ statements- do not require semicolons (;) at the end; the directive extends automatically until the end of the line. If a semicolon is included in the line, it is part of the replacement sequence and is also included in all replaced occurrences. Operators Once introduced to variables and constants, we can begin to operate with them by using operators. What follows is a complete list of operators. At this point, it is likely not necessary to know all of them, but they are all listed here to also serve as reference. Assignment operator (=) assigns a value to a variable The assignment operation always takes place from right to left, and never the other way around: This statement assigns to variable x the value contained in variable y. The value of x at the moment this statement is executed is lost and replaced by the value of y. Consider also that we are only assigning the value of y to x at the moment of the assignment operation. Therefore, if y changes at a later moment, it will not affect the new value taken by x. Notice how a was not affected by the final modification of b, even though we declared a = b earlier. Assignment operations are expressions that can be evaluated. That means that the assignment itself has a value, and -for fundamental types- this value is the one assigned in the operation. For example: In this expression, y is assigned the result of adding 2 and the value of another assignment expression (which has itself a value of 5). It is roughly equivalent to: The following expression is also valid in C++: It assigns 5 to the all three variables: x, y and z; always from right-to-left. Arithmetic operators ( +, -, *, /, % ) The five arithmetical operations supported by C++ are: Operations of addition, subtraction, multiplication and division correspond literally to their respective mathematical operators. The last one, modulo operator, represented by a percentage sign (%), gives the remainder of a division of two values. For example: Compound assignment (+=, -=, *=, /=, %=, >>=,