cpp

examples

examples.cpp⚙️
/**
 * C++ Operators - Examples
 * 
 * This file demonstrates various operators in C++ with practical examples.
 * Each example is contained in its own function for easy understanding.
 * 
 * Topics covered:
 * - Arithmetic operators
 * - Relational operators
 * - Logical operators
 * - Bitwise operators
 * - Assignment operators
 * - Increment/Decrement operators
 * - Ternary operator
 * - sizeof operator
 * - Operator precedence
 * - Type casting
 * 
 * Compile: g++ -std=c++17 -Wall -Wextra examples.cpp -o examples
 * Run: ./examples
 */

#include <iostream>
#include <iomanip>
#include <cmath>
#include <string>
#include <bitset>

using namespace std;

// ============================================================
// Example 1: Arithmetic Operators
// ============================================================
void example_arithmetic_operators() {
    cout << "\n=== Example 1: Arithmetic Operators ===" << endl;
    
    int a = 17, b = 5;
    
    cout << "a = " << a << ", b = " << b << endl;
    cout << "a + b = " << (a + b) << endl;  // 22
    cout << "a - b = " << (a - b) << endl;  // 12
    cout << "a * b = " << (a * b) << endl;  // 85
    cout << "a / b = " << (a / b) << endl;  // 3 (integer division)
    cout << "a % b = " << (a % b) << endl;  // 2 (remainder)
    
    cout << "\n-- Integer vs Float Division --" << endl;
    cout << "17 / 5 (int) = " << 17 / 5 << endl;          // 3
    cout << "17.0 / 5 (float) = " << 17.0 / 5 << endl;    // 3.4
    cout << "17 / 5.0 (float) = " << 17 / 5.0 << endl;    // 3.4
    
    cout << "\n-- Unary Operators --" << endl;
    int x = 10;
    cout << "x = " << x << endl;
    cout << "+x = " << (+x) << endl;   // 10
    cout << "-x = " << (-x) << endl;   // -10
    cout << "-(-x) = " << (-(-x)) << endl;  // 10
}

// ============================================================
// Example 2: Modulus Applications
// ============================================================
void example_modulus_applications() {
    cout << "\n=== Example 2: Modulus Applications ===" << endl;
    
    // Check even or odd
    cout << "-- Even/Odd Check --" << endl;
    for (int i = 1; i <= 10; i++) {
        cout << i << " is " << ((i % 2 == 0) ? "even" : "odd") << endl;
    }
    
    // Extract last digit
    cout << "\n-- Extract Last Digit --" << endl;
    int number = 12345;
    cout << "Number: " << number << endl;
    cout << "Last digit: " << (number % 10) << endl;
    
    // Wrap around (circular indexing)
    cout << "\n-- Circular Indexing (7 days of week) --" << endl;
    string days[] = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};
    int today = 3;  // Wednesday
    cout << "Today: " << days[today] << endl;
    cout << "3 days later: " << days[(today + 3) % 7] << endl;
    cout << "10 days later: " << days[(today + 10) % 7] << endl;
    
    // Check divisibility
    cout << "\n-- Divisibility Check --" << endl;
    int num = 24;
    cout << num << " divisible by 3? " << ((num % 3 == 0) ? "Yes" : "No") << endl;
    cout << num << " divisible by 5? " << ((num % 5 == 0) ? "Yes" : "No") << endl;
}

// ============================================================
// Example 3: Relational Operators
// ============================================================
void example_relational_operators() {
    cout << "\n=== Example 3: Relational Operators ===" << endl;
    
    int a = 10, b = 20, c = 10;
    
    cout << boolalpha;  // Print "true"/"false" instead of 1/0
    cout << "a = " << a << ", b = " << b << ", c = " << c << endl;
    
    cout << "\na == b: " << (a == b) << endl;   // false
    cout << "a == c: " << (a == c) << endl;     // true
    cout << "a != b: " << (a != b) << endl;     // true
    cout << "a < b: " << (a < b) << endl;       // true
    cout << "a > b: " << (a > b) << endl;       // false
    cout << "a <= c: " << (a <= c) << endl;     // true
    cout << "b >= a: " << (b >= a) << endl;     // true
    
    // Comparing characters
    cout << "\n-- Character Comparison --" << endl;
    char ch1 = 'A', ch2 = 'Z';
    cout << "'" << ch1 << "' < '" << ch2 << "': " << (ch1 < ch2) << endl;  // true
    cout << "'" << ch1 << "' ASCII value: " << (int)ch1 << endl;  // 65
    cout << "'" << ch2 << "' ASCII value: " << (int)ch2 << endl;  // 90
}

