How to convert string to int without using library functions in c

Converting a String to an Integer in C without Library Functions

To convert a string to an integer in C without using library functions, you can implement a simple algorithm that iterates through each character of the string and calculates the corresponding integer value. Here's an example implementation:

#include <stdio.h>

int stringToInt(char* str) {
    int result = 0;
    int sign = 1;
    int i = 0;

    // Check for negative sign
    if (str[0] == '-') {
        sign = -1;
        i = 1;
    }

    // Iterate through each character of the string
    while (str[i] != '\0') {
        // Convert character to integer value
        int digit = str[i] - '0';

        // Update the result by multiplying it by 10 and adding the digit
        result = result * 10 + digit;

        i++;
    }

    // Apply the sign
    result = result * sign;

    return result;
}

int main() {
    char str[] = "12345";
    int num = stringToInt(str);
    printf("The converted integer is: %d\n", num);

    return 0;
}

In this example, the stringToInt function takes a character array (str) as input and returns the corresponding integer value. It initializes the result variable to 0 and the sign variable to 1. If the first character of the string is a negative sign, it updates the sign variable to -1 and starts iterating from the second character (i = 1).

The algorithm then iterates through each character of the string using a while loop. It converts each character to its integer value by subtracting the ASCII value of '0'. It updates the result variable by multiplying it by 10 and adding the digit value.

Finally, the algorithm applies the sign to the result and returns it.

In the main function, we provide an example string "12345" and call the stringToInt function to convert it to an integer. The result is then printed to the console.

Please note that this implementation assumes that the input string is a valid integer representation and does not handle error cases such as non-numeric characters or overflow.