Open In App

Character Arithmetic in C

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




// C program to demonstrate character arithmetic.
#include <stdio.h>
 
int main()
{
    char ch1 = 125, ch2 = 10;
    ch1 = ch1 + ch2;
    printf("%d\n", ch1);
    printf("%c\n", ch1 - ch2 - 4);
    return 0;
}

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




#include <stdio.h>
// driver code
int main(void)
{
    char value1 = 'a';
    char value2 = 'b';
    char value3 = 'z';
    // perform character arithmetic
    char num1 = value1 + 3;
    char num2 = value2 - 1;
    char num3 = value3 + 2;
    // print value
    printf("numerical value=%d\n", num1);
    printf("numerical value=%d\n", num2);
    printf("numerical value=%d\n", num3);
    return 0;
}

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

Example 3




#include <stdio.h>
 
int main()
{
    char a = 'A';
    char b = 'B';
 
    printf("a = %c\n", a);
    printf("b = %c\n", b);
    printf("a + b = %c\n", a + b);
 
    return 0;
}

Output

a = A
b = B
a + b = â

Explanation 


Article Tags :