Kalpadiptya Roy
Kalpadiptya Roy

Reputation: 187

Why my C program stops running in the middle?

I am trying to calculate the minimum coin denomination using the dynamic programming approach, but my code stops running after the 2nd query even though it should run for 10 times if I provide T = 10. Why is it stopping?

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

int min(int x, int y)
{
    return (x < y) ? x : y;
}

short int min_denom(short int N)
{
    short int *table, i, j, x;
    table = (short int*)malloc(N * sizeof(short int));
    for(i = 0; i < N; i++)  
        table[i] = 1 + i;
    for(i = 1; i <= (short int)sqrt(N); i++)    
        for(j = 0; j < N; j++)      
            if(j == i)
                table[j] = min(1, table[j]);
            else if(j > i)
                table[j] = min(table[j - i - 1] + 1, table[j]);         
    x = table[N - 1];
    free(table);
    return x;               
}

int main()
{
    short int T, N, i;
    scanf("%d", &T);
    for(i = 1; i < T; i++)
    {
        scanf("%d", &N);
        printf("%d\n", min_denom((short int)N));        
    }
    scanf("%d", &N);
    printf("%d\n", min_denom((short int)N));
         
    return 0;
}

The output is:

10
100
10
500
22

Then it stops running automatically.

Upvotes: 0

Views: 481

Answers (1)

Kalpadiptya Roy
Kalpadiptya Roy

Reputation: 187

The code will run till the end if we just replace "%d" either with "%hd" or "%hi". The reason is since the input we are taking will be stored in a short int type of variable, so we must use the proper access specifier for that.

The changed portion is given below.

 short int T, N, i;
 scanf("%hi", &T);
 for(i = 1; i < T; i++)
 {
     scanf("%hi", &N);
     printf("%hi\n", min_denom((short int)N));        
 }
 scanf("%hi", &N);
 printf("%hi\n", min_denom((short int)N));

Upvotes: 1

Related Questions