vendredi 27 janvier 2017

Generating Random UNIQUE and converting to binary in C

I have implemented a basic program which generates 10 random and unique numbers from 1 to 10 as shown below. I have added an extra part in which I want the binary representation for each unique and random number. My program looks like this.

   int value=1, loop, loop1, get=0, x, arr[10], array[20], count, i =0, y;
   srand(time(NULL));

for (x = 0; x < 10; x++)
{
    for (count = 0; count < 10; count++) {
        array[count] = rand() % 10 + 1;     //generate random number between 1 to 10 and put in array
    }
    while (i < 10) {
        int r = rand() % 10 + 1;    // declaring int r 

        for (x = 0; x < i; x++)
        {
            if (array[x] == r) {    //if integer in array x is equal to the random number generated
                break;              //break
            }
        }
        if (x == i) {           //if x is equal to i then   
            array[i++] = r;         //random number is placed in array[10]
        }
    }
    for (y = 0; y < 10; y++) {
        printf("unique random number is %d\n", array[y]);
        array[y] = value;

        for (loop = 0; loop < 1000; loop++)
        {
            if (value <= 1) { arr[loop] = 1; break; }       //if value is 1 after dividing put 1 in array
            if (value % 2 == 0) arr[loop] = 0;
            else arr[loop] = 1;

            value = value / 2;
        }
        for (loop1 = loop; loop1 > -1; loop1--)
            printf("%d", arr[loop1]);
        printf("\n");
    }   
   }

My problem is that The binary value for each random unique number is being given as 1. In this program it is seen that I initialised value=1 and this can be the source for my error, however when I remove this I get an error stating that the local variable is uninitialised.

The first part of my program which generates the unique numbers is working fine, however the second part where I am converting to binary is not.

EDIT: I tested The second part of my program and it works well on it's own. The problem must be the way I am combining the two programs together.




Aucun commentaire:

Enregistrer un commentaire