// ============================================================
// Example 4: Floating-Point Comparison
// ============================================================
void example_float_comparison() {
    cout << "\n=== Example 4: Floating-Point Comparison ===" << endl;
    
    double a = 0.1 + 0.2;
    double b = 0.3;
    
    cout << fixed << setprecision(17);
    cout << "0.1 + 0.2 = " << a << endl;
    cout << "0.3       = " << b << endl;
    
    cout << boolalpha;
    cout << "\nDirect comparison (a == b): " << (a == b) << endl;  // Likely false!
    
    // Epsilon comparison
    const double EPSILON = 1e-9;
    bool approximately_equal = fabs(a - b) < EPSILON;
    cout << "Epsilon comparison: " << approximately_equal << endl;  // true
    
    // Relative epsilon for larger numbers
    cout << "\n-- Relative Epsilon --" << endl;
    double x = 1000000.1, y = 1000000.2;
    double diff = fabs(x - y);
    double relative_diff = diff / max(fabs(x), fabs(y));
    cout << "Difference: " << diff << endl;
    cout << "Relative difference: " << relative_diff << endl;
}

// ============================================================
// Example 5: Logical Operators
// ============================================================
void example_logical_operators() {
    cout << "\n=== Example 5: Logical Operators ===" << endl;
    
    bool a = true, b = false;
    
    cout << boolalpha;
    cout << "a = " << a << ", b = " << b << endl;
    
    cout << "\n-- AND (&&) --" << endl;
    cout << "a && a: " << (a && a) << endl;  // true
    cout << "a && b: " << (a && b) << endl;  // false
    cout << "b && b: " << (b && b) << endl;  // false
    
    cout << "\n-- OR (||) --" << endl;
    cout << "a || a: " << (a || a) << endl;  // true
    cout << "a || b: " << (a || b) << endl;  // true
    cout << "b || b: " << (b || b) << endl;  // false
    
    cout << "\n-- NOT (!) --" << endl;
    cout << "!a: " << (!a) << endl;  // false
    cout << "!b: " << (!b) << endl;  // true
    
    // Practical example
    cout << "\n-- Practical Example: Access Control --" << endl;
    int age = 25;
    bool hasID = true;
    bool isVIP = false;
    
    bool canEnter = (age >= 21 && hasID) || isVIP;
    cout << "Age: " << age << ", Has ID: " << hasID << ", Is VIP: " << isVIP << endl;
    cout << "Can enter (21+ with ID or VIP): " << canEnter << endl;
}

// ============================================================
// Example 6: Short-Circuit Evaluation
// ============================================================
void example_short_circuit() {
    cout << "\n=== Example 6: Short-Circuit Evaluation ===" << endl;
    
    int x = 0;
    
    // AND short-circuit: second operand not evaluated if first is false
    cout << "Testing: x != 0 && 10/x > 1 (where x = 0)" << endl;
    if (x != 0 && 10 / x > 1) {
        cout << "This won't print" << endl;
    } else {
        cout << "Safe! Division by zero was avoided due to short-circuit" << endl;
    }
    
    // OR short-circuit: second operand not evaluated if first is true
    cout << "\nTesting: x == 0 || 10/x > 1 (where x = 0)" << endl;
    if (x == 0 || 10 / x > 1) {
        cout << "Safe! Short-circuit prevented evaluation of 10/x" << endl;
    }
    
    // Demonstrating evaluation with side effects
    cout << "\n-- Side Effects Demo --" << endl;
    int counter = 0;
    
    auto increment = [&counter]() { 
        counter++; 
        cout << "  increment() called, counter = " << counter << endl;
        return true; 
    };
    
    cout << "false && increment():" << endl;
    bool result1 = false && increment();  // increment() NOT called
    cout << "  Result: " << boolalpha << result1 << ", Counter: " << counter << endl;
    
    cout << "\ntrue || increment():" << endl;
    bool result2 = true || increment();  // increment() NOT called
    cout << "  Result: " << result2 << ", Counter: " << counter << endl;
    
    cout << "\ntrue && increment():" << endl;
    bool result3 = true && increment();  // increment() IS called
    cout << "  Result: " << result3 << ", Counter: " << counter << endl;
}

