Program to convert number in characters in C
×


Program to convert number in characters in C

35

Let's say we want to convert the number 12345 into its character representation.

The output should be the string "12345".

C Code to Convert Number to Characters:

// program to convert Number to Characters
#include 
#include 

void numberToChars(int number, char* result) {
    int i = 0;
    int length = 0;
    char temp[20];  // Temporary string to store reversed characters

    // Convert number to characters
    do {
        temp[i++] = (number % 10) + '0';  // Convert digit to character
        number /= 10;
    } while (number != 0);

    temp[i] = '\0';  // Null terminate the string

    // Reverse the string
    length = strlen(temp);
    for (i = 0; i < length; i++) {
        result[i] = temp[length - 1 - i];
    }
    result[length] = '\0';  // Null terminate the result string
}

int main() {
    int number = 12345;
    char result[20];

    // Convert number to characters
    numberToChars(number, result);

    printf("Number in characters: %s\n", result);

    return 0;
}
	

Output:

Number in characters: 12345

Explanation:

numberToChars Function:

This function takes an integer number and a character array result as arguments.

It converts each digit of the number to its character representation and stores it in the result array.

Conversion:

We use the modulo operator % to get the last digit of the number.

We then add '0' to convert the digit to its ASCII character representation.

Reversal:

After converting, we reverse the characters in the temp array to get the correct order.

Main Function:

We call the numberToChars function to convert the number 12345 to its character representation.

We then print the result using printf.

The C program demonstrates how to convert an integer number into its character representation.

By breaking down the number digit by digit and converting each digit to its character equivalent, we create a string that represents the number as characters.



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