In C programming language: We often need to shuffle data in many applications. C
ID: 674925 • Letter: I
Question
In C programming language:
We often need to shuffle data in many applications. Consider a case of a game that plays cards for example or a system that does a draw for lottery. The purpose of this lab is to write functions that will help us shuffle elements of an array.
Create a function that takes an array of integers and its size as parameters and populates the array with the values: 0, 1, 2, ..., size-1, where size is the size of the array.
Create a function that takes an array of integers and two indices (integers) and swaps the two elements. For example if I pass the array and 3 and 7 then the array will swap the element at index 3 with the element at index 7.
Create a function that takes an array of integers and its size as parameters and shuffles the array. You can accomplish this by going through the elements and exchanging each one with a randomly selected element (hint: use the method you created in step 2.
Create a function that takes an array of integers, its size and a value as parameters and returns the index at which the value is stored. If the array doesn't contain the value then the function returns -1. For example if the array is 1 4 6 2 10 11 12 and the value is 11 then the function returns 5 because 11 is stored at index 5. If the value is 20 then the function returns -1 because 20 is not in the array.
Create a function that takes an array of integers and its size as parameters and prints the contents of the array.
In main write code to test your function. Namely, creates an array of 15 integers, populate it, print it, shuffle it, print it again and print the index of an element in the array and the index of an element not in array .
Here is sample output:
Explanation / Answer
#include<stdio.h>
#include <stdlib.h>
void swap(int* a,int s1,int s2){
int temp;
temp = a[s1];
a[s1] = a[s2];
a[s2] = temp;
}
int main(){
int a[10],i,n,index = -1;
for(i = 0; i < 10; i++)
scanf("%d",&a[i]);
for(i = 0; i < 10; i++)
swap(&a,i,rand()%10);
printf("Enter a number to search? ");
scanf("%d",&n);
for(i = 0; i < 10; i++)
{
if(a[i] == n)
index = i;
}
printf("%d is found at index %d",n,index);
return 0;
}