How to use Loops In C Language

We can use loops to convert a string to an integer by traversing each element of the string one by one and comparing the number characters to their ASCII values to get their numeric values and using some mathematics for generating the integer. The below example demonstrates how to do it.

Example:

C




// C Program to convert string
// into integer using for loop
#include <stdio.h>
#include <string.h>
  
int main()
{
    char* str = "4213";
    int num = 0;
  
    // converting string to number
    for (int i = 0; str[i] != '\0'; i++) {
        num = num * 10 + (str[i] - 48);
    }
  
    // at this point num contains the converted number
    printf("%d\n", num);
    return 0;
}


Output

4213

Note: We have used str[i] – 48 to convert the number character to their numeric values. For e.g. ASCII value of character ‘5’ is 53, so 53 – 48 = 5 which is its numeric value.

Convert String to int in C

Converting string to int is a reoccurring task in the programming world. Despite being a simple task, many coders either fail or get confused while doing this. Conversion is mostly done so that we can perform operations over numbers that are stored as strings.

Example:

 str=”163″ 

 number=163

C is a strongly typed language. We’ll get an error if we try to input a value that isn’t acceptable with the data type. Not just in inputs but we will get an error while performing operations.

There are 3 methods to convert a string to int which are as follows:

  1. Using atoi( )
  2. Using Loops
  3. Using sscanf()

Similar Reads

1. String Conversion using atoi( )

The atoi() function in C takes a character array or string literal as an argument and returns its value in an integer. It is defined in the header file....

2. Using Loops

...

3. Using sscanf()

...

Contact Us