How to Convert Integer to String in C with Example
sprintf(buffer, "%d", number); where buffer is a char array to hold the string and number is the integer.Examples
How to Think About It
Algorithm
Code
#include <stdio.h> int main() { int number = 123; char str[12]; // enough for int including sign and null sprintf(str, "%d", number); printf("Converted string: %s\n", str); return 0; }
Dry Run
Let's trace converting the integer 123 to a string.
Initialize variables
number = 123, str = uninitialized char array
Call sprintf
sprintf(str, "%d", 123) writes "123" into str
Print result
printf prints "Converted string: 123"
| Step | Variable | Value |
|---|---|---|
| 1 | number | 123 |
| 2 | str | "123" |
| 3 | output | Converted string: 123 |
Why This Works
Step 1: Buffer for string
We create a char array to hold the string because C strings are arrays of characters ending with a null character.
Step 2: Using sprintf
sprintf formats the integer into text and stores it in the buffer, converting the number to its string form.
Step 3: Printing the string
We print the buffer with printf using %s to show the string version of the integer.
Alternative Approaches
#include <stdio.h> int main() { int number = 456; char str[12]; snprintf(str, sizeof(str), "%d", number); printf("Converted string: %s\n", str); return 0; }
#include <stdlib.h> #include <stdio.h> int main() { int number = -789; char str[12]; itoa(number, str, 10); // base 10 printf("Converted string: %s\n", str); return 0; }
Complexity: O(n) time, O(n) space
Time Complexity
The time depends on the number of digits in the integer, so it is O(n) where n is the digit count.
Space Complexity
Space is needed for the output string buffer, proportional to the number of digits plus one for the null terminator.
Which Approach is Fastest?
Using sprintf or snprintf is efficient and standard; itoa may be faster but less portable.
| Approach | Time | Space | Best For |
|---|---|---|---|
| sprintf | O(n) | O(n) | Standard, simple conversion |
| snprintf | O(n) | O(n) | Safe conversion with buffer limit |
| itoa | O(n) | O(n) | Quick conversion but non-standard |