I'm having extreme trouble figuring this code out. I need four functions besides main()
that: reads the array elements, prints the array elements, sorts the array, and swaps two elements of an array.
I cannot use any structured code (e.g., no goto
, break
, continue
, etc. statements.
I also need to be able to run the program by entering more values than the declared array size which is 10, display an error message and then sort the first 10 values entered anyway. I need to be able to run the program and enter a character and display an error message and flush the bad data and continue reading until end of file or the array is full.
#include <stdio.h>
#define MAXSIZE 10 //max number of elements is 10
int main()
{
void print(const int arr[],int size);
void sort(int arr[],int size);
int getArray(int arr[],int max);
int arr[MAXSIZE]; //array
int size=getArray(arr,MAXSIZE); //size of array
printf("The array is:\n");
print(arr,size);
sort(arr,size);
printf("The sorted array is:\n");
print(arr,size);
}
void swap(int arr[],int i,int j) //swap function
{
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
void print(const int arr[],int size) //print function
{
int i;
for (i = 0; i < size; i++)
printf ("%d ",arr[i]);
printf("\n");
}
void sort(int arr[],int size) //sort funtion
{
void swap(int arr[], int i, int j);
int min, min_index, i, j;
for( i = 0; i <= size - 2; i++)
{
min = arr[i];
min_index = i;
for(j = i + 1; j < size; j++)
{
if (arr[j] < min)
{
min = arr[j];
min_index = j;
}
}
swap(arr, i, min_index);
}
}
int getArray(int arr[],int max)
{
int temp = 0;
int count = 0;
char c;
printf ("Enter numbers with spaces between them\n");
scanf ("%i", &temp);
while ((c = scanf ("%i", &temp)) != EOF || count < max)
{
if(c == 0){
printf ("Invalid character. Please enter the numbers again.\n");
while (getchar() != '\n');
} else {
arr[count] = temp;
count++;
}
if (c == 1)
{
printf ("Too many values\n");
return count;
}
}
return count;
}
The output is not what I want. This is what I get when I run it.
Enter numbers with spaces between them
5 4 3 2 1
Too many values
The array is:
4
The sorted array is:
4
I need the program to properly take in all the elements and not have the 'Too many values' thrown if the user only inputs 5 elements.
It should only print the 'Too many values' when the array is over 10 (MAXSIZE
) elements. As of right now it only takes the first or second element of the array.