-4

This is the Code :

#include <ctype.h>

/* atoi:  convert s to integer; version 2 */
int atoi(char s[])
{
int i, n, sign;

for (i = 0; isspace(s[i]); i++)  /* skip white space */
    ;
sign = (s[i] == '-') ? -1 : 1;
if (s[i] == '+' || s[i] == '-')  /* skip sign */
    i++;
for (n = 0; isdigit(s[i]); i++)
    n = 10 * n + (s[i] - '0');
return sign * n;
}

Q1) The first line of code counts white space? That means it counts spaces, enter, return etc? Say my string starts after two spaces is it? And after counting white spaces i value has been incremented?

Q2) the next sign line calculates if string is like -234? or 234?

Q3) next line if it has + or - sign count them in i which has already been incremented by calculated white spaces? is it?

Q4) next line calculates the number in the string say 234. n= 10*n+ ('2'-'0') => i get 2 => n= 10*2 + ('3'-'0') => i get 23 and at last i get number 234

and in the last line multiply 234 with -1 or +1 whatever the answer is*

Do I understand this code correctly?

DavidO
  • 13,812
  • 3
  • 38
  • 66
HELP PLZ
  • 41
  • 1
  • 9

1 Answers1

4

A1) No, it counts only white spaces in the beginning of line (white spaces in standard isspace() implementation are ' ', '\t', '\n', '\v', '\f', '\r'; i.e. space, tabs, newline, feed and carriage return).

A2) Yes, it determines sign of value.

A3) If value is "234" it will not increment i. But if value is "+234" or "-234" we need to increment i (to recognize digits after it).

A4) Yes. But not '24' (it looks like misprint; there must be '23').

Ilya
  • 4,583
  • 4
  • 26
  • 51
  • 1
    aren't these white (enter, space, return) included in whitespace characters i read it wikipedia: http://en.wikipedia.org/wiki/Whitespace_character – HELP PLZ Jun 18 '14 at 08:08
  • 1
    @Abhimanyu: uh, sure (and why do you have to ask?). You might want to read a C reference instead of Wikipedia, though. – Jongware Jun 18 '14 at 08:33
  • @Abhimanyu: It is better to read http://www.cplusplus.com/reference/cctype/isspace/ about isspace() function. – Ilya Jun 18 '14 at 09:13