In: Computer Science
1. Write a program that includes a function search() that finds the index of the first
element of an input array that contains the value specified. n is the size of the array. If
no element of the array contains the value, then the function should return -1. Name your
program .C The program takes an int array, the number of elements in the array,
and the value that it searches for. The main function takes input, calls the
search()function, and displays the output.
int search(int a[], int n, int value);
Example input/output #1:
Enter the length of the array: 4
Enter the elements of the array: 8 2 3 9
Enter the value for searching: 3
Output: 2
Example input/output #2:
Enter the length of the array: 6
Enter the elements of the array: 4 7 1 0 3 9
Enter the value for searching: 5
Output: -1
2. Modify the part 1 program so that it deletes all instances of the value from the array. As
part of the solution, write and call the function delete() with the following
prototype. n is the size of the array. The function returns the new size of the array after
deletion (The array after deletion will be the same size as before but the actual elements
are the elements from index 0 to new_size-1). In writing function delete(), you may
include calls to function search(). The main function takes input, calls the
delete()function, and displays the output. Name your program .C
int delete(int a[], int n, int value);
Example input/output #1:
Enter the length of the array: 6
Enter the elements of the array: 4 3 1 0 3 9
Enter the value for deleting: 3
Output array:
4 1 0 9
#include<stdio.h>
int search(int a[],int n,int value){
int i;
for(i = 0; i < n; i++){
if(a[i] == value){
return i;
}
}
return -1;
}
int delete(int a[],int n,int value){
int shift = 0;;
int removed = 0;
int i;
for ( i = 0; i < n; i++)
{
if (search(a,n,value)!=-1)
{
removed++;
}
else
{
a[shift++] = a[i];
}
}
return (n - removed);
}
int main(){
int arr[100],i,size;
int value;
printf("Enter the length of the array: ");
scanf("%d",&size);
printf("Enter the elements of the array: ");
for(i = 0; i < size; i++)
scanf("%d",&arr[i]);
printf("Enter the value for searching: ");
scanf("%d",&value);
printf("Output: %d",search(arr,size,value));
}
/* OUTPUT */
Ans 2)
#include<stdio.h>
int delete(int a[],int n,int value){
int shift = 0;;
int removed = 0;
int i;
for ( i = 0; i < n; i++)
{
if (a[i] == value)
{
removed++;
}
else
{
a[shift++] = a[i];
}
}
return (n - removed);
}
int main(){
int arr[100],i,size;
int value;
printf("Enter the length of the array: ");
scanf("%d",&size);
printf("Enter the elements of the array: ");
for(i = 0; i < size; i++)
scanf("%d",&arr[i]);
printf("Enter the value for deleting: ");
scanf("%d",&value);
size = delete(arr,size,value);
printf("Output array: \n");
for(i = 0 ; i < size; i++){
printf("%d ",arr[i]);
}
}