// ============================================================
// Example 7: Bitwise Operators
// ============================================================
void example_bitwise_operators() {
    cout << "\n=== Example 7: Bitwise Operators ===" << endl;
    
    unsigned int a = 5, b = 3;  // a = 0101, b = 0011
    
    cout << "a = " << a << " (binary: " << bitset<4>(a) << ")" << endl;
    cout << "b = " << b << " (binary: " << bitset<4>(b) << ")" << endl;
    
    cout << "\n-- Bitwise AND (&) --" << endl;
    cout << "a & b = " << (a & b) << " (binary: " << bitset<4>(a & b) << ")" << endl;
    
    cout << "\n-- Bitwise OR (|) --" << endl;
    cout << "a | b = " << (a | b) << " (binary: " << bitset<4>(a | b) << ")" << endl;
    
    cout << "\n-- Bitwise XOR (^) --" << endl;
    cout << "a ^ b = " << (a ^ b) << " (binary: " << bitset<4>(a ^ b) << ")" << endl;
    
    cout << "\n-- Bitwise NOT (~) --" << endl;
    cout << "~a = " << (~a) << " (binary: " << bitset<32>(~a) << ")" << endl;
    
    cout << "\n-- Left Shift (<<) --" << endl;
    cout << "a << 1 = " << (a << 1) << " (binary: " << bitset<8>(a << 1) << ")" << endl;
    cout << "a << 2 = " << (a << 2) << " (binary: " << bitset<8>(a << 2) << ")" << endl;
    
    cout << "\n-- Right Shift (>>) --" << endl;
    unsigned int c = 20;  // 10100
    cout << "c = " << c << " (binary: " << bitset<8>(c) << ")" << endl;
    cout << "c >> 1 = " << (c >> 1) << " (binary: " << bitset<8>(c >> 1) << ")" << endl;
    cout << "c >> 2 = " << (c >> 2) << " (binary: " << bitset<8>(c >> 2) << ")" << endl;
}

// ============================================================
// Example 8: Bitwise Practical Applications
// ============================================================
void example_bitwise_applications() {
    cout << "\n=== Example 8: Bitwise Practical Applications ===" << endl;
    
    // Check odd/even
    cout << "-- Check Odd/Even --" << endl;
    for (int i = 1; i <= 5; i++) {
        cout << i << " is " << ((i & 1) ? "odd" : "even") << endl;
    }
    
    // Bit manipulation
    cout << "\n-- Bit Manipulation --" << endl;
    unsigned int flags = 0b0000;  // All flags off
    
    // Set bit at position 0
    flags |= (1 << 0);
    cout << "After setting bit 0: " << bitset<4>(flags) << endl;
    
    // Set bit at position 2
    flags |= (1 << 2);
    cout << "After setting bit 2: " << bitset<4>(flags) << endl;
    
    // Check if bit 1 is set
    cout << "Bit 1 is " << ((flags & (1 << 1)) ? "set" : "not set") << endl;
    
    // Toggle bit 2
    flags ^= (1 << 2);
    cout << "After toggling bit 2: " << bitset<4>(flags) << endl;
    
    // Clear bit 0
    flags &= ~(1 << 0);
    cout << "After clearing bit 0: " << bitset<4>(flags) << endl;
    
    // XOR swap
    cout << "\n-- XOR Swap (without temp variable) --" << endl;
    int x = 15, y = 27;
    cout << "Before: x = " << x << ", y = " << y << endl;
    x = x ^ y;
    y = x ^ y;
    x = x ^ y;
    cout << "After:  x = " << x << ", y = " << y << endl;
    
    // Power of 2 check
    cout << "\n-- Power of 2 Check --" << endl;
    for (int n : {1, 2, 3, 4, 5, 8, 16, 15}) {
        bool isPowerOf2 = (n > 0) && ((n & (n - 1)) == 0);
        cout << n << " is " << (isPowerOf2 ? "" : "not ") << "a power of 2" << endl;
    }
}

