Implement C++ Operators

C++C++Beginner
Practice Now

Introduction

In this lab, you will learn how to implement various C++ operators, including basic math operations, increment/decrement, relational and logical operators, bitwise operations, compound assignment, order of operations, and the ternary conditional operator. These fundamental operators are essential for performing arithmetic, making comparisons, and manipulating data in C++ programming. Through a series of practical exercises, you will gain a solid understanding of how to effectively utilize these operators to build more complex and efficient C++ applications.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL cpp(("C++")) -.-> cpp/ControlFlowGroup(["Control Flow"]) cpp(("C++")) -.-> cpp/IOandFileHandlingGroup(["I/O and File Handling"]) cpp(("C++")) -.-> cpp/StandardLibraryGroup(["Standard Library"]) cpp(("C++")) -.-> cpp/BasicsGroup(["Basics"]) cpp/BasicsGroup -.-> cpp/operators("Operators") cpp/ControlFlowGroup -.-> cpp/conditions("Conditions") cpp/ControlFlowGroup -.-> cpp/if_else("If...Else") cpp/IOandFileHandlingGroup -.-> cpp/output("Output") cpp/StandardLibraryGroup -.-> cpp/math("Math") subgraph Lab Skills cpp/operators -.-> lab-446084{{"Implement C++ Operators"}} cpp/conditions -.-> lab-446084{{"Implement C++ Operators"}} cpp/if_else -.-> lab-446084{{"Implement C++ Operators"}} cpp/output -.-> lab-446084{{"Implement C++ Operators"}} cpp/math -.-> lab-446084{{"Implement C++ Operators"}} end

Perform Basic Math Operations (+, -, *, /, %)

In this step, you'll learn how to perform basic mathematical operations in C++. Mathematical operations are fundamental to programming and allow you to manipulate numeric values using standard arithmetic operators.

Open the WebIDE and create a new file called math_operations.cpp in the ~/project directory:

touch ~/project/math_operations.cpp

Add the following code to the math_operations.cpp file:

#include <iostream>

int main() {
    // Declare variables for mathematical operations
    int a = 10;
    int b = 3;

    // Addition (+)
    int sum = a + b;
    std::cout << "Addition: " << a << " + " << b << " = " << sum << std::endl;

    // Subtraction (-)
    int difference = a - b;
    std::cout << "Subtraction: " << a << " - " << b << " = " << difference << std::endl;

    // Multiplication (*)
    int product = a * b;
    std::cout << "Multiplication: " << a << " * " << b << " = " << product << std::endl;

    // Division (/)
    int quotient = a / b;
    std::cout << "Division: " << a << " / " << b << " = " << quotient << std::endl;

    // Modulus (%) - Remainder of division
    int remainder = a % b;
    std::cout << "Modulus: " << a << " % " << b << " = " << remainder << std::endl;

    return 0;
}

Compile and run the program:

g++ math_operations.cpp -o math_operations
./math_operations

Example output:

Addition: 10 + 3 = 13
Subtraction: 10 - 3 = 7
Multiplication: 10 * 3 = 30
Division: 10 / 3 = 3
Modulus: 10 % 3 = 1

Let's break down the mathematical operators:

  1. + (Addition): Adds two numbers together. For example, 5 + 3 would result in 8.
  2. - (Subtraction): Subtracts the second number from the first. For example, 10 - 4 would result in 6.
  3. * (Multiplication): Multiplies two numbers. For example, 6 * 7 would result in 42.
  4. / (Division): Divides the first number by the second. When both numbers are integers, this results in integer division, meaning the decimal part is truncated. For example, 10 / 3 would result in 3.
  5. % (Modulus): Returns the remainder of the division. For example, 10 % 3 would result in 1 because the remainder of 10 divided by 3 is 1.

Some important notes:

  • Integer division truncates the decimal part. For example, 5 / 2 will result in 2, not 2.5.
  • The modulus operator works only with integer types. You cannot use it with floating-point numbers (like float or double).
  • Always be careful with division by zero, which causes runtime errors. Your program will crash if you attempt to divide any number by zero.

