Open In App

Character Arithmetic in C++

Last Updated : 09 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Character arithmetic in C++ involves performing mathematical operations on characters. In C++, characters are represented using the char data type, which is essentially an integer type that stores ASCII values. In this article, we will discuss character arithmetic and how to perform character arithmetic in C++.

What is Character Arithmetic in C++?

Character arithmetic involves performing arithmetic operations on characters based on their ASCII values. So when some operations are performed on the characters, they are automatically promoted to integers. This process is called integer promotion. Due to this, we can perform some common mathematical operations on the character type variables.

Following are some common character arithmetic operations:

  • Increment and Decrement: The increment (++) operator increments the value, while the decrement (–) operator decrements it by one.
  • Addition and Subtraction: We can add or subtract integers to/from characters, and the result will be a new character based on the modified ASCII value.
  • Multiplication and Division: While multiplication and division may not have intuitive meanings when applied to characters, they still operate based on ASCII values. This operation is less commonly used due to less relevance.

Note: While doing character arithmetic, keep in mind the size of the character type is 1 byte so it can only store the values from 0 to 255.

Example of Character Arithmetic in C++

The below example demonstrates the common arithmetic operations on characters.

C++




// C++ program to demonstrate charcater arithmetic
  
#include <iostream>
using namespace std;
  
int main()
{
    char charA = 'A';
  
    // Increment
    cout << "Original character: " << charA << endl;
    charA++;
    cout << "After increment (++): " << charA << endl;
  
    // Decrement
    charA--;
    cout << "After decrement (--): " << charA << endl;
  
    // Addition
    // Moving 3 characters forward from 'A'
    char resultAdd = charA + 3;
    cout << "After adding 3: " << resultAdd << endl;
  
    // Subtraction
    // Moving 2 characters backward from 'D'
    char resultSub = resultAdd - 2;
    cout << "After subtracting 2: " << resultSub << endl;
  
    return 0;
}


Output

Original character: A
After increment (++): B
After decrement (--): A
After adding 3: D
After subtracting 2: B

Conclusion

Character arithmetic in C++ provides a way to manipulate characters through their ASCII values. This knowledge is particularly useful in scenarios where characters need to be transformed, encrypted, or manipulated in various ways.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads