problem: reading user input into an array
This program sorts an array of data, and is supposed to print the first number of the array and the last number of the array after the sort.
The problem is that it will let the user enter more than the size of the array. If you run it, you'll see what I mean. Would I have to implement some form of sentinel that checks if they have entered more than the array size?
Code:
#include <stdio.h>
#define SIZE 10
void bubble(int *, const int, int (*)(int, int)); /* bubble sort */
void swap(int *, int *);
int sortAscending(const int, const int);/* sorting items in ascending order*/
int main(void)
{
int months[SIZE];
int counter;
printf("Sorting Data in array months\n");
scanf("%d", &months);
bubble(months, SIZE, sortAscending);
/* prints out the first value */
for (counter = 0; counter <= 1 - 1; counter++)
{
printf("%4d\n", months[counter]);
}
/* prints out the last value */
for (counter = 0; counter <= SIZE; counter++)
if (counter == SIZE -1)
{
printf("%4d", counter[months]);
}
printf("\n");
return 0;
}
/* sorts the array months */
void bubble(int *work, const int size, int (*compare)(int, int))
{
int pass, count;
void swapt(int *, int *);
for (pass = 1; pass <= size - 1; pass++)
for (count = 0; count <= size - 2; count++)
if ((*compare) (work[count], work[count + 1]))
swap(&work[count], & work[count + 1]);
}
void swap(int *element1Ptr, int *element2Ptr)
{
int temp;
temp = *element1Ptr;
*element1Ptr = *element2Ptr;
*element2Ptr = temp;
}
/* sorts the array months into ascending order (smallest to largest) */
int sortAscending(const int a, const int b)
{
return b < a;
}