Use Pre and Post Increment/Decrement (++i, i++)

In this step, you'll learn about increment and decrement operators in C++. These operators allow you to increase or decrease a variable's value by 1, with subtle differences between pre-increment and post-increment.

Open the WebIDE and create a new file called increment_decrement.cpp in the ~/project directory:

touch ~/project/increment_decrement.cpp

Add the following code to the increment_decrement.cpp file:

#include <iostream>

int main() {
    // Pre-increment (++i)
    int a = 5;
    std::cout << "Original value of a: " << a << std::endl;

    // Pre-increment: increment happens before the value is used
    std::cout << "Pre-increment (++a): " << ++a << std::endl;
    std::cout << "Value after pre-increment: " << a << std::endl;

    // Post-increment (i++)
    int b = 5;
    std::cout << "\nOriginal value of b: " << b << std::endl;

    // Post-increment: increment happens after the value is used
    std::cout << "Post-increment (b++): " << b++ << std::endl;
    std::cout << "Value after post-increment: " << b << std::endl;

    // Decrement operators work similarly
    int c = 5;
    std::cout << "\nPre-decrement (--c): " << --c << std::endl;

    int d = 5;
    std::cout << "Post-decrement (d--): " << d-- << std::endl;
    std::cout << "Value after post-decrement: " << d << std::endl;

    return 0;
}

Compile and run the program:

g++ increment_decrement.cpp -o increment_decrement
./increment_decrement

Example output:

Original value of a: 5
Pre-increment (++a): 6
Value after pre-increment: 6

Original value of b: 5
Post-increment (b++): 5
Value after post-increment: 6

Pre-decrement (--c): 4
Post-decrement (d--): 5
Value after post-decrement: 4

Key differences:

  • Pre-increment ++i: Increments the value before it's used in the expression. In the code example, ++a first increments a to 6, and then the value 6 is used in the cout statement.
  • Post-increment i++: Uses the current value in the expression first, and then increments the value. In the code example, b++ first uses the current value of b which is 5 in the cout statement, and then increments b to 6.

The same principles apply to decrement operators --i and i--, where --i decrements first and then uses the value, and i-- uses the value first and then decrements.

Important notes:

  • Pre-increment changes the value before it's used in an expression, meaning that the incremented value is immediately available for use.
  • Post-increment uses the original value first, and then increments. This means that you get the original value in the current statement and the incremented value in the next.
  • These operators are commonly used in loops (like for loops) and complex expressions where you want to modify a variable while also using its value.
  • When using these operators, especially in complex expressions, it's important to keep in mind whether you need the pre- or post- version to get the intended behavior.

Compare Values Using Relational Operators (<, >, ==, !=)

In this step, you'll learn about relational operators in C++. These operators help you compare values and determine relationships between different numbers or variables.

Open the WebIDE and create a new file called relational_operators.cpp in the ~/project directory:

touch ~/project/relational_operators.cpp

Add the following code to the relational_operators.cpp file:

#include <iostream>

int main() {
    int a = 10;
    int b = 5;
    int c = 10;

    // Less than (<)
    std::cout << "Less than (<):" << std::endl;
    std::cout << a << " < " << b << " is " << (a < b) << std::endl;
    std::cout << b << " < " << a << " is " << (b < a) << std::endl;

    // Greater than (>)
    std::cout << "\nGreater than (>):" << std::endl;
    std::cout << a << " > " << b << " is " << (a > b) << std::endl;
    std::cout << b << " > " << a << " is " << (b > a) << std::endl;

    // Equal to (==)
    std::cout << "\nEqual to (==):" << std::endl;
    std::cout << a << " == " << b << " is " << (a == b) << std::endl;
    std::cout << a << " == " << c << " is " << (a == c) << std::endl;

    // Not equal to (!=)
    std::cout << "\nNot equal to (!=):" << std::endl;
    std::cout << a << " != " << b << " is " << (a != b) << std::endl;
    std::cout << a << " != " << c << " is " << (a != c) << std::endl;

    return 0;
}

Compile and run the program:

g++ relational_operators.cpp -o relational_operators
./relational_operators

Example output:

Less than (<):
10 < 5 is 0
5 < 10 is 1

Greater than (>):
10 > 5 is 1
5 > 10 is 0

Equal to (==):
10 == 5 is 0
10 == 10 is 1

Not equal to (!=):
10 != 5 is 1
10 != 10 is 0

Key points about relational operators:

  • < (Less than): Checks if the left value is less than the right value. For example, 5 < 10 is true (returns 1), while 10 < 5 is false (returns 0).
  • > (Greater than): Checks if the left value is greater than the right value. For example, 10 > 5 is true (returns 1), while 5 > 10 is false (returns 0).
  • == (Equal to): Checks if two values are exactly equal. For example, 5 == 5 is true (returns 1), while 5 == 6 is false (returns 0).
  • != (Not equal to): Checks if two values are not equal. For example, 5 != 6 is true (returns 1), while 5 != 5 is false (returns 0).
  • These operators return 1 (true) or 0 (false). In C++, 1 represents true and 0 represents false. These values can be used in conditional statements.

Important notes:

  • Relational operators are fundamental for creating conditional statements, allowing your program to make decisions based on comparisons.
  • They always return a boolean value, which is represented by an integer in C++ (1 for true, 0 for false).
  • These operators are commonly used in if statements, while loops, and for loops to control the flow of execution.

Combine Conditions with Logical AND (&&) and OR (||)

In this step, you'll learn how to combine multiple conditions using logical AND (&&) and OR (||) operators in C++. These operators help you create more complex conditional statements by evaluating multiple conditions.

Open the WebIDE and create a new file called logical_operators.cpp in the ~/project directory:

touch ~/project/logical_operators.cpp

Add the following code to the logical_operators.cpp file:

#include <iostream>

int main() {
    int x = 10;
    int y = 5;
    int z = 15;

    // Logical AND (&&) operator
    std::cout << "Logical AND (&&) operator:" << std::endl;

    // Both conditions must be true
    if (x > y && x < z) {
        std::cout << "x is greater than y AND less than z" << std::endl;
    }

    if (x > 20 && y < 10) {
        std::cout << "This will not be printed" << std::endl;
    }

    // Logical OR (||) operator
    std::cout << "\nLogical OR (||) operator:" << std::endl;

    // At least one condition must be true
    if (x > 20 || y < 10) {
        std::cout << "At least one condition is true" << std::endl;
    }

    if (x > 20 || z < 20) {
        std::cout << "Another true condition" << std::endl;
    }

    // Combining AND and OR
    std::cout << "\nCombining AND and OR:" << std::endl;

    if ((x > y && y < z) || x == 10) {
        std::cout << "Complex condition is true" << std::endl;
    }

    return 0;
}

Compile and run the program:

g++ logical_operators.cpp -o logical_operators
./logical_operators

Example output:

Logical AND (&&) operator:
x is greater than y AND less than z

Logical OR (||) operator:
At least one condition is true
Another true condition

Combining AND and OR:
Complex condition is true

Key points about logical operators:

  • && (AND): Both conditions connected by && must be true for the entire expression to be true. If any one of the conditions is false, the whole expression is evaluated as false. In the code, x > y && x < z is true because x > y (10 > 5) and x < z (10 < 15) are both true.
  • || (OR): At least one of the conditions connected by || must be true for the entire expression to be true. If all conditions are false, the whole expression is evaluated as false. In the code, x > 20 || y < 10 is true because y < 10 (5 < 10) is true.
  • You can combine multiple conditions using parentheses to control the order of evaluation. This makes your complex expressions easier to read and understand.
  • These operators are extremely useful for creating complex decision-making logic within conditional statements.

Important notes:

  • Logical operators are often used in if statements, while loops, and other control flow structures to make your programs more versatile.
  • They help create more sophisticated conditional checks by allowing you to check multiple criteria simultaneously.
  • Short-circuit evaluation:
    • For &&, if the first condition is false, the second condition is not evaluated because the entire expression will be false no matter what the second condition is. This optimization can improve performance.
    • For ||, if the first condition is true, the second condition is not evaluated because the entire expression will be true.

