C++ Programming

Jul 8, 2024

Lecture on C++ Programming

Introduction to C++

  • C++ Speed: Fast language, used in advanced graphics apps (Adobe, video editing, graphics-intensive software).
  • Middle-Level Language: Used with embedded systems, video game creation.
  • Comparison: Faster and closer to machine code compared to Python, Java, C# (higher level languages).
  • Learning Curve: Worthwhile but steeper than some other languages.

Requirements to Get Started

  1. Text Editor: VS Code, CodeBlocks, Notepad (VS Code and CodeBlocks also are IDEs with dev tools).
  2. Compiler: Converts source code to machine instructions. GCC for Windows/Linux, Clang for macOS.

Setting Up VS Code

  • Download VS Code from code.visualstudio.com.
  • Steps: Download, install, launch.
  • Recommended Extensions: C/C++ and Code Runner.

Creating and Running a Simple C++ Program

  1. File Setup: Create a folder for projects, create a new file (hello_world.cpp).
  2. Compiler Setup: Instructions vary based on OS, Linux/Mac easier (commands for terminal), Windows detailed via mingw setup.
  3. Writing Code: Basic output (std::cout), using return 0 for successful execution check, new line management (std::endl or \n), writing comments (// for single-line, /* ... */ for multi-line).

Variables

  • Declaration and Assignment: Steps to declare (int x;) and assign (x = 5;), alternatively (int x = 5;).
  • Data Types:
    • int: Whole numbers (e.g., age, year, days).
    • double: Decimal numbers (e.g., price, GPA, temperature).
    • char: Single characters (e.g., grade, initial, currency symbols).
    • bool: True/False states (e.g., student, power, for sale).
    • string: Sequence of text (e.g., name, day, address).

Const Keyword & Namespaces

  • Const Variables: Immutable variables, useful for constants (e.g., const double PI = 3.14159;), naming conventions (uppercase).
  • Namespaces: Prevent name conflicts, using different namespaces for identical names, using namespace ... practice.

Typedefs & Type Aliases

  • Typedefs: Create new identifier (alias) for existing data type for readability and reducing typos.
  • Using Keyword: Modern alternative to typedef for better template support.

Arithmetic Operators

  • Basic Operations: Addition, subtraction, multiplication, division, and modulus (% for remainder).
  • Order of Precedence: Parentheses, then multiplication/division, then addition/subtraction.

Type Conversion

  • Implicit and Explicit: Conversion between data types, explicitly precede with new data type (int x = (int)3.14;).
  • Practical Example: Avoiding integer division issues when calculating scores.

User Input Handling

  • Basic Input: std::cin for character input, handling issues with spaces using std::getline.
  • Input Validation: Clearing input buffer to handle unexpected characters.

Math Functions & Usage

  • Functions: max(), min(), pow(), sqrt(), abs(), round(), ceil(), floor() from cmath library.
  • Practice: Hypotenuse calculation using C++ math functions.

Conditional Statements

  • If Statements: Conditions to control program flow (if, else if, else), comparison operators (> >= < <= ==).
  • Switch Statements: Efficient alternative to multiple else if for comparing one value against many cases.

Ternary Operator & Logical Operators

  • Ternary Operator: Shorthand for if-else (condition ? expression1 : expression2;).
  • Logical Operators: && (AND), || (OR), ! (NOT) for compound conditions.

Loops

  • While Loop: Executes code while condition is true, useful for enforcing user action.
  • Do-While Loop: Executes code block at least once before checking condition.
  • For Loop: Loop with initialization, condition, and increment, good for defined iterations.
  • Break and Continue: Manage loop execution (break exits loop, continue skips to next iteration).
  • Nested Loops: Loop inside another loop, practical example: generating patterns or grids.

Arrays

  • Basic Concepts: Initialization, accessing elements, modifying values, fixed-size.
  • Multi-dimensional Arrays: Grids/matrices, accessing with multiple indices, iterating over them.
  • User Input: Filling arrays through loops, working with dynamic sizes (user input).
  • Array Functions & Searching: Custom functions for array operations (searching, sorting).

Pointer Concepts

  • Pointers: Variables storing memory address, interaction with * (dereference operator) and & (address-of operator).
  • Pointer Operations: Assigning, dereferencing, null pointers to ensure valid addresses, dynamic memory usage (new, delete).

Structures (structs)

  • Structs: Group related variables of different types under one name, accessing through dot operator.
  • Passing Structs: By value (copy) or by reference (original), modifying via functions.

Enumerations (enums)

  • Enums: User-defined data type for set of constants, useful for predefined options.
  • Usage in Switch: Simplifies handling of multiple related options.

Object-Oriented Programming

  • Classes & Objects: Classes are blueprints, objects are instances; attributes and methods.
  • Constructors: Special methods for initializing objects, overloaded constructors for multiple formats.
  • Getters and Setters: Public methods to access private attributes for encapsulation.
  • Inheritance: Ability to derive classes from base class, inheriting attributes and methods for code reuse.

Function Templates

  • Templates: Define functions for any data type using template <typename T>, overridden by various types at runtime.

Practical Applications

  • Constructing meaningful projects/examples like banking programs, quiz games, and common algorithms (e.g., sorting, searching).