C - Do arithmetic operations to values of type char

Introduction

The following program demonstrates how to perform arithmetic with char variables that you've initialized with characters.

The first three statements in the body of main() are as follows:

char first = 'A';
char second = 'B';
char last = 'Z';

The next statement initializes a variable of type char with an integer value:

char number = 40;

The initializing value must be within the range of values that a one-byte variable can store.

The next three statements declare three more variables of type char:

char ex1 = first + 2;                     // Add 2 to 'A'
char ex2 = second - 1;                    // Subtract 1 from 'B'
char ex3 = last + 2;                      // Add 2 to 'Z'

The next two statements output the three variables ex1, ex2, and ex3 in two different ways:

printf("Character values      %-5c%-5c%-5c\n", ex1, ex2, ex3);
printf("Numerical equivalents %-5d%-5d%-5d\n", ex1, ex2, ex3);

The first statement interprets the values stored as characters by using the %-5c conversion specifier.

This specifies that the value should be output as a character that is left aligned in a field width of 5.

The second statement outputs the same variables again, but interprets the values as integers by using the %-5d specifier.

The last line outputs the variable number as a character and as an integer:

printf("The number %d is the code for the character %c\n", number, number);

Demo

#include <stdio.h>

int main(void)
{
      char first = 'A';
      char second = 'B';
      char last = 'Z';

      char number = 40;

      char ex1 = first + 2;                     // Add 2 to 'A'
      char ex2 = second - 1;                    // Subtract 1 from 'B'
      char ex3 = last + 2;                      // Add 2 to 'Z'

      printf("Character values      %-5c%-5c%-5c\n", ex1, ex2, ex3);
      printf("Numerical equivalents %-5d%-5d%-5d\n", ex1, ex2, ex3);
      printf("The number %d is the code for the character %c\n", number, number);
      return 0;// w w w  . j  av  a  2 s  .  co  m
}

Result

Related Topic