I created two files for displaying and reading data separately and included them in my main file which is for sorting it. But when I execute the main program the data is not displayed but the function is being called.
#include <stdio.h>
#include <stdlib.h>
#include "arrdisp.c"
#include "arrread.c"
void selsort(int arr[]);
int random(int min, int max);
int n;
void main() {
int a[10], i;
char ch;
printf("Do you want to insert student marks manually?(y/n):");
scanf("%c", &ch);
if (ch == 'y') {
read(a, n);
for (i = 0; i < n; i++) printf("%d, ", a[i]);
} else {
printf("How many random marks do you want to insert:");
scanf("%d", &n);
for (i = 0; i < n; i++) a[i] = random(0, 100);
}
printf("before sorting:\n");
disp(a, n);
printf("\nAfter sorting:\n");
selsort(a);
disp(a, n);
printf("Array elements");
for (i = 0; i < n; i++) printf("%d, ", a[i]);
}
int random(int min, int max) {
return min + rand() / (RAND_MAX / (max - min + 1) + 1);
}
void swap(int *xp, int *yp) {
int temp = *xp;
*xp = *yp;
*yp = temp;
}
void selsort(int arr[]) {
int i, j, min_idx;
for (i = 0; i < n - 1; i++) {
min_idx = i;
for (j = i + 1; j < n; j++)
if (arr[j] < arr[min_idx]) min_idx = j;
if (min_idx != i) swap(&arr[min_idx], &arr[i]);
}
}
Can anyone explain what's going wrong?
I tried making the array extern variable and got some error in the main program itself saying that the array is undefined. So I tried defining normal functions in the same program and still had the same output, so I don't think it's a problem with the header file but I'm still clueless.
You're not initializing n
, so your display loops will not work because a non initialized int
variable will get zero.
The only place I see you initialize n
is in your else statement, which will not be accessed if the user chooses y
.
Ask the user to input 'n':
printf("Do you want to insert student marks manually?(y/n):");
scanf("%c",&ch);
if(ch == 'y')
{
printf("How many students:");
scanf("%d", &n);
read(a, n);
for (i = 0; i < n; i++)
printf("%d, ", a[i]);
}