0

I have a program below, which gets some random numbers from users and then multiply every second to the last digit by 2, stores it into an array and print out the value of each array index.

It seems to compile fine (no error), but when running the program, I got some errors. (See below screenshoot where the first is correct as expected and the other two are not as expected)

See the Screenshot here for the errors

So suppose, a user typed: 99999999 (i.e in eight places) the array_size will be set to store 4 different values at index, 0, 1, 2, 3. The product of each second to last digit will be calculated and a loop will be used to achieve the below;

array[0] = 18;
array[1] = 18;
array[2] = 18;
array[3] = 18;

From the screenshot, two errors are generated.

  1. Runtime error out of bound...
  2. values are not calculated properly, even when the formula is CORRECT.

MY CODE BELOW

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

    int main(void)
    {
        int last_digit, new_num, second_to_last_digit, product, product_len, digits_not_mult, index_upd;
        int num = get_long("Enter Number: ");
        int as = (log10(num) + 1) / 2; //calculates the length of no. entered by user and divides by half.
        int mult_array[as]; //sets the array_size for to store the products of every second to last digits.

        digits_not_mult = 0;
        index_upd = 0;

        while(num > 0)
        {

            last_digit = num % 10;
          //  nnum = num / 10;  //  num /= 10;
            second_to_last_digit = (num / 10) % 10; 
            product = second_to_last_digit * 2;
            digits_not_mult += last_digit;
            num /= 100; //updates the number entered by user

            index_upd++; //will be used to set the index of the array below.
            mult_array[index_upd - 1] = product;
           printf("product is %i \n", mult_array[index_upd - 1]); // prints each value stored in the array.   
       }

    return 0;
    }
2
  • Thanks to Arindam Ghosh via FB Dec 27 '19 at 12:36
  • Runtime -out of bounds was due to the odd value that may exist due to the array_size[as] The fixed was to add 1 to the array_size. (i.e mult_array[as + 1];). Fir the second part where the values are not calculated property on some numbers, I fixed it by changing the type for NUM from INT to LONG. Dec 27 '19 at 12:43
0

For the first question - Runtime -out of bounds was due to the odd value that may exist due to the array_size[as]

The fixed was to add 1 to the array_size.

i.e  `mult_array[as + 1];

For the second part where the values are not calculated property on some numbers, I fixed it by. changing the type for NUM from INT to LONG.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .