### Introduction to C++ C++ is a powerful, high-performance, object-oriented programming language. It's an extension of C, offering features like classes, objects, and templates. #### Basic Structure ```cpp #include // Include necessary libraries // Main function: program execution starts here int main() { // Code goes here std::cout ### Data Types Fundamental types to store different kinds of values. | Type | Size (bytes) | Range | Description | |---------|--------------|----------------------------------------|--------------------------| | `int` | 4 | -2x10^9 to 2x10^9 | Integer numbers | | `char` | 1 | -128 to 127 or 0 to 255 | Single character | | `bool` | 1 | `true` or `false` | Boolean value | | `float` | 4 | $\approx \pm 3.4 \times 10^{38}$ (7 digits precision) | Single-precision float | | `double`| 8 | $\approx \pm 1.7 \times 10^{308}$ (15 digits precision) | Double-precision float | #### Type Modifiers - `short`, `long`: Modify `int` size. - `signed`, `unsigned`: Specify if a type can hold negative values. - Example: `unsigned int`, `long double`. ### Variables & Constants #### Variable Declaration & Initialization - **Declaration:** `dataType variableName;` - **Initialization:** `dataType variableName = value;` - **Multiple:** `int a, b = 5;` ```cpp int age = 30; // Integer variable double price = 19.99; // Double-precision float char grade = 'A'; // Character bool isActive = true; // Boolean std::string name = "Alice"; // String (requires #include ) ``` #### Constants Values that cannot be changed after initialization. - `const dataType CONST_NAME = value;` - `#define PI 3.14159` (preprocessor macro) ```cpp const double PI = 3.14159; const int MAX_USERS = 100; ``` ### Operators Symbols that perform operations on operands. #### Arithmetic Operators - `+` (Addition), `-` (Subtraction), `*` (Multiplication), `/` (Division), `%` (Modulo) - `++` (Increment), `--` (Decrement) #### Relational Operators - `==` (Equal to), `!=` (Not equal to) - ` ` (Greater than) - ` =` (Greater than or equal to) #### Logical Operators - `&&` (Logical AND) - `||` (Logical OR) - `!` (Logical NOT) #### Assignment Operators - `=` (Assign) - `+=`, `-=`, `*=`, `/=`, `%=` (Compound assignment) #### Other Operators - `sizeof()`: Returns the size of a variable or type. - `&`: Address-of operator (for pointers). - `*`: Dereference operator (for pointers). - `.` (Member access), `->` (Pointer member access) ### Control Structures Control the flow of program execution. #### If-Else Statements Conditional execution. ```cpp if (condition) { // code if condition is true } else if (anotherCondition) { // code if anotherCondition is true } else { // code if all conditions are false } ``` #### Switch Statement Multi-way branch. ```cpp switch (expression) { case value1: // code for value1 break; case value2: // code for value2 break; default: // code if no match } ``` #### Loops - **`for` loop:** For known number of iterations. ```cpp for (initialization; condition; update) { // code to repeat } ``` - **`while` loop:** Repeats as long as condition is true. ```cpp while (condition) { // code to repeat } ``` - **`do-while` loop:** Executes at least once, then repeats as long as condition is true. ```cpp do { // code to repeat } while (condition); ``` - **`break`:** Exits the loop. - **`continue`:** Skips current iteration, proceeds to next. ### Functions Reusable blocks of code. #### Declaration & Definition ```cpp // Function declaration (prototype) int add(int a, int b); int main() { int sum = add(5, 3); // Function call return 0; } // Function definition int add(int a, int b) { return a + b; } ``` #### Parameters - **Pass by Value:** A copy of the argument is passed. - **Pass by Reference:** The original argument is passed (using `&`). ```cpp void modifyValue(int val) { val = 10; } // Original unchanged void modifyRef(int &ref) { ref = 10; } // Original modified ``` #### Return Types - `void`: Function does not return a value. - Any data type: Returns a value of that type. ### Arrays Collections of elements of the same data type, stored in contiguous memory locations. #### Declaration & Initialization ```cpp int numbers[5]; // Declares an array of 5 integers int scores[] = {10, 20, 30, 40, 50}; // Initialized array, size inferred int matrix[2][3] = {{1, 2, 3}, {4, 5, 6}}; // 2D array ``` #### Accessing Elements - `arrayName[index]` (0-indexed) ```cpp numbers[0] = 100; // Assigns 100 to the first element int thirdScore = scores[2]; // Gets the third element (30) ``` ### Pointers Variables that store memory addresses. #### Declaration `dataType *pointerName;` #### Operations - `&` (Address-of operator): Returns the memory address of a variable. - `*` (Dereference operator): Accesses the value at the address stored in the pointer. ```cpp int var = 10; int *ptr = &var; // ptr now holds the address of var std::cout ### References An alias (another name) for an existing variable. Must be initialized at declaration. ```cpp int original = 50; int &alias = original; // alias is another name for original alias = 100; // original also becomes 100 std::cout ### Strings Sequences of characters. C++ offers two main ways: #### C-style Strings (char arrays) - Null-terminated character arrays. Requires ` `. ```cpp char greeting[] = "Hello"; // 'H', 'e', 'l', 'l', 'o', '\0' char name[20]; strcpy(name, "World"); // Copy string strcat(greeting, name); // Concatenate strings ``` #### C++ `std::string` - More flexible, safer, and easier to use. Requires ` `. ```cpp std::string message = "Hello"; std::string user = "Alice"; std::string fullMessage = message + ", " + user + "!"; // Concatenation std::cout ### Input/Output (I/O) Using `iostream` for console interaction. #### Output - `std::cout`: Standard output stream. - ` >` (Extraction operator): Reads data from `cin`. ```cpp int age; std::cout > age; std::cout ### Structs User-defined data types that group related variables (members) under one name. Members are public by default. #### Declaration & Usage ```cpp struct Person { std::string name; int age; double height; }; int main() { Person p1; // Declare a struct variable p1.name = "Bob"; p1.age = 25; p1.height = 1.75; Person p2 = {"Alice", 30, 1.68}; // Initialize upon declaration std::cout ### Classes (Basics) The fundamental building block of Object-Oriented Programming (OOP) in C++. Like structs, but members are private by default, and can include functions (methods). #### Declaration & Usage ```cpp class Car { public: // Access specifier: members are accessible from outside the class std::string brand; std::string model; int year; // Method (member function) void displayInfo() { std::cout ### `std::vector` (STL) Dynamic arrays from the Standard Template Library (STL). They can grow and shrink in size. Requires `#include `. #### Declaration & Operations ```cpp #include #include int main() { std::vector numbers; // Empty vector of integers numbers.push_back(10); // Add element to end numbers.push_back(20); numbers.push_back(30); std::cout names = {"Alice", "Bob", "Charlie"}; names.clear(); // Removes all elements std::cout ### Error Handling (Exceptions) Mechanisms to handle runtime errors gracefully. #### `try-catch` Block ```cpp #include #include // For standard exceptions double divide(int num, int den) { if (den == 0) { throw std::runtime_error("Division by zero!"); } return static_cast (num) / den; } int main() { try { double result = divide(10, 0); std::cout