How can you perform arithmetic with characters in C++?

0164

In C++, you can perform arithmetic operations with characters by treating them as their corresponding ASCII values. Each character has an integer value associated with it, which you can use in arithmetic operations. Here’s an example:

#include <iostream>

int main() {
    char a = 'A'; // ASCII value 65
    char b = 'B'; // ASCII value 66

    // Performing arithmetic operations
    int sum = a + b; // 65 + 66 = 131
    int difference = b - a; // 66 - 65 = 1
    int product = a * 2; // 65 * 2 = 130
    int division = b / 2; // 66 / 2 = 33

    std::cout << "Sum: " << sum << std::endl;
    std::cout << "Difference: " << difference << std::endl;
    std::cout << "Product: " << product << std::endl;
    std::cout << "Division: " << division << std::endl;

    return 0;
}

In this code, we perform addition, subtraction, multiplication, and division using characters by leveraging their ASCII values. The results are printed as integers.

0 Comments

no data
Be the first to share your comment!