Apply Bitwise Operations for Binary Manipulation

In this step, you'll learn about bitwise operators in C++. These operators work directly on the binary representation of integers, allowing you to manipulate individual bits.

Open the WebIDE and create a new file called bitwise_operations.cpp in the ~/project directory:

touch ~/project/bitwise_operations.cpp

Add the following code to the bitwise_operations.cpp file:

#include <iostream>
#include <bitset>

int main() {
    // Binary representation of numbers
    unsigned int a = 5;   // 0101 in binary
    unsigned int b = 3;   // 0011 in binary

    // Bitwise AND (&)
    std::cout << "Bitwise AND (&):" << std::endl;
    std::cout << "a = " << std::bitset<4>(a) << " (5 in decimal)" << std::endl;
    std::cout << "b = " << std::bitset<4>(b) << " (3 in decimal)" << std::endl;
    unsigned int and_result = a & b;
    std::cout << "a & b = " << std::bitset<4>(and_result)
              << " (" << and_result << " in decimal)" << std::endl;

    // Bitwise OR (|)
    std::cout << "\nBitwise OR (|):" << std::endl;
    unsigned int or_result = a | b;
    std::cout << "a | b = " << std::bitset<4>(or_result)
              << " (" << or_result << " in decimal)" << std::endl;

    // Bitwise XOR (^)
    std::cout << "\nBitwise XOR (^):" << std::endl;
    unsigned int xor_result = a ^ b;
    std::cout << "a ^ b = " << std::bitset<4>(xor_result)
              << " (" << xor_result << " in decimal)" << std::endl;

    // Bitwise NOT (~)
    std::cout << "\nBitwise NOT (~):" << std::endl;
    unsigned int not_result = ~a;
    std::cout << "~a = " << std::bitset<32>(not_result)
              << " (" << not_result << " in decimal)" << std::endl;

    // Left shift (<<)
    std::cout << "\nLeft Shift (<<):" << std::endl;
    unsigned int left_shift = a << 2;
    std::cout << "a << 2 = " << std::bitset<8>(left_shift)
              << " (" << left_shift << " in decimal)" << std::endl;

    // Right shift (>>)
    std::cout << "\nRight Shift (>>):" << std::endl;
    unsigned int right_shift = a >> 1;
    std::cout << "a >> 1 = " << std::bitset<4>(right_shift)
              << " (" << right_shift << " in decimal)" << std::endl;

    return 0;
}

Compile and run the program:

g++ bitwise_operations.cpp -o bitwise_operations
./bitwise_operations

Example output:

Bitwise AND (&):
a = 0101 (5 in decimal)
b = 0011 (3 in decimal)
a & b = 0001 (1 in decimal)

Bitwise OR (|):
a | b = 0111 (7 in decimal)

Bitwise XOR (^):
a ^ b = 0110 (6 in decimal)

Bitwise NOT (~):
~a = 11111111111111111111111111111010 (4294967290 in decimal)

Left Shift (<<):
a << 2 = 00010100 (20 in decimal)

Right Shift (>>):
a >> 1 = 0010 (2 in decimal)

Key points about bitwise operators:

  • & (AND): Compares corresponding bits of two numbers. If both bits are 1, the resulting bit is 1; otherwise, it is 0. In the code example, 5 & 3 (binary 0101 & 0011) results in 0001 which is 1 in decimal.
  • | (OR): Compares corresponding bits of two numbers. If at least one of the bits is 1, the resulting bit is 1; otherwise, it is 0. In the example, 5 | 3 (binary 0101 | 0011) results in 0111 which is 7 in decimal.
  • ^ (XOR): Compares corresponding bits of two numbers. If the bits are different, the resulting bit is 1; otherwise, it is 0. In the example, 5 ^ 3 (binary 0101 ^ 0011) results in 0110 which is 6 in decimal.
  • ~ (NOT): Inverts all the bits of a number. If a bit is 1, it becomes 0, and vice versa. Note that the output ~a is 11111111111111111111111111111010 which is the binary representation of the result when the number is treated as a 32-bit unsigned integer.
  • << (Left Shift): Shifts the bits of a number to the left by a specified number of positions. It effectively multiplies the number by 2 for each shift. In the example, 5 << 2 (binary 0101 << 2) shifts the bits to become 010100 which is 20 in decimal.
  • >> (Right Shift): Shifts the bits of a number to the right by a specified number of positions. It effectively divides the number by 2 for each shift. In the example, 5 >> 1 (binary 0101 >> 1) shifts the bits to become 0010 which is 2 in decimal.

Important notes:

  • Bitwise operations work directly on the binary representations of integers, allowing for low-level manipulation and optimization.
  • They are commonly used in embedded systems, graphics programming, and scenarios where you need to set, clear, or test individual bits within a value.
  • Be careful with signed and unsigned integers, as right shift behavior can vary (arithmetic vs. logical shift).
  • Using std::bitset helps in visualizing how these operations work at the bit level.

Use Compound Assignment Operators (+=, -=, *=)

In this step, you'll learn about compound assignment operators in C++. These operators combine an arithmetic operation with assignment, making your code more concise and readable.

Open the WebIDE and create a new file called compound_operators.cpp in the ~/project directory:

touch ~/project/compound_operators.cpp

Add the following code to the compound_operators.cpp file:

#include <iostream>

int main() {
    // Initialize variables
    int x = 10;
    int y = 5;

    // Addition assignment (+=)
    std::cout << "Addition Assignment (+=):" << std::endl;
    std::cout << "Initial x: " << x << std::endl;
    x += 3;  // Equivalent to x = x + 3
    std::cout << "x += 3: " << x << std::endl;

    // Subtraction assignment (-=)
    std::cout << "\nSubtraction Assignment (-=):" << std::endl;
    std::cout << "Initial y: " << y << std::endl;
    y -= 2;  // Equivalent to y = y - 2
    std::cout << "y -= 2: " << y << std::endl;

    // Multiplication assignment (*=)
    std::cout << "\nMultiplication Assignment (*=):" << std::endl;
    int z = 4;
    std::cout << "Initial z: " << z << std::endl;
    z *= 3;  // Equivalent to z = z * 3
    std::cout << "z *= 3: " << z << std::endl;

    // Division assignment (/=)
    std::cout << "\nDivision Assignment (/=):" << std::endl;
    int a = 15;
    std::cout << "Initial a: " << a << std::endl;
    a /= 3;  // Equivalent to a = a / 3
    std::cout << "a /= 3: " << a << std::endl;

    // Modulus assignment (%=)
    std::cout << "\nModulus Assignment (%=):" << std::endl;
    int b = 17;
    std::cout << "Initial b: " << b << std::endl;
    b %= 5;  // Equivalent to b = b % 5
    std::cout << "b %= 5: " << b << std::endl;

    return 0;
}

Compile and run the program:

g++ compound_operators.cpp -o compound_operators
./compound_operators

Example output:

Addition Assignment (+=):
Initial x: 10
x += 3: 13

Subtraction Assignment (-=):
Initial y: 5
y -= 2: 3

Multiplication Assignment (*=):
Initial z: 4
z *= 3: 12

Division Assignment (/=):
Initial a: 15
a /= 3: 5

Modulus Assignment (%=):
Initial b: 17
b %= 5: 2

Key points about compound assignment operators:

  • += (Add and assign): Adds the right operand to the left operand and assigns the result to the left operand. x += 3 is equivalent to x = x + 3.
  • -= (Subtract and assign): Subtracts the right operand from the left operand and assigns the result to the left operand. y -= 2 is equivalent to y = y - 2.
  • *= (Multiply and assign): Multiplies the left operand by the right operand and assigns the result to the left operand. z *= 3 is equivalent to z = z * 3.
  • /= (Divide and assign): Divides the left operand by the right operand and assigns the result to the left operand. a /= 3 is equivalent to a = a / 3.
  • %= (Modulus and assign): Computes the modulus of the left operand by the right operand and assigns the result to the left operand. b %= 5 is equivalent to b = b % 5.

