r/C_Programming • • 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;
      }
    }
  }
}    
0 Upvotes

14 comments sorted by

16

u/mikeblas 29d ago

Please properly format your code.

3

u/PaninoInfernale1551 28d ago edited 28d ago

i just realized that while pasting the code it got messed up. I dont know how to properly paste it as it doesnt allow to send screenshots of the code. I fixed it, give me another chance :)

2

u/mikeblas 28d ago

Instructions for formatting code are not hard to find.

8

u/sreekotay 29d ago

the most generic fixes (aside from ... formattting yikes)?

sort the list first.
then binary search

2

u/PaninoInfernale1551 28d ago

code got messed up while pasting it. i'll work on the other 2. thank you

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.

insertion with double check (range + uniqueness)

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 freq into the array. If successful, array[] is modified to include the given frequency and the function returns the index where freq was added. If unsuccessful, array[] is not modified and the return value is -1. You could simply append freq to the end of the array, but as u/sreekotay is implying, there are advantages to keeping array[] 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.

function that calculates the minimum distance between two frequencies

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 frequency freq, find the minimum distance between freq and any frequency in array[]." 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 where array[i] > freq. It would then determine whether freq is closer to array[i], the first value greater than freq, or array[i-1], the last value less than freq. It would also need to handle boundary conditions if freq < array[0] or freq > array[size-1]. The return value is the calculated distance.

function that identifies the frequency closest to a given value

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:

is it efficient?

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 use array[] later. Since data is usually read far more often than it's written, that's usually a good trade to make.

I also used prototype functions and didnt where i could've, when should and shouldn't i use them?

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/PaninoInfernale1551 28d ago edited 28d ago

First of all, thank you for the detailed comment.

I kind of forgot about the first function, xd. I was so focused on the other two, since they were more complex, that I just made a "temp" array fill function to save time instead of inserting values each time. I'll add it, it should be simple.

About adding the values in order into the array: that's true, but I'd rather sort the array in case someone (including me) doesn't do that.

For the other functions, I realized—also by reading the other comments—that I can just compare the values array[i] and instead of comparing each possible combination of frequencies, so that's definitely fewer loops.

"The exact distance between... Instead, I'm going to assume it means" I'm sorry, but no, the second function asked exactly the min distance existing between two freqs in the array, so ideally comparing every combination of freqs and finding the shortest distance.

I know the prompts don't seem interesting or hard to make, but again, we just started and this isn't an advanced C class. The exercise prior (or two) to this one was basically "given an array, find the two largest numbers and sum them", so again, nothing special.

I'll definitely keep all of this in mind from now on, so again, thank you very much for your time and effort in explaining this to me.

There are two last things I don't understand: how do I format code? And how do I see / hypothesize that code is inefficient? Most of the time, nested loops seem like the most obvious answer.

1

u/PaninoInfernale1551 28d ago

nevermind... i just realized that while pasting the code it got messed up. I dont know how to properly paste it as it doesnt allow to send screenshots of the code

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/PaninoInfernale1551 28d ago

Yeah, I was more focused on understanding the required functions and the logic behind them that I started experimenting so much (also with stuff unrelated to this exercise) that I got off track.
I ignored the first function and made, like, 5 versions of the required ones.
Also i just realized that pasting the code in here messed it all up with unnecessary spaces and stuff... I fixed it. The "new" code is how i originally wrote it

1

u/SmokeMuch7356 29d ago

I n   main   you can't invoke srand before declaring the variables. That would be valid in C++ but not in C.

It's valid as of C99.  Unless the OP is limited to a C89 compiler it's not a problem.

1

u/ephemere_sloboda 29d ago

Man now I feel old...

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?

1

u/PaninoInfernale1551 28d ago edited 28d ago

i just realized that it's was a mistake while pasting the code here and looks way better in reality. I fixed it, give me another chance :)