VOOZH about

URL: https://www.geeksforgeeks.org/c/character-arithmetic-c-c/

⇱ Character Arithmetic in C - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Character Arithmetic in C

Last Updated : 26 Dec, 2023

As already known character range is between -128 to 127 or 0 to 255. This point has to be kept in mind while doing character arithmetic. 

What is Character Arithmetic?

Character arithmetic is used to implement arithmetic operations like addition, subtraction, multiplication, and division on characters in C language. 
In character arithmetic character converts into an integer value to perform the task. For this ASCII value is used.
It is used to perform actions on the strings.

To understand better let's take an example.

Example 1


Output
-121
y

So %d specifier causes an integer value to be printed and %c specifier causes a character value to printed. But care has to taken that while using %c specifier the integer value should not exceed 127. 

Let's take one more example.

Example 2


Output
numerical value=100
numerical value=97
numerical value=124

Example 3

Output

a = A
b = B
a + b = â

Explanation 

  • In this program, two character variables a and b are declared and assigned the values 'A' and 'B', respectively. The program then adds a and b using character arithmetic, which results 'â'. The result is then printed using the printf() function.
  • Note that in character arithmetic, the characters are treated as integers based on their ASCII code values. For example, the ASCII code for 'A' is 65 and for 'B' is 66, so adding 'A' and 'B' results in 65 + 66 = 131, which is the ASCII code for 'â'.
Comment
Article Tags: