3

I have made a program which converts numbers entered into a string into an integer like atoi does, but its giving wrong output.

#include<stdio.h>
#include<conio.h>
#include<math.h>
#include<string.h>
void main(void)
{
 static int sum;
 int i,x,y,z;
 char string[10];
 printf("Enter a string:\n");
 gets(string);
 x=strlen(string);
 for(i=0; ;i++)
 {
  if(string[i]=='\0')
  {
   break;
  }
  y=pow(10,i);
  z=string[x-i+1]*y;
  sum+=z;
 }
 printf("%d",sum);
 getch();
}
Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880
  • It would be helpful if you added an example of what you expect and what you're actually getting to the question. – ChrisF Jul 11 '10 at 16:21
  • 3
    note: `for(A;;B) { if (C) break; ... }` can be written as `for(A; !C; B) { ... }`. – ShinTakezou Jul 11 '10 at 17:08
  • @Shin That is my laziness sir :) –  Jul 12 '10 at 15:47
  • it's more idiomatic and less things to type, so the lazy solution is indeed `for(A; !C; B)`! :D – ShinTakezou Jul 12 '10 at 16:23
  • lol that consumes too much of my mind .I find adding the break condition afterwords very helpful as if i want to use a do while loop,i use a for loop and use the break condition after doing everything in the for loop so it always runs for a time :p –  Jul 13 '10 at 11:45

3 Answers3

5

Your string do not contain the int values 0, 1, 2, ... 9.

They contain the char values '0', '1', '2', ... '9'. Encoded in e.g. ASCII, '0' == 48.

You need to convert the char to int; one way to do this is by subtracting '0', e.g.:

z = (string[x-i+1] - '0') * y;

Related questions


On Horner's Scheme

You can also do better by not using the pow, by using Horner scheme.

Here's an example (here ^ denotes exponentiation instead of bitwise-xor):

8675309 = 8*10^6 + 6*10^5 + 7*10^4 + 5*10^3 + 3*10^2 + 0*10^1 + 9*10^0
        = (((((8*10 + 6)*10 + 7)*10 + 5)*10 + 3)*10 + 0)*10 + 9

It may look complicated at first, but it really isn't. You basically read the digits left to right, and you multiply your result so far by 10 before adding the next digit.

In table form:

step   result  digit  result*10+digit
   1   init=0      8                8
   2        8      6               86
   3       86      7              867
   4      867      5             8675
   5     8675      3            86753
   6    86753      0           867530
   7   867530      9          8675309=final

I'll leave you to implement this simple algorithm on your own, since this is homework.

See also

Related questions

Community
  • 1
  • 1
polygenelubricants
  • 376,812
  • 128
  • 561
  • 623
  • What do you say about the program which i made?I have a question to raise.Many a times i come across standard codings as you gave me via Wikipedia,but i realize that instead of that if you try yourself for an idea wont that be a better option? –  Jul 12 '10 at 15:49
  • @fahad: Michael Aaron Safyan gave a comprehensive line-by-line review of your code; I don't really have anything new to contribute. I'm not sure what your second question is about, but if it's about learning, then I do believe that in addition to learning by doing, one should also learn by examples. – polygenelubricants Jul 12 '10 at 15:53
5

Ok. Here is a quick review of your code. Comments embedded.

#include<stdio.h>

Leave a space between #include and <stdio.h>.

#include<conio.h>

This is a non-standard Windows-only header that you don't need. Don't include this.

#include<math.h>
#include<string.h>

Again use a space, when including your headers.

void main(void)

While this is legal, it is more common to find the signature int main(int argc, char* argv[]) as the signature for the main function. I would suggest that you use that signature.

 {
     static int sum;

Why are you making this static? Are you planning to invoke main repeatedly and have the previous result for sum persist from one invocation of main to another? If not, then don't make it static.

 int i,x,y,z;
 char string[10];

Consider allocating more space for your string. Ten characters is quite small. Also consider creating a variable to represent the size of your string, rather than using a magic number, since you will likely have to reference the buffer size in multiple places.

printf("Enter a string:\n");
gets(string);

No. Don't do that!!! The function gets is a major security vulnerability!. It makes your program susceptible to buffer overflow attacks. Instead, use fgets, and specify the size of the buffer that you want to fill, so that it doesn't overrun your buffer. You should never, ever use plain gets.

x=strlen(string);

Consider choosing a more descriptive name for x. Perhaps len. It is perfectly ok (and good) to create variables that have identifiers longer than a single letter.

for(i=0; ;i++)
{
  if(string[i]=='\0')
  {
     break;
  }

Consider putting the termination condition in the for-loop; for(i = 0; string[i]!='\0'; i++).

  y=pow(10,i);
  z=string[x-i+1]*y;

Hint: there is a smarter way to do this than using pow.

  sum+=z;
 }
 printf("%d",sum);

Ok. The above is fine, although you might want to use "%d\n".

 getch();

You really shouldn't be doing this on all systems. Instead, do:

#ifdef _WIN32
    system("pause");
#endif

If possible, though, I would suggest you avoid that weird pausing behavior. Suppose your professor uses an automated script to validate the output of your program. Putting any sort of pause in the program (even on Windows), will break such a script. If you don't want the terminal window to disappear while on Windows, you should invoke your program from the command prompt.

}

If you were to change the signature to something returning int as I suggested, then you would want to add the statement return 0; before the end of the function.

Michael Aaron Safyan
  • 93,612
  • 16
  • 138
  • 200
  • On the issue of static integers i would like to ask that as far as my knowledge is i think they are only used to initialize the integer with 0 but googling it i found out that when the program runs it stores the value in the static variable even after the program terminates.Is that true? –  Jul 12 '10 at 15:55
  • @fahad, a static variable, in the context of a function, is more or less a global variable that is visible only in the scope of the function. It is not stored on the function's activation record as a local variable, so unlike local variables whose values vary from invocation to invocation, a static function variable maintains its state across all calls of the function. That said, variable only persists across a single process (a single invocation of the program), so no it doesn't store its value even after the program terminates, but it does store the value even after the function terminates. – Michael Aaron Safyan Jul 13 '10 at 01:42
2

it should be:

z=(string[x-(i+1)]-'0')*y;
adamk
  • 45,184
  • 7
  • 50
  • 57