r/C_Programming • u/PaninoInfernale1551 • 29d ago
Need tips to improve
I started studying C for an exam, this is my first time approaching coding so i'm a bit lost.
While doing some exercises from my prof i encountered this one that took me some time. (prompt in the code).
This is what i came up with it works correctly (i think), but i have a few questions:
is it efficient?
I also used prototype functions and didnt where i could've, when should and shouldn't i use them?
Thank you for your time spent reading this
EDIT: most comments were about formatting. i changed it. It has always looked like this, but pasting it here on reddit messed it up :)
/*
Constraints:
no frequency can be repeated
all frequencies must be between 800 and 2500 MHz
Required functions: insertion with double check (range + uniqueness) --
function that calculates the minimum distance between two frequencies --
function that identifies the frequency closest to a given value
*/
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <stdbool.h>
void fillArray(int array[],int size,int min,int max);
void printArray(int array[],int size);
void sortArray(int array[],int size);
int main ()
{
srand(time(NULL));
int freq[10];
int max=2500;
int min=800;
int size = sizeof(freq)/sizeof(freq[0]);
int mindist = abs(freq[0]-freq[1]); //base min distance, could be the result or changed
/*
printf("Insert lowest frequency: ");
scanf("%d", &min);
printf("Insert highest frequency: "); //eventual custom frequency range.
scanf("%d", &max); //option to deny min > max and max-min < size-1
*/
fillArray(freq, size, min, max);
printArray(freq, size); //printing and sorting not needed,
//but i used them to check the work
sortArray(freq, size);
printf("\nSort\n");
printArray(freq, size);
//compares pos 0 with pos 1 to size-1, pos 1 with pos 2 to pos size-1 and so on
for (int i=0;i<size-1;i++)
{
for (int j=i+1; j<size;j++)
{
if (mindist>(abs(freq[i]-freq[j])))
{
mindist=abs(freq[i]-freq[j]);
}
}
}
printf("\nmindist=%d\n", mindist);
int check, closestfreq;
int shortdist = max-min; //there's no distance bigger than this
printf("Pick a frequency between %d and %d", min, max);
scanf("%d", &check);
//self explainatory
while (check < min || check > max)
{
printf("The chosen frequency is not in range\n
Pick a frequency between %d and %d", min, max);
scanf("%d", &check);
}
//checks every distance from check with each frequency in the array, finds the shortest one
//and saves that frequency.
for (int i=0; i<size; i++)
{
if (shortdist>abs(check-freq[i]))
{
shortdist = abs(check-freq[i]);
closestfreq = freq[i];
}
}
if (shortdist==0) //again, self explainatory
{
printf("The chosen frequency is in the list");
}
else
{
printf("Closest frequency to chosen is: %d", closestfreq);
}
return 0;
}
void fillArray(int array[],int size,int min,int max)
{
int new_random;
bool unico;
for (int i=0; i<size;i++)
{
do {
new_random = (rand() % (max+1-min)+min);
unico=1;
for (int j=0; j<i; j++)
{
if (new_random == array[j])
{
unico=0;
}
}
}
while (!unico);
array[i]= new_random;
}
}
void printArray(int array[],int size)
{
for (int i=0; i<size;i++)
{
printf("%d ", array[i]);
}
}
void sortArray (int array[], int size)
{
for (int j=0; j<size-1;j++)
{
for (int i=0; i<size-j-i;i++)
{
if (array[i]>array[i+1])
{
int t=array[i+1];
array[i+1]=array[i];
array[i]=t;
}
}
}
}
16
u/mikeblas 29d ago
Please properly format your code.
8
u/sreekotay 29d ago
the most generic fixes (aside from ... formattting yikes)?
sort the list first.
then binary search
3
u/alpicola 29d ago
After reformatting that code to make it legible, my first impression is that your code doesn't seem to fit the prompt. The program has two constraints and asks for three functions. I think the constraints are there, but I only see two functions and neither one seems to do any of the three things listed.
I would be looking for a function that has a prototype something like this:
int insertFreq(int array[], int size, int freq);That function would attempt to insert
freqinto the array. If successful,array[]is modified to include the given frequency and the function returns the index wherefreqwas added. If unsuccessful,array[]is not modified and the return value is-1. You could simply appendfreqto the end of the array, but as u/sreekotay is implying, there are advantages to keepingarray[]sorted, and the easiest way to do that is by inserting values new values in order. The rest of my comment is going to assume a sorted array.This function description feels a ambiguous to me. The exact distance between any two frequencies is simply
abs(freq1 - freq2), which isn't very interesting. Instead, I'm going to assume it means "given a frequencyfreq, find the minimum distance betweenfreqand any frequency inarray[]." The prototype for that function should look something like this:int findDistance(int array[], int size, int freq);This function would loop through
array[]until finding the first index wherearray[i] > freq. It would then determine whether freq is closer toarray[i], the first value greater than freq, orarray[i-1], the last value less than freq. It would also need to handle boundary conditions iffreq < array[0]orfreq > array[size-1]. The return value is the calculated distance.Once again, your function prototype is going to look something like this:
int findClosestFreq(int array[], int size, int freq);The fun thing about this function is that we've kind of already done this when implementing
findDistance(). Go ahead and recycle that logic.Finally, to answer your questions:
No, what you did is pretty inefficient. Your code has a lot of nested loops which are always a red flag from an efficiency perspective. You need them, sometimes, but seeing them should start you to thinking that there might be a better way to solve your problem. In this case, you can trade a little inefficiency when building
array[](keeping it sorted) for a big efficiency boost when you try to usearray[]later. Since data is usually read far more often than it's written, that's usually a good trade to make.If all of your code is in one file, you should use them whenever you are going to use a function that hasn't been implemented yet when reading your code from top to bottom.
Eventually, you are going to learn to separate code into different files. Once that happens, you will typically put prototypes for every (public) function in a header file (file extension
.h) and function implementations into a similarly named code file (file extension.c).1
u/ephemere_sloboda 29d ago
In main you can't invoke srand before declaring the variables. That would be valid in C++ but not in C.
The first assignment to mindist uses values in freq which have not been initialised yet.
You have sorted the array, you don't need a double loop to compare all frequencies with all other frequencies. You just need to compare adjacent elements, single loop.
The search for smallest distance is ok, again you have sorted the array so you could just stop (break) once freq[I] is higher than the input.
In general, I would try to follow the prompts more accurately. Number of elements is up to 15, not always 15. Start with an empty array (hint: you will need a separate variable to track how many elements are populated). Create a function that inserts a new element (checking uniqueness and range). Create another function that finds the minimum distance. Create another function that finds the closest frequency. In main, you invoke these functions.
1
u/Dazzling_Music_2411 29d ago
What's with the crazy vertical formatting? You don't really expect anyone to read that, do you?