// ============================================================
// Example 9: Assignment Operators
// ============================================================
void example_assignment_operators() {
    cout << "\n=== Example 9: Assignment Operators ===" << endl;
    
    int x = 10;
    cout << "Initial x = " << x << endl;
    
    x += 5;
    cout << "x += 5  -> x = " << x << endl;
    
    x -= 3;
    cout << "x -= 3  -> x = " << x << endl;
    
    x *= 2;
    cout << "x *= 2  -> x = " << x << endl;
    
    x /= 4;
    cout << "x /= 4  -> x = " << x << endl;
    
    x %= 4;
    cout << "x %= 4  -> x = " << x << endl;
    
    // Bitwise compound assignment
    cout << "\n-- Bitwise Compound Assignment --" << endl;
    int y = 12;  // 1100
    cout << "y = " << y << " (" << bitset<4>(y) << ")" << endl;
    
    y &= 10;  // 1010
    cout << "y &= 10 -> y = " << y << " (" << bitset<4>(y) << ")" << endl;
    
    y |= 5;   // 0101
    cout << "y |= 5  -> y = " << y << " (" << bitset<4>(y) << ")" << endl;
    
    y ^= 3;   // 0011
    cout << "y ^= 3  -> y = " << y << " (" << bitset<4>(y) << ")" << endl;
    
    // Chained assignment
    cout << "\n-- Chained Assignment --" << endl;
    int a, b, c;
    a = b = c = 100;
    cout << "a = b = c = 100 -> a=" << a << ", b=" << b << ", c=" << c << endl;
}

// ============================================================
// Example 10: Increment and Decrement Operators
// ============================================================
void example_increment_decrement() {
    cout << "\n=== Example 10: Increment and Decrement Operators ===" << endl;
    
    int a = 5;
    cout << "Initial a = " << a << endl;
    
    cout << "\n-- Pre-increment vs Post-increment --" << endl;
    int b = 5, c = 5;
    cout << "++b = " << (++b) << " (b is now " << b << ")" << endl;  // 6, b=6
    cout << "c++ = " << (c++) << " (c is now " << c << ")" << endl;  // 5, c=6
    
    cout << "\n-- Pre-decrement vs Post-decrement --" << endl;
    int d = 10, e = 10;
    cout << "--d = " << (--d) << " (d is now " << d << ")" << endl;  // 9, d=9
    cout << "e-- = " << (e--) << " (e is now " << e << ")" << endl;  // 10, e=9
    
    cout << "\n-- In Expressions --" << endl;
    int x = 5;
    int result1 = ++x * 2;  // x becomes 6, then 6*2 = 12
    cout << "x=5; ++x * 2 = " << result1 << " (x is now " << x << ")" << endl;
    
    int y = 5;
    int result2 = y++ * 2;  // 5*2 = 10, then y becomes 6
    cout << "y=5; y++ * 2 = " << result2 << " (y is now " << y << ")" << endl;
    
    cout << "\n-- Multiple Operations --" << endl;
    int n = 1;
    cout << "n = 1" << endl;
    cout << "n++: " << n++ << " (n=" << n << ")" << endl;
    cout << "++n: " << ++n << " (n=" << n << ")" << endl;
    cout << "n--: " << n-- << " (n=" << n << ")" << endl;
    cout << "--n: " << --n << " (n=" << n << ")" << endl;
}

