OneBite.Dev - Coding blog in a bite size

shuffle the elements in an array in C

Code snippet on how to shuffle the elements in an array in C

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
 
int main(int argc, char * argv[]) {
 
    int array[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    int index, temp;
 
    srand(time(NULL));
 
    for (int i = 0; i < 10; i++) {
        index = rand() % 10;
        temp = array[i];
        array[i] = array[index];
        array[index] = temp;
    }
 
    for (int i = 0; i < 10; i++) {
        printf("%d\n", array[i]);
    }
 
    return 0;
}

This code shuffles the elements in an array of size 10. First, it initializes an array of 10 elements, with values from 1-10. It then seeds the random number generator with the current system time. In a loop, it assigns a random index from 0-9 to the variable index. It then stores the value of the element at the current index in a variable called temp. Next, it swaps the element at the current index with the element at the given random index. The loop iterates 10 times and shuffles the elements in the array. Finally, the elements in the array are printed to the console.

c