Solution for Exercise 12-14

ex1214

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

#define SIZE 40

int main()
{
    int bubble[SIZE];
    int inner,outer,temp,x;

    srand((unsigned)time(NULL));
/* Display original array */
    puts("Original Array:");
    for(x=0;x<SIZE;x++)
    {
        bubble[x] = rand();
        bubble[x] = (bubble[x] % 100)+1;
        printf("%d\t",bubble[x]);
    }
    putchar('\n');

/* Bubble sort */
    for(outer=0;outer<SIZE-1;outer++)
    {
        for(inner=outer+1;inner<SIZE;inner++)
        {
            if(bubble[outer] > bubble[inner])
            {
                temp=bubble[outer];
                bubble[outer] = bubble[inner];
                bubble[inner] = temp;
            }
        }
    }

/* Display sorted array */
    puts("Sorted Array:");
    for(x=0;x<SIZE;x++)
        printf("%d\t",bubble[x]);
    putchar('\n');

    return(0);
}

Notes

* The stdlib.h and time.h header files are required (Lines 2 and 3) for the rand(), srand(), and time() functions.

* Line 12 seeds the randomizer, as is discussed in Chapter 11.

* Lines 17 and 18 assign the random values to the array. I split it up into two steps to make it more clear. First in Line 17 the random value is assigned to the array element. Next, the random value is clipped by the modulus so that it falls into the range 1 to 100. You could do the same thing by using another int variable to temporarily store the random number, or you could use the rand() function directly. All solutions are valid as long as the results are what you intended.