Important notes:

  • Compound assignment operators make your code more concise and easier to read by combining an operation and an assignment in one step.
  • They work with all basic arithmetic operations (+, -, *, /, %)
  • They can help reduce typing, make the code shorter, and potentially improve performance.

Understand Order of Operations with Multiple Operators

In this step, you'll learn about the order of operations in C++, often remembered by the acronym PEMDAS (Parentheses, Exponents, Multiplication and Division, Addition and Subtraction). Understanding this order is crucial for writing correct mathematical expressions.

Open the WebIDE and create a new file called order_of_operations.cpp in the ~/project directory:

touch ~/project/order_of_operations.cpp

Add the following code to the order_of_operations.cpp file:

#include <iostream>

int main() {
    // Basic order of operations demonstration
    int a = 10;
    int b = 5;
    int c = 3;

    // Multiplication before addition
    std::cout << "Multiplication before Addition:" << std::endl;
    int result1 = a + b * c;
    std::cout << "a + b * c = " << result1 << std::endl;

    // Parentheses change the order of operations
    std::cout << "\nParentheses change order:" << std::endl;
    int result2 = (a + b) * c;
    std::cout << "(a + b) * c = " << result2 << std::endl;

    // Complex expression with multiple operators
    std::cout << "\nComplex Expression:" << std::endl;
    int x = 4;
    int y = 2;
    int z = 3;

    int complex_result = x + y * z - (x / y);
    std::cout << "x + y * z - (x / y) = " << complex_result << std::endl;

    // Demonstrating precedence with increment and multiplication
    std::cout << "\nIncrement and Multiplication:" << std::endl;
    int m = 3;
    int n = 2;
    int precedence_result = m++ * n;
    std::cout << "m++ * n = " << precedence_result << std::endl;
    std::cout << "m after operation = " << m << std::endl;

    return 0;
}

Compile and run the program:

g++ order_of_operations.cpp -o order_of_operations
./order_of_operations

Example output:

Multiplication before Addition:
a + b * c = 25

Parentheses change order:
(a + b) * c = 45

Complex Expression:
x + y * z - (x / y) = 8

Increment and Multiplication:
m++ * n = 6
m after operation = 4

Key points about order of operations:

  • The order of operations, also known as operator precedence, determines how an expression is evaluated. C++ follows the rules of mathematics for this.
  • PEMDAS/BODMAS: This is a common mnemonic to remember the order:
    • Parentheses / Brackets: Expressions within parentheses or brackets are evaluated first.
    • Exponents / Orders: Exponents or orders (like square roots) are evaluated next, although C++ doesn't have a built-in exponent operator, this step refers to operations like pow().
    • MD Multiplication and Division: Multiplication and division have the same precedence and are evaluated from left to right.
    • AS Addition and Subtraction: Addition and subtraction have the same precedence and are evaluated from left to right.
  • In the code, int result1 = a + b * c; evaluates to 10 + (5 * 3) which is 10 + 15 = 25 because multiplication has a higher precedence than addition.
  • Parentheses can override the default order of operations, making the expression int result2 = (a + b) * c; evaluates to (10 + 5) * 3 which is 15 * 3 = 45, as the expression inside the parentheses is calculated first.
  • The increment/decrement operators have specific precedence rules that can sometimes be confusing. The post-increment operator m++ used in the code, the original value of m is used first in the multiplication m * n and only afterwards the variable m is incremented.
  • In the complex expression x + y * z - (x / y), multiplication and division are done before addition and subtraction. The parentheses enforce that integer division x / y is done first.
  • Always use parentheses to make your intent clear, especially when you have complicated expressions. This not only makes the code easier to read but also ensures that the expression is evaluated exactly as intended.

Important notes:

  • PEMDAS/BODMAS helps predict how expressions will be evaluated, but keep in mind that C++ doesn't have a built-in exponent operator.
  • When in doubt, use parentheses to explicitly define the order. This can make your code clearer and prevent errors that might occur due to misunderstood precedence.
  • Some operators have equal precedence and are evaluated from left to right. For example, if you have a - b + c, subtraction will be done before addition.
  • Be especially careful when combining multiple operators in a single expression without using parentheses. It can lead to subtle bugs if you do not properly understand the operator precedence.

