Header Ads

28 - WAP to implement own atoi & itoa function in C

This program used to implement own atoi & itoa function in C.

atoi - This function converts string argument ('str') to an integer (type int).
int atoi(const char *str)
itoa - This function converts integer value into a null-terminated string. It can convert negative numbers too.
char* itoa(int num, char* buffer, int base) 
/* Program for atoi & itoa in C */

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

//ASCII to integer
int atoi(const char *string)
{
 int idx = 0, integer = 0, minus;

 while (string[idx] != '\0')
 {
  //Checking for minus
  if ((idx == 0) && (string[idx] == '-'))
  {
   minus = 1;
  }
  //Checking for characters and calculating the integer
  if (string[idx] >= '0' && string[idx] <= '9')
  {
   integer = integer * 10 + string[idx] - '0';
  }
  idx++;
 }
 //Calculating the negative
 if (minus == 1)
 {
  integer *= -1;
 }
 return integer;
}

//Integer to ascii
char* itoa(int integer)
{
 int idx, minus;
 //Declaring character array pointer
 char *c_array = malloc(12 * sizeof (char));

 //Checking if it is negative
 if (integer & (1 << 31))
 {
  minus = 1;
  integer = ~integer;
  integer += 1;
 }

 //Checking if it is zero
 if (integer == 0)
 {
  c_array = "0";
  return c_array;
 }

 else
 {
  c_array[11] = '\0';

  for (idx = 10; integer != 0; idx--)
  {
   c_array[idx] = (integer % 10) + '0';
   integer = integer / 10;
  }
 }

 //Returning negative number
 if (minus == 1)
 {
  c_array[idx] = '-';
  return c_array + idx;
 }

 //Returning positive number
 else
 {
  return c_array + idx + 1;
 }
}

//length of the first word
int getword()
{
 int len = 0;
 char ch = getchar();
 //Checking for spaces and enter
 while (ch != ' ' && ch !='\n')
 {
  len++;
  ch = getchar();
 }
 return len;
}

int main()
{
 int integer, choice;
 char string[30], string1[30], ch;

 while (1)
 {
  printf(" Select your choice\n 1. AtoI\n 2. ItoA\n 3. Get Word\n Enter Your Choice : ");
  //Reading choice from user
  scanf("%d", &choice);
  getchar();
  switch (choice)
  {
   case 1://ASCII to integer
    printf(" Enter the String : ");
    scanf("%s", string);
    printf(" Integer = %d\n", atoi(string)); 
    break;
   case 2://Integer to ascii
    printf(" Enter the Integer : ");
    scanf("%d", &integer);
    printf(" String = %s\n", itoa(integer));
    break;
   case 3://Get word
    printf(" Enter the Word : ");
    printf(" The length of the string is = %d\n", getword());
    break;
   default:
    printf(" Error! Wrong choice mate!\n");
    break;
  }
  while (getchar() != '\n');
  printf(" >>>>> To continue press Y : ");
  ch = getchar();
  if (!(ch == 'y' || ch == 'Y'))
  {
   break;
  }
 }
}

Program Output:

 ...

No comments