-1

Can you help me find out why the second 0 in the array turns into 45 please.

Screen shot of plain text

Everything is okay but except this number makes the result goes wrong. I cannot find out what's the matter with this.

Here is my code:

 #include <stdio.h>

 int getuserchoice() {  
     int n;
     printf("---ISBN Validate---");
     printf("\n1-ISBN Checking");
     printf("\n2-Quit");
     printf("\nSelect: ");
     scanf("%d", &n);
     return n;
 }

 int main() {
     long a[10];
     long sum = 0;
     int i = 0, n = 1;
     long x;
     if (getuserchoice() == 1) {
         printf("\nEnter the values for ISBN number : ");
         scanf("%ld", &x);
         if (x > 0) {
             while (x > 0) {
                 a[i] = x % 10;
                 x = x / 10;
                 i++;
             }
         }

         for (i = 0; i < 10; i++)
             printf("%ld\t", a[i]);
         for (i = 0; i < 10; i++) {
             sum += a[i] * n;
             n++;
         }
         if (sum % 11 == 0)
             printf("\nISBN Status: Valid!");
         else
             printf("\nISBN Status: Invalid!");
     } else
             printf("\nSee you later!");
     getchar();
     return 0;
}
aduguid
  • 3,099
  • 6
  • 18
  • 37
  • 1
    Where does 0 turn into 45 (we don't accept images here)? You have undefined behavior in your while loop when `i` becomes 10 – An0num0us Jun 24 '18 at 15:14
  • very thank you . it's solved – NolFire Jun 24 '18 at 15:25
  • If my answer was helpful for you, consider upvoting it and marking it as accepted. – An0num0us Jun 24 '18 at 15:31
  • Please do not post images of text-only screen shots. Treat the image as 'code' and show it directly in the question. The icing on the cake is adding a line `` with a blank line after it before the image so it doesn't get coloured by the SO MarkDown system. – Jonathan Leffler Jun 24 '18 at 15:50

1 Answers1

1

By default uninitialized arrays contain garbage (literally anything). It so happens that that particular element contains 45 (amazing, isn't it?).

It stays 45 because leading 0s are discarded when reading a number (you should read it as a string (C++) or char[]), so you are never accessing that particular array element to give it a meaningful value.

Here's SO post on how to initialize an array with 0s in C.

An0num0us
  • 961
  • 7
  • 15