-4

Below is my code that should calculate the ISBN number of a book:

#include <cs50.h>
#include <stdio.h>
#include <math.h>

int main(void)
{
    int isbn[] = 0;
    printf("Please enter ISBN number: \n");

    scanf("%d", &isbn);
    int num = 0;
    int times_by = 1;
    long long sum;
    long long sum1;
    long long result = 0;
    for (num = 0; num <= 9; num++){
        sum = isbn[num] * times_by;
        sum1 = sum + sum;
        times_by++;
    }
    result = sum / 11;
    if (result == 0){
        printf("Yes\n");
    } 
    else {
        printf("No\n");
    }
}

It is telling me that there is a problem with the initiator of isbn. I tried to create an array, which the inputted ISBN number would be saved to after, though Im not sure if this is possible..

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Tallulah
  • 51
  • 1
  • 11

2 Answers2

4

The problem starts with int isbn[]=0; This declares an arry of no size, which can't be.

Then you read isbn as a single int and then you seem to want to calculate using each digit of the ISBN.

To do that, I suggest to declare char isbn[14]={0}; (ISBN can be 13 characters, see isbn).

Then read it as scanf("%13s", isbn);

and process it like:

    sum = (isbn[num]-'0') * times_by; // convert digit to number

Note: sum1 = sum + sum; should be sum1 = sum1 + sum;

Note: result = sum / 11; should be result = sum1 / 11;

Note: you must initialize sum1: long long sum1=0;

Note: result = sum1 / 11; won't give you the remainder. Use result = sum1 % 11;

Paul Ogilvie
  • 25,048
  • 4
  • 23
  • 41
  • Agreed. If you're not going to use something for math, it should be an array of chars/ints, not a (single) integer. Thus, storing the ISBN as an array makes sense. – Jonathon Reinhart Jan 10 '18 at 13:18
  • So I had tried that originally. It shows me this error " isbn.c:7:10: error: array initializer must be an initializer list or string literal char isbn[10] = 0;" – Tallulah Jan 10 '18 at 13:21
  • There are a few liitle bugs in your program, though I think I spotted most of them. But you should learn to use a debugger so you can step through your program and see in detail what it does and where you made the small (or sometimes large) mistakes. – Paul Ogilvie Jan 10 '18 at 13:24
  • OK: "error: array initializer must be an initializer list or string literal char isbn[10] = 0;" Then use curly braces, `isbn[10]={0};` – Paul Ogilvie Jan 10 '18 at 13:25
  • @chux, updated. Better to be correct than sloppy (which I already was...) – Paul Ogilvie Jan 10 '18 at 13:43
1

The line int isbn[] = 0; is your problem you are pointing the array's address to 0x0 which is not a valid address space for your application.

You should initialize your isbn array in another way. For example int isbn[20]. You should give a length which is sufficient for ISBN numbers. I just used 20 as an example.

nollak
  • 131
  • 1
  • 2