0
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[]) {  
    srand(time(NULL));
    int i = 0;
    int dizi[20];

    for (i = 0; i < 20; i++) {
        dizi[i] = rand() % 20;
    }   

    for (i = 0; i < 20; i++) {
        printf("%d\n", dizi[i]);
    }   
    
    return 0;
}

Is the if else structure sufficient to solve this problem or do I need to do something about the rand function?

Chris
  • 26,361
  • 5
  • 21
  • 42

1 Answers1

-1

If you want to fill a 20 element array with random numbers from 0 to 19 without repetition, then fill them with 0 to 19 normally, then randomly swap indices.

#include <stdlib.h>
#include <time.h>
#include <stdio.h>

#define N 20

int main(void) {
    srand(time(NULL));

    int arr[N];
    for (size_t i = 0; i < N; i++) {
        arr[i] = i;
    }

    for (size_t i = 0; i < N; i++) {
        int r1 = rand() % N;
        int r2 = rand() % N;
        int temp = arr[r1];
        arr[r1] = arr[r2];
        arr[r2] = temp;
    }

    for (size_t i = 0; i < N; i++) {
        printf("%d\n", arr[i]);
    }
}

https://godbolt.org/z/avKGozfoh

As pointed out in comments, the above represents a naive algorithm. Using a hopefully faithful implementation of the Knuth/Fisher-Yates algorithm, we get an even distribution of results.

#include <stdlib.h>
#include <time.h>
#include <stdio.h>

#define N 20

int main(void) {
    srand(time(NULL));

    int arr[N];
    for (size_t i = 0; i < N; i++) {
        arr[i] = i;
    }

    for (size_t i = 0; i < N; i++) {
        size_t j = rand() % (N - i) + i;
        int temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }

    for (size_t i = 0; i < N; i++) {
        printf("%d\n", arr[i]);
    }
}

https://godbolt.org/z/qsfYa8r54

Chris
  • 26,361
  • 5
  • 21
  • 42