Introduction to C++ Programming - Notes
Introduction to C++
- C++ facilitates a disciplined approach to computer program design.
- Programs process information and display results.
- Examples:
- Displaying messages on the screen.
- Obtaining information from the user.
- Performing arithmetic calculations.
- Making decisions by comparing numbers.
First Program in C++: Printing a Line of Text
- Illustrates important C++ features.
- Comments:
- Explain programs to programmers.
- Improve readability.
- Ignored by compiler.
- Single-line comments begin with
//.- Example:
// This is a text-printing program.
- Multi-line comments start with
/* and end with */.
- Good Programming Practice 2.1: Every program should begin with a comment describing the program's purpose, author, date, and time.
- Preprocessor directives:
- Processed before compiling.
- Begin with
#.- Example:
#include <iostream>
- Tells the preprocessor to include the input/output stream header file.
- White space:
- Blank lines, space characters, and tabs.
- Used to enhance readability.
- Ignored by the compiler.
- Common Programming Error 2.1: Forgetting to include the
<iostream> header file causes a compiler error. - Good Programming Practice 2.2: Use blank lines and space characters to enhance program readability.
- Function
main:- Part of every C++ program.
- Exactly one
main function per program. - Can return a value.
- Example:
int main() returns an integer.
- Body delimited by braces
{}.
- Statements:
- Instruct the program to perform an action.
- End with a semicolon
;.
- Namespace
std:::- Specifies using a name that belongs to the "namespace"
std. - Can be removed using
using statements.
- Standard output stream object:
std::cout- "Connected" to the screen.
- Defined in
<iostream>.
- Stream insertion operator
<<:- Value to the right (right operand) inserted into left operand.
- Example:
std::cout << "Hello";- Inserts the string "Hello" into the standard output.
- Displays to the screen.
- Escape characters:
- Character preceded by
\. - Indicates “special” character output.
- Example:
\n moves the cursor to the beginning of the next line.
- Common Programming Error 2.2: Forgetting the semicolon at the end of a C++ statement is a syntax error.
- Syntax errors are also known as compiler errors, compile-time errors, or compilation errors.
- The program won't execute until all syntax errors are corrected.
return statement:- One way to exit a function.
- When used at the end of
main, the value 0 indicates successful termination.
- Good Programming Practice 2.3: Many programmers end a function's output with a newline (
\n) to ensure the cursor is at the beginning of a new line, promoting software reusability.
| Escape sequence | Description |
|---|
\n | Newline. Position the screen cursor to the beginning of the next line. |
\t | Horizontal tab. Move the screen cursor to the next tab stop. |
\r | Carriage return. Position the screen cursor to the beginning of the current line. |
\a | Alert. Sound the system bell. |
\\ | Backslash. Used to print a backslash character. |
\' | Single quote. Use to print a single quote character. |
\" | Double quote. Used to print a double quote character. |
- Good Programming Practice 2.4: Indent the body of each function one level within the braces to make the program's structure clear.
- Good Programming Practice 2.5: Set a consistent indent size (e.g., 1/4-inch tab stops or three spaces).
Modifying Our First C++ Program
- Examples:
- Printing text on one line using multiple statements.
- Each stream insertion resumes printing where the previous one stopped.
- Printing text on several lines using a single statement.
- Newline escape sequences position the cursor to the beginning of the next line.
- Two back-to-back newline characters output a blank line.
Another C++ Program: Adding Integers
- Variable:
- A location in memory where a value can be stored.
- Common data types:
int: for integer numbers.char: for characters.double: for floating-point numbers.
- Declare variables with data type and name before use.
- You can declare several variables of the same type in one declaration using a comma-separated list.
- Example:
int integer1, integer2, sum;
- Variable name:
- Must be a valid identifier.
- Series of characters (letters, digits, underscores).
- Cannot begin with a digit.
- Case-sensitive.
- Good Programming Practice 2.6: Place a space after each comma in declarations.
- Good Programming Practice 2.7: Some programmers prefer to declare each variable on a separate line with a descriptive comment.
- Portability Tip 2.1: Use identifiers of 31 characters or fewer to ensure portability.
- Good Programming Practice 2.8: Choose meaningful identifiers to make a program self-documenting.
- Good Programming Practice 2.9: Avoid abbreviations in identifiers.
- Good Programming Practice 2.10: Avoid identifiers that begin with underscores and double underscores.
- Error-Prevention Tip 2.1: Avoid using "loaded" words like "object" as identifiers.
- Good Programming Practice 2.11: Always place a blank line between a declaration and adjacent executable statements.
- Good Programming Practice 2.12: Separate declarations from executable statements with a blank line.
- Input stream object:
std::cin from <iostream>- Usually connected to the keyboard.
- Stream extraction operator
>>:- Waits for user input and Enter key.
- Stores the value in the variable to the right of the operator.
- Converts the value to the variable’s data type.
- Example:
std::cin >> number1;
- Error-Prevention Tip 2.2: Programs should validate the correctness of all input values.
- Assignment operator `=``:
- Assigns the value on the right to the variable on the left.
- Binary operator (two operands).
- Example:
sum = variable1 + variable2;
- Stream manipulator
std::endl:- Outputs a newline and flushes the output buffer.
- Good Programming Practice 2.13: Place spaces on either side of a binary operator.
- Concatenating stream insertion operations:
- Use multiple stream insertion operators in a single statement (also called chaining or cascading).
std::cout << "Sum is " << number1 + number2 << std::endl;
Memory Concepts
- Variable names correspond to memory locations.
- Every variable has a name, type, size, and value.
- When a new value is placed into a variable, it overwrites the old value.
- Writing to memory is “destructive.”
- Reading from memory is nondestructive.
Arithmetic
- Arithmetic operators:
*: Multiplication/: Division (Integer division truncates the remainder. E.g., 7/5=1)%: Modulus operator (returns the remainder. E.g., 7)
- Common Programming Error 2.3: Attempting to use the modulus operator with noninteger operands is a compilation error.
- Straight-line form: Required for arithmetic expressions in C++.
- Grouping subexpressions: Parentheses are used to group subexpressions.
- Example: a∗(b+c)
| C++ Operator | Operation | Algebraic | C++ Expression |
|---|
+ | Addition | f+7 | f + 7 |
- | Subtraction | p−c | p - c |
* | Multiplication | bm or b"."m | b * m |
/ | Division | x/y | x / y |
% | Modulus | rmods | r % s |
- Rules of operator precedence:
- Parentheses.
- Multiplication, Division, and Modulus (left to right).
- Addition and Subtraction (left to right).
| Operator(s) | Operation(s) | Order of Evaluation |
| :---------: | :------------- | :------------------------------------------------------------------------------------------------------------------------------------------------ |-
| () | Parentheses | Evaluated first. Innermost parentheses are evaluated first. If on the same level, they're evaluated left to right. |
| *, /, % | Mult, Div, Mod | Evaluated second. If there are several, they are evaluated left to right. |
| +, - | Add, Sub | Evaluated last. If there are several, they are evaluated left to right. |
- Common Programming Error 2.4: C++ does not support
** or ^ for exponentiation. - Good Programming Practice 2.14: Using redundant parentheses in complex arithmetic expressions can make the expressions clearer.
Decision Making: Equality and Relational Operators
- Condition: An expression that can be either true or false.
if statement: Executes the body if the condition is true; otherwise, the body is skipped.
| Standard Algebraic | C++ Equality or Relational Operator | C++ condition | Meaning of C++ Condition |
|---|
> | > | x > y | x is greater than y |
< | < | x < y | x is less than y |
>= | >= | x >= y | x is greater than or equal to y |
<= | <= | x <= y | x is less than or equal to y |
= | == | x == y | x is equal to y |
!= | != | x != y | x is not equal to y |
- Common Programming Error 2.5: Syntax error if there are spaces between the symbols in
==, !=, >=, and <=. - Common Programming Error 2.6: Reversing the order of symbols (e.g.,
=!, =>, =<) is usually a syntax error or logic error. - Common Programming Error 2.7: Confusing the equality operator
== with the assignment operator = results in logic errors. - Good Programming Practice 2.15: Place
using declarations immediately after the #include. - Good Programming Practice 2.16: Indent the statements in the body of an
if statement. - Good Programming Practice 2.17: For readability, use no more than one statement per line.
- Common Programming Error 2.8: Placing a semicolon after the condition in an
if statement is often a logic error. - Common Programming Error 2.9: It is a syntax error to split an identifier by inserting white-space characters.
- Good Programming Practice 2.18: A lengthy statement may be spread over several lines, broken at meaningful points, indenting all subsequent lines.
- Good Programming Practice 2.19: Refer to the operator precedence and associativity chart when writing expressions containing many operators.