I'm quite new to C, I'm learnig it cause of my school and i can say I'm starting to understand why most laguages are based on this one.
I'm trying to make a programm that creates an int array of 100 random numbers saves it to a file and then eliminates duplicate numbers and sorts it in ascending order.
My solustion brings out in to the same file the desired effect but it feels kind of too complicated for what it is suppose to do.
I'm 99% certain that there is a more delicate or simple way to do this.
I was gonna use 3 function:
- For saving the file
- For eliminating duplicates and,
- For sorting
In the end I did 2 cause I encoutered a few problems in my solution.
e.x.:One of the problems is that after deleting duplicates I was left with a bunch of places in my array that were filled with values I didn't whant, like the sort of values you get in a variable that you haven't initialize. So I used counter variables ending up using global vars which they weren't my first choice.
I'm pretty sure you can find a few crazy things in there.
I'm open to any suggestion if there is any and I would like to thank you all in advance for trying to help me find the end of my own mess.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int cnt;
void *save(int *pin)
{
FILE *dat;
int i=0;
dat = fopen("data.txt","w");
while(pin[i])
{
if(i==cnt){break;}
fprintf(dat,"\n%d",pin[i]);
i++;
}
fclose(dat);
return 0;
}
void del_sort()
{
FILE *dat;
int pin[100];
int i=0,j,k,sw=0,temp;
dat=fopen("data.txt","r");
while(!feof(dat))
{
fscanf(dat,"%d",&pin[i]);
i++;
}
fclose(dat);
//Eliminate duplicate numbers
for(i=0;i<cnt;i++)
{
sw++;
if (pin[i]>100)
{
sw--;
break;
}
for(j=i+1;j<cnt;j++)
{
if (pin[i]==pin[j])
{
for(k=j;k<cnt;k++)
{
pin[k]=pin[k+1];
}
}
}
}
int pin2[sw];
for(i=0;i<sw;i++)
{
pin2[i]=pin[i];
}
//Sort number in Ascending order
for(i=0;i<sw-1;i++)
{
for(j=0;j<sw-i-1;j++)
{
if(pin2[j]>pin2[j+1])
{
temp=pin2[j];
pin2[j]=pin2[j+1];
pin2[j+1]=temp;
}
}
}
printf("\n\n\n");
for(i=0;i<sw;i++)
{
printf("%d\t",pin2[i]);
}
cnt = sw;
save(pin2);
}
int main()
{
srand(time(0));
int pin[100];
int i;
cnt=0;
for(i=0;i<100;i++)
{
pin[i]=rand()%100+1;
printf("%d\t",pin[i]);
cnt++;
}
printf("\n");
save(pin);
del_sort();
return 0;
}