SAVITIBAI PHULE UNIVERSITY OF PUNE
S. Y. B.Sc. (Computer Science) Semester III
Practical Examination
SUBJECT: CS-233 Practical course based on CS231
/*
Q.1 Create a random array of n integers. Accept a value x from user and use linear search algorithm to check whether the number is present in the array or not and output the position if the number is present.
*/
#include<stdio.h>
#include<stdlib.h>
#define MAX 100
// CheckFor: Create new Array
void CreateArray(int A[], int n){
// CheckFor: Declaration of local variable
int i = 0;
// LoopFor: Assingn the random array elements
for ( i = 0; i < n; i++)
A[i] = rand();
}
// CheckFor: Display the Array
void DisplayArray(int A[], int n){
// CheckFor: Declaration of local variable
int i = 0;
// LoopFor: Display the array elements
for ( i = 0; i < n; i++)
printf("%d \t", A[i]);
}
// CheckFor: Search the Array Element using Linear Search Algorithm
void LinearSearch(int A[], int n, int key){
// CheckFor: Declaration of local variable
int i = 0, flag = 0;
// LoopFor: Moving the Array from first to last element
for ( i = 0; i < n; i++){
// CheckFor: Key element match into the Array elements
// if Match then print the message
if ( key == A[i]){
flag = 1;
break;
}
}
// CheckFor: Key element does not found in Array
if (flag == 1)
printf("\n\nThe %d element search at %d position in Array", key, i+1);
else
printf("\n %d element not found in Array\n", key);
}
int main(){
int A[MAX], num = 0, key = 0;
// Accept the n number from user
printf("Enter How many element we want to in array: ");
scanf("%d", &num);
// create n random element array
CreateArray(A, num);
// Display the given array
printf("\n\nThe given array elements are: \n\n");
DisplayArray(A, num);
// Sort the element using insertion sort algorithm
printf("\n\nAccept a value x from user we want to search in array: ");
scanf("%d", &key);
LinearSearch(A, num, key);
printf("\n\n");
system("pause");
return 0;
}
No comments:
Post a Comment