// ============================================================
// Example 11: Ternary Operator
// ============================================================
void example_ternary_operator() {
    cout << "\n=== Example 11: Ternary Operator ===" << endl;
    
    // Basic usage
    int a = 10, b = 20;
    int max_val = (a > b) ? a : b;
    cout << "max(" << a << ", " << b << ") = " << max_val << endl;
    
    // In output
    int score = 75;
    cout << "Score " << score << " is a " 
         << ((score >= 60) ? "pass" : "fail") << endl;
    
    // Finding min and max of three numbers
    int x = 15, y = 8, z = 23;
    int min3 = (x < y) ? ((x < z) ? x : z) : ((y < z) ? y : z);
    int max3 = (x > y) ? ((x > z) ? x : z) : ((y > z) ? y : z);
    cout << "Min of " << x << ", " << y << ", " << z << " = " << min3 << endl;
    cout << "Max of " << x << ", " << y << ", " << z << " = " << max3 << endl;
    
    // Absolute value
    int num = -42;
    int abs_val = (num < 0) ? -num : num;
    cout << "Absolute value of " << num << " = " << abs_val << endl;
    
    // Grade classification
    cout << "\n-- Grade Classification --" << endl;
    for (int s : {95, 85, 75, 65, 55}) {
        char grade = (s >= 90) ? 'A' : 
                     (s >= 80) ? 'B' : 
                     (s >= 70) ? 'C' : 
                     (s >= 60) ? 'D' : 'F';
        cout << "Score " << s << " -> Grade " << grade << endl;
    }
    
    // Return type must match
    cout << "\n-- Type Consistency --" << endl;
    bool condition = true;
    auto result = condition ? 1 : 2;          // int
    auto result2 = condition ? 1.0 : 2;       // double (promotion)
    auto result3 = condition ? "yes" : "no";  // const char*
    cout << "result: " << result << ", result2: " << result2 
         << ", result3: " << result3 << endl;
}

// ============================================================
// Example 12: sizeof Operator
// ============================================================
void example_sizeof_operator() {
    cout << "\n=== Example 12: sizeof Operator ===" << endl;
    
    cout << "-- Fundamental Types --" << endl;
    cout << "sizeof(char):        " << sizeof(char) << " bytes" << endl;
    cout << "sizeof(short):       " << sizeof(short) << " bytes" << endl;
    cout << "sizeof(int):         " << sizeof(int) << " bytes" << endl;
    cout << "sizeof(long):        " << sizeof(long) << " bytes" << endl;
    cout << "sizeof(long long):   " << sizeof(long long) << " bytes" << endl;
    cout << "sizeof(float):       " << sizeof(float) << " bytes" << endl;
    cout << "sizeof(double):      " << sizeof(double) << " bytes" << endl;
    cout << "sizeof(long double): " << sizeof(long double) << " bytes" << endl;
    cout << "sizeof(bool):        " << sizeof(bool) << " bytes" << endl;
    
    cout << "\n-- Pointers --" << endl;
    cout << "sizeof(int*):        " << sizeof(int*) << " bytes" << endl;
    cout << "sizeof(double*):     " << sizeof(double*) << " bytes" << endl;
    cout << "sizeof(char*):       " << sizeof(char*) << " bytes" << endl;
    
    cout << "\n-- Arrays --" << endl;
    int arr[10];
    cout << "int arr[10]" << endl;
    cout << "  sizeof(arr):          " << sizeof(arr) << " bytes" << endl;
    cout << "  sizeof(arr[0]):       " << sizeof(arr[0]) << " bytes" << endl;
    cout << "  Number of elements:   " << sizeof(arr) / sizeof(arr[0]) << endl;
    
    double darr[5];
    cout << "\ndouble darr[5]" << endl;
    cout << "  sizeof(darr):         " << sizeof(darr) << " bytes" << endl;
    cout << "  Number of elements:   " << sizeof(darr) / sizeof(darr[0]) << endl;
    
    cout << "\n-- Expressions --" << endl;
    cout << "sizeof(5 + 3):     " << sizeof(5 + 3) << " bytes (int)" << endl;
    cout << "sizeof(5 + 3.0):   " << sizeof(5 + 3.0) << " bytes (double)" << endl;
    cout << "sizeof('A' + 1):   " << sizeof('A' + 1) << " bytes (int)" << endl;
}

