This program contains functions that sort arrays, and opens and reads files. Written in C.
Sort arrays in C.
Date Created:Saturday March 24th, 2007 02:36 PM
Date Modified:Sunday August 03rd, 2008 11:48 AM
/*
* Author: Dan Lynch
*/
#include <stdio.h>
/*
* prototypes
*/
void swap(int *a, int *b);
void sortarray(int *array, int size);
void write_to_file(char * filename, int highest, int type);
void readfile(char * filename, int *numbers);
void highestnumber(int a, int b, int c, int * highest);
int file_exists(char * filename);
int GetLargestInArray(int x[], int n);
/*
* program
*/
int main()
{
int i,a,b,c,highest;
int numbers[1000];
int set[3];
char * filename="data.c";
for (i=0; i<3; i++)
{
printf("Enter three numbers:\n");
scanf("%d %d %d",&a,&b,&c);
highestnumber(a,b,c,&highest);
set[i]=highest;
}
sortarray(set,3);
if ( file_exists (filename) ) write_to_file(filename, set[0],1);
else write_to_file(filename, set[0],0);
readfile(filename, numbers);
return 0;
}
/*
* functions
*
*/
void readfile(char * filename, int * numbers)
{
FILE *data;
int a,i;
data = fopen ( filename, "r" );
if (data != NULL) {
i=0;
do {
fscanf(data, "%d", &numbers[i]);
i++;
} while( !feof(data) );
fclose( data );
printf("Highest number out of %d entries in data.c is %d\n", i,GetLargestInArray(numbers, (i-1)) );
} else {
printf("Cannot Open File in readfile()!");
}
for (a=1;a<i;a++) printf("\nNumber %d = %d",a,numbers[a-1]);
}
void write_to_file(char * filename, int highest, int type)
{
FILE *data;
if (type == 0) {
data = fopen ( filename, "w" );
printf("data.c is non-existent, I will create it for you.\n");
} else {
data = fopen ( filename, "a" );
}
if ( data == NULL )
{
printf("cannot open");
} else {
fprintf(data,"%d\n",highest);
fclose(data);
}
}
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
void sortarray(int* array, int size) {
int j,k;
for ( j=0; j < size - 1; j++) {
for ( k = j; k < size; k++) {
if ( array[j] < array[k] ) {
swap(&array[j], &array[k]);
}
}
}
}
void highestnumber(int a, int b, int c, int * highest)
{
if (a > b && a > c) {
printf("The largest number of %d %d %d is %d\n",a,b,c,a);
*highest=a;
} else if (b > a && b > c) {
printf("The largest number of %d %d %d is %d\n",a,b,c,b);
*highest=b;
} else {
printf("The largest number of %d %d %d is %d\n",a,b,c,c);
*highest=c;
}
}
int GetLargestInArray(int x[], int n) {
int i; int largest=x[0];
for(i=0;i<n;i++) if(x[i]>largest) largest=x[i];
return largest;
}
int file_exists(char * filename)
{
FILE * data;
data = fopen(filename, "r");
if (data != NULL)
{
fclose(data);
return 1;
Downloads:
Download: array.c 3 KB
Please login or Click Here to register for downloads
Sort Array by Dan Lynch
is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 United States License
Based on a work at www.3daet.com
Permissions beyond the scope of this license may be available at http://www.3daet.com
