vankineeni tawrun
vankineeni tawrun

Reputation: 39

C program gives different answers with a floating rand() call included

I was trying to solve a competitive programming question when I wrote this code:

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

int brr[100];
int n,arr[100];
int s[100];

int dyn(int num){    
    int i,ans;
    if(brr[num]!=-1){
      return brr[num];}

    for(i=0;i<n;i++){
      if(arr[i]==num){
        ans=1;
        s[num]=arr[i];
        break;}
      else if(arr[i]<num){
        if(i==0){
          ans=1+dyn(num-arr[i]);
          s[num]=arr[i];}
        else {
          if(ans>1+dyn(num-arr[i])){
            ans=1+dyn(num-arr[i]);
            s[num]=arr[i];
          }}}}
  brr[num]=ans;
   return ans ;
}    

int main(){
  scanf("%d",&n);
  int i;
  for(i=0;i<n;i++){
    scanf(" %d",&arr[i]);
  }
  int num=0;
  scanf(" %d",&num);
  for(i=0;i<=num;i++){
    brr[i]=-1;}
  brr[0]=0;
  for(i=1;i<=num;i++){
    dyn(i);
    //rand();
  }
  printf("\n%d\n",dyn(num));
  while(num>0){
    printf("\t%d",s[num]);
    num=num-1;
  }
  return 0;
}

Line 44 has a commented out rand(). If I execute the code with the rand() commented out, i get the result as

2
6    6    6    6    6    5    0    0    2    1

for the input 4 6 5 2 1 10

After removing the comment I get

2
5    6    6    6    6    5    2    2    2    1

for the same input.

What's going on?

Upvotes: 2

Views: 69

Answers (1)

Marian
Marian

Reputation: 7472

In the function dyn in the line

if(ans>1+dyn(num-arr[i])){

the value ans may be used uninitialized. This is causing that the behavior of the program is undefined.

Upvotes: 7

Related Questions