C Program For Int to Char Conversion
To convert the int to char in C language, we will use the following 2 approaches:
- Using typecasting
- Using sprintf()
Example:
Input: N = 65 Output: A
1. Using Typecasting
Method 1:
- Declaration and initialization: To begin, we will declare and initialize our integer with the value to be converted.
- Typecasting: It is a technique for transforming one data type into another. We are typecasting integer N and saving its value in the data type char variable c.
- Print the character: Finally, print the character using print.
Example:
C
// C program to demonstrate // conversion of int to char // using typecasting #include <stdio.h> // Driver code int main() { int N = 103; printf ( "%c" , ( char )(N)); return 0; } |
Output
g
Time complexity is O(1)
The auxiliary is also O(1)
Method 2:
- Declaration and initialization: To begin, we will declare and initialize our integer with the value to be converted.
- Typecasting: Declare another variable as character c and assign the value of N to the C
- Print the character: Finally, print the character using printf.
Example:
C
// C program to demonstrate conversion of // int to char using typecasting #include <stdio.h> // Driver code int main() { int N = 71; char c = N; printf ( "%c" , c); return 0; } |
Output
G
2. Using sprintf()
Allot space for a single int variable that will be converted into a char buffer.
Example:
C
// C program to demonstrate conversion of // int to char using sprintf() #include <stdio.h> int main() { int num = 71; char c[1]; sprintf (c, "%c" , num); printf ( "The character value is %s" , c); return 0; } |
Output
The character value is G
Method: Converting to int to char by adding 0
C
#include <stdio.h> // Driver code int main() { int N = 71; char c = N+0; printf ( "%c" , c); return 0; } |
Output
G
Method:
C
#include <stdio.h> int main() { int num=71; if (num >= 0 && num <= 127) { printf ( "The character representation of %d is: %c\n" , num, num); } else { printf ( "The integer %d is out of range for character representation\n" , num); } return 0; } |
Output
The character representation of 71 is: G