I got an assignment yesterday that goes as follows: Generate and show 20 random numbers in the range [100,120]. Then write all numbers in this range that haven't been chosen in ascending order. My solution works but there's a problem. The program breaks when I remove the braces from the constant LENGTH. I'm talking about the line with the arrow (<---) For some reason the rand starts generating negative numbers when I do. Why does this happen? Removing the const and working with a normal variable "length" also works.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define MIN 100
#define MAX 120
#define LENGTH MAX - MIN + 1
//Range is [MIN, MAX]
void write_arr(int const arr[], int amount)
{
int i;
for (i = 0; i < amount; i++) {
printf("%-3d ", arr[i]);
}
printf("\n");
}
int main()
{
srand(time(NULL));
int numbers[MAX - MIN];
int i;
for (i = 0; i < LENGTH; i++) {
numbers[i] = i + MIN;
}
//write_arr(numbers, LENGTH);
///Now remove 20 random numbers -> We do this by setting the value of a number to something that can't occur normally (MIN-1)
for (i = 0; i < LENGTH; i++) {
int delete = rand() % (LENGTH); //<----------------- I can't remove these braces
printf("%3d ", delete + MIN);
numbers[delete] = MIN - 1;
}
printf("\n");
//Now write all numbers that still have a valid value
for (i = 0; i < LENGTH; i++) {
if (numbers[i] != MIN - 1) {
printf("%-3d ", numbers[i]);
}
}
printf("\n");
return 0;
}