Itoa function in C
×


Itoa function in C

344

 The itoa function in C is a non-standard function used to convert an integer to a string.

 It takes an integer (value), a character array (str) where the resulting string will be stored, and a base (base) for the conversion.

 The function returns a pointer to the resulting null-terminated string (str).

Syntax of itoa in C:

	

char* itoa(int value, char* str, int base);

 value: The integer to be converted.

 str: A pointer to a character array where the resulting string will be stored.

 base: The base for conversion (commonly 10 for decimal, 2 for binary, etc.).

Return Value:

 A pointer to the resulting null-terminated string str.

Example:

// Program for itoa in C
#include<stdio.h> 
#include<stdlib.h>

// Non-standard itoa function declaration
char* itoa(int value, char* str, int base);

int main() {
    int num1 = 12345;     // An integer
    int num2 = -6789;     // A negative integer
    char str1[20];        // String to hold the result for num1
    char str2[20];        // String to hold the result for num2

    // Convert integers to strings
    itoa(num1, str1, 10); // Convert num1 to decimal
    itoa(num2, str2, 10); // Convert num2 to decimal

    // Print the results
    printf("Integer: %d, String: %s\n", num1, str1);
    printf("Integer: %d, String: %s\n", num2, str2);

    return 0;
}

// Non-standard itoa function implementation
char* itoa(int value, char* str, int base) {
    // Handle 0 case
    if (value == 0) {
        str[0] = '0';
        str[1] = '\0';
        return str;
    }

    // Handle negative numbers
    int isNegative = 0;
    if (value < 0 && base == 10) {
        isNegative = 1;
        value = -value;
    }

    int i = 0;
    while (value != 0) {
        int rem = value % base;
        str[i++] = (rem > 9) ? (rem - 10) + 'a' : rem + '0';
        value = value / base;
    }

    // Add negative sign for base 10
    if (isNegative) {
        str[i++] = '-';
    }

    str[i] = '\0';

    // Reverse the string
    int start = 0;
    int end = i - 1;
    while (start < end) {
        char temp = str[start];
        str[start] = str[end];
        str[end] = temp;
        start++;
        end--;
    }

    return str;
}

	
Output:

Integer: 12345, String: 12345
Integer: -6789, String: -6789

In this program:

 We've implemented the itoa function to convert an integer to a string.

 We use this function to convert two integers (num1 and num2) to decimal strings.

 We print the original integers along with their string representations.



Best WordPress Hosting


Share:


Discount Coupons

Get a .COM for just $6.98

Secure Domain for a Mini Price



Leave a Reply


Comments
    Waiting for your comments