// ============================================================
// Example 13: Operator Precedence
// ============================================================
void example_operator_precedence() {
    cout << "\n=== Example 13: Operator Precedence ===" << endl;
    
    cout << "-- Arithmetic Precedence --" << endl;
    int result1 = 2 + 3 * 4;        // 14, not 20
    int result2 = (2 + 3) * 4;      // 20
    cout << "2 + 3 * 4 = " << result1 << " (* before +)" << endl;
    cout << "(2 + 3) * 4 = " << result2 << " (parentheses override)" << endl;
    
    cout << "\n-- Complex Expression --" << endl;
    int a = 10 - 5 - 2;             // 3, left to right
    int b = 2 * 3 + 4 / 2;          // 6 + 2 = 8
    cout << "10 - 5 - 2 = " << a << " (left to right)" << endl;
    cout << "2 * 3 + 4 / 2 = " << b << endl;
    
    cout << "\n-- Relational vs Bitwise --" << endl;
    // Common mistake: & has lower precedence than ==
    int x = 5, y = 3;
    // x & y == 0 is parsed as x & (y == 0) = 5 & false = 5 & 0 = 0
    cout << "x & y == 0 (without parens): " << (x & y == 0) << endl;
    cout << "(x & y) == 0 (with parens): " << ((x & y) == 0) << endl;
    
    cout << "\n-- Logical Operators --" << endl;
    // && has higher precedence than ||
    bool r1 = true || false && false;   // true || (false && false) = true
    bool r2 = (true || false) && false; // true && false = false
    cout << boolalpha;
    cout << "true || false && false = " << r1 << endl;
    cout << "(true || false) && false = " << r2 << endl;
    
    cout << "\n-- Assignment Precedence --" << endl;
    // Assignment is right-to-left
    int p, q, r;
    p = q = r = 10;  // r=10, q=r, p=q
    cout << "p = q = r = 10: p=" << p << ", q=" << q << ", r=" << r << endl;
    
    cout << "\n-- Ternary with Arithmetic --" << endl;
    int val = 5;
    int result = val > 3 ? val * 2 : val + 2;  // ? : has low precedence
    cout << "val=5; val > 3 ? val * 2 : val + 2 = " << result << endl;
}

// ============================================================
// Example 14: Type Casting
// ============================================================
void example_type_casting() {
    cout << "\n=== Example 14: Type Casting ===" << endl;
    
    cout << "-- Implicit Casting (Promotion) --" << endl;
    int i = 10;
    double d = i;  // int to double (safe)
    cout << "int " << i << " -> double " << d << endl;
    
    char c = 'A';
    int ascii = c;  // char to int
    cout << "char '" << c << "' -> int " << ascii << endl;
    
    cout << "\n-- C-Style Casting --" << endl;
    double pi = 3.14159;
    int truncated = (int)pi;  // C-style cast
    cout << "double " << pi << " -> int " << truncated << endl;
    
    cout << "\n-- static_cast --" << endl;
    double value = 7.8;
    int converted = static_cast<int>(value);
    cout << "static_cast<int>(" << value << ") = " << converted << endl;
    
    // Converting between related types
    float f = 3.5f;
    double df = static_cast<double>(f);
    cout << "float " << f << " -> double " << fixed << setprecision(1) << df << endl;
    
    cout << "\n-- Integer Division Fix --" << endl;
    int num = 7, denom = 3;
    cout << "7 / 3 (int) = " << (num / denom) << endl;
    cout << "7 / 3 (with cast) = " << (static_cast<double>(num) / denom) << endl;
    
    cout << "\n-- Character/Integer Conversion --" << endl;
    for (char ch = 'a'; ch <= 'e'; ch++) {
        cout << "'" << ch << "' = " << static_cast<int>(ch) << endl;
    }
    
    // Number to character
    for (int n = 0; n <= 5; n++) {
        char digit = static_cast<char>('0' + n);
        cout << "Digit " << n << " as char: '" << digit << "'" << endl;
    }
}

// ============================================================
// Main Function - Run All Examples
// ============================================================
int main() {
    cout << "╔════════════════════════════════════════════════════════════╗" << endl;
    cout << "║           C++ OPERATORS - COMPREHENSIVE EXAMPLES           ║" << endl;
    cout << "╚════════════════════════════════════════════════════════════╝" << endl;
    
    example_arithmetic_operators();
    example_modulus_applications();
    example_relational_operators();
    example_float_comparison();
    example_logical_operators();
    example_short_circuit();
    example_bitwise_operators();
    example_bitwise_applications();
    example_assignment_operators();
    example_increment_decrement();
    example_ternary_operator();
    example_sizeof_operator();
    example_operator_precedence();
    example_type_casting();
    
    cout << "\n╔════════════════════════════════════════════════════════════╗" << endl;
    cout << "║                    ALL EXAMPLES COMPLETE                    ║" << endl;
    cout << "╚════════════════════════════════════════════════════════════╝" << endl;
    
    return 0;
}
Examples - C++ Tutorial | DeepML