In C, you can shuffle an array using the Fisher-Yates shuffle algorithm.
In this example,
intArray
containing integers.intArray
.#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void shuffleArray(int array[], int n) {
srand(time(NULL));
for (int i = n - 1; i > 0; i--) {
int j = rand() % (i + 1);
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
int main() {
int intArray[] = {1, 2, 3, 4, 5};
int n = sizeof(intArray) / sizeof(int);
shuffleArray(intArray, n);
printf("Shuffled Array: ");
for (int i = 0; i < n; i++) {
printf("%d ", intArray[i]);
}
return 0;
}
Shuffled Array: 5 2 3 4 1
In this example,
strArray
containing strings.strArray
.#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
void shuffleArray(char *array[], int n) {
srand(time(NULL));
for (int i = n - 1; i > 0; i--) {
int j = rand() % (i + 1);
char *temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
int main() {
char *strArray[] = {"apple", "banana", "cherry"};
int n = sizeof(strArray) / sizeof(strArray[0]);
shuffleArray(strArray, n);
printf("Shuffled Array: ");
for (int i = 0; i < n; i++) {
printf("%s ", strArray[i]);
}
return 0;
}
Shuffled Array: banana cherry apple
In this tutorial, we learned How to Shuffle an Array in C language with well detailed examples.