r/C_Programming • u/MycologistIll1355 • Jul 17 '26
First real C project
Hello everyone! This is my first real C project and I would like some feedback on what I can improve. It's my first attempt at a sorting algorithm (selection sort) and it is 100% AI free.
#include <stdio.h>
int main() {
int num_len;
printf("How many numbers to sort?\n");
scanf("%d", &num_len);
int numbers[num_len];
printf("which numbers?\n");
for (int i = 0; i < num_len; i++) {
scanf("%d", &numbers[i]);
}
for (int i = 0; i < num_len-1; i++) {
int iMin = i;
for(int j = i+1; j < num_len; j++) {
if(numbers[j] < numbers[iMin]) {
iMin = j;
}
}
if(iMin != i) {
int temp = numbers[i];
numbers[i] = numbers[iMin];
numbers[iMin] = temp;
}
}
for (int i = 0; i < num_len; i++) {
printf("%d", numbers[i]);
printf(" ");
}
printf("\n");
}
24
Upvotes
10
u/Thesk790 Jul 17 '26
You can generate pseudo-random numbers with
rand, which uses a seed, that you set withsrand(time(NULL)), and everytime you run the program it will generates pseudo-random numbers. You can use a loop and use only the count of the user, print the numbers unordered and then ordered.2
u/SmokeMuch7356 Jul 18 '26
Good job! The next step would be to put the sorting routine into its own function; that way you could sort multiple different arrays.
The next step after that would be figuring out how to specify different sorting orders - ascending, descending, ASCIIbetical, etc. Read up on the qsort library function for one way to do that (although function pointers may be a bit cryptic for where you are right now).
1
u/Interesting_Buy_3969 Jul 18 '26 edited Jul 18 '26
I've just read first 5 lines or so, and the first thing I immediately want to fix:
Thus you allow the user to make a stack overflow easily because
num_lenis only limited byint's representation - usually 232 - 1. Create a constant which the array size cannot exceed and accept numbers from user properly, like that:so that the VLA is unlikely to cause stack overflow.
1
u/cdtrmnbaell Jul 23 '26
Great ! Try to build Bank management , library management.