-
-
Notifications
You must be signed in to change notification settings - Fork 4.4k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
A shorter and simple understandable code...
- Loading branch information
1 parent
e5dad3f
commit 1c042cb
Showing
1 changed file
with
13 additions
and
29 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,36 +1,20 @@ | ||
#include <stdio.h> | ||
#include <stdlib.h> | ||
|
||
int linearsearch(int *arr, int size, int val) | ||
{ | ||
int i; | ||
for (i = 0; i < size; i++) | ||
{ | ||
if (arr[i] == val) | ||
return 1; | ||
} | ||
return 0; | ||
int search(int array[], int n, int x) { | ||
|
||
// Going through array sequencially | ||
for (int i = 0; i < n; i++) | ||
if (array[i] == x) | ||
return i; | ||
return -1; | ||
} | ||
|
||
int main() | ||
{ | ||
int n, i, v; | ||
printf("Enter the size of the array:\n"); | ||
scanf("%d", &n); // Taking input for the size of Array | ||
int main() { | ||
int array[] = {2, 4, 0, 1, 9}; | ||
int x = 1; | ||
int n = sizeof(array) / sizeof(array[0]); | ||
|
||
int *a = (int *)malloc(n * sizeof(int)); | ||
printf("Enter the contents for an array of size %d:\n", n); | ||
for (i = 0; i < n; i++) | ||
scanf("%d", &a[i]); // accepts the values of array elements until the | ||
// loop terminates// | ||
int result = search(array, n, x); | ||
|
||
printf("Enter the value to be searched:\n"); | ||
scanf("%d", &v); // Taking input the value to be searched | ||
if (linearsearch(a, n, v)) | ||
printf("Value %d is in the array.\n", v); | ||
else | ||
printf("Value %d is not in the array.\n", v); | ||
|
||
free(a); | ||
return 0; | ||
(result == -1) ? printf("Element not found") : printf("Element found at index: %d", result); | ||
} |