Practice with the Ternary Conditional Operator

In this step, you'll learn about the ternary conditional operator, a compact way to write simple if-else statements in a single line. This operator provides a concise method for making decisions in your code.

Open the WebIDE and create a new file called ternary_operator.cpp in the ~/project directory:

touch ~/project/ternary_operator.cpp

Add the following code to the ternary_operator.cpp file:

#include <iostream>

int main() {
    // Basic ternary operator syntax
    // condition ? value_if_true : value_if_false

    // Simple comparison
    int x = 10;
    int y = 5;

    // Determine the larger number
    int max_value = (x > y) ? x : y;
    std::cout << "Larger value: " << max_value << std::endl;

    // Check if a number is even or odd
    int number = 7;
    std::string result = (number % 2 == 0) ? "Even" : "Odd";
    std::cout << number << " is " << result << std::endl;

    // Nested ternary operator
    int a = 15;
    std::string category = (a < 10) ? "Small"
                         : (a < 20) ? "Medium"
                         : "Large";
    std::cout << "Category: " << category << std::endl;

    // Ternary operator with function calls
    int abs_value = (x < 0) ? -x : x;
    std::cout << "Absolute value of x: " << abs_value << std::endl;

    // Ternary operator in output
    std::cout << "Is x greater than y? "
              << ((x > y) ? "Yes" : "No") << std::endl;

    return 0;
}

Compile and run the program:

g++ ternary_operator.cpp -o ternary_operator
./ternary_operator

Example output:

Larger value: 10
7 is Odd
Category: Medium
Absolute value of x: 10
Is x greater than y? Yes

Key points about the ternary operator:

  • Syntax: condition ? value_if_true : value_if_false. It's a shorthand way of writing an if-else statement in a single line.
  • The condition is evaluated. If it's true, the expression returns value_if_true; otherwise, it returns value_if_false.
  • In the code, int max_value = (x > y) ? x : y; determines the larger number between x and y. If x is greater than y it will assign x to max_value, otherwise it will assign y. Because x is 10 and y is 5, max_value becomes 10.
  • The expression std::string result = (number % 2 == 0) ? "Even" : "Odd"; uses the modulus operator % to check if the number is even or odd. The result is either "Even" or "Odd", depending on the outcome of the check, and is assigned to the string variable result.
  • Ternary operators can be nested, but doing so can quickly make the code difficult to read. In the example, the nested ternary operator assigns the string "Small", "Medium", or "Large" to the variable category depending on the value of the integer a.
  • The example with int abs_value = (x < 0) ? -x : x; demonstrates how the ternary operator can be used to get the absolute value of x. If x is negative, it will negate x which is equivalent to converting it to absolute value. Otherwise it will return x as is.
  • The final example shows how the result of a ternary operator can be printed directly: std::cout << "Is x greater than y? " << ((x > y) ? "Yes" : "No") << std::endl;

Important notes:

  • Use sparingly to maintain code readability. Overuse of ternary operators, especially nested ones, can make the code hard to follow.
  • Can become hard to read if too complex. Complex decisions should often be expressed with full if-else blocks.
  • Primarily used for simple, straightforward conditions where one of two values needs to be returned or assigned.

Summary

In this lab, you learned how to perform basic mathematical operations in C++, including addition, subtraction, multiplication, division, and modulus. You also explored the use of pre- and post-increment/decrement operators, understanding the subtle differences between them. Additionally, you learned about relational and logical operators to compare and combine values effectively. Furthermore, you practiced bitwise operations for binary manipulation and compound assignment operators to simplify and condense arithmetic operations with assignment. Finally, you gained an understanding of the order of operations with multiple operators and used the ternary conditional operator for concise conditional statements. These fundamental concepts are essential for building robust and efficient C++ programs. By mastering these basic operators, you will be well-equipped to handle more complex coding challenges.