In: Computer Science
Write a Java Program that can:
The code must have four separate methods for each task stated above.
Do not use any pre-defined Java functions.
You are free to use int or String data-type for the array.
import java.io.*;
import java.lang.*;
import java.util.*;
public class Allmethods {
public static int[] addX(int n, int arr[], int
x)
{
int i;
int newarr[] = new int[n +
1];
for (i = 0; i < n; i++)
newarr[i] =
arr[i];
newarr[n] = x;
return newarr;
}
public static int[] delX(int n,int a[],int x)
{
int flag =1,loc=0;
for (int i = 0; i < n; i++)
{
if(a[i] == x)
{
flag =1;
loc = i;
break;
}
else
{
flag = 0;
}
}
if(flag == 1)
{
for(int i = loc+1; i < n; i++)
{
a[i-1] = a[i];
}
return a;
}
return a;
}
public static int search(int arr[],int n,int toSearch)
{
int found = 0,i;
for(i=0; i<n; i++)
{
if(arr[i] == toSearch)
{
found = 1;
break;
}
}
System.out.println("\n\nSearch Method for Above Array
is:\n");
if(found == 1)
{
System.out.println(toSearch + " is found "+"at position "+(i +
1));
}
else
{
System.out.println(toSearch + " is not found ");
}
return 0;
}
public static int[] replace(int arr[],int n,int elem,int
replace)
{
for(int i=0;i<n;i++)
{
if(arr[i]==replace)
{
arr[i] = elem;
}
}
return arr;
}
public static void main(String[] args)
{
int n = 10;
int i;
int arr[]
= { 1, 2, 3, 4,
5, 6, 7, 8, 9, 10 };
System.out.println("Initial
Array:\n");
for(i=0;i<n;i++)
{
System.out.print(arr[i]+" ");
}
int x = 50;
arr = addX(n, arr, x);
System.out.println("\n");
System.out.println("Array with " +
x + " added:\n");
for(i=0;i<n+1;i++)
{
System.out.print(arr[i]+" ");
}
int elem = 10;
int xarr[] = new
int[arr.length-1];
xarr =
delX(arr.length,arr,elem);
System.out.println("\n\nArray after
deleting element "+elem + " is\n");
for(i=0;i<xarr.length-1;i++)
{
System.out.print(xarr[i]+"
");
}
int parr[] = { 1, 2, 3, 4, 5, 6, 7,
8, 9, 10,50 };
int toSearch = 50;
System.out.println("\n\nElements in
an array:\n");
for(i=0;i<parr.length;i++)
{
System.out.print(parr[i]+"
");
}
search(parr,parr.length,toSearch);
int arr1[] = { 1, 2, 3, 4, 5, 6, 7,
8, 9, 10 };
int replace = 3;
int elem1 = 45;
System.out.println("\n\nElements in
an array:\n");
for(i=0;i<arr1.length;i++)
{
System.out.print(arr1[i]+"
");
}
arr1 =
replace(arr1,arr1.length,elem1,replace);
System.out.println("\n\nArray after
replacing element "+replace +" with element "+elem1+" is\n");
for(i=0;i<arr1.length;i++)
{
System.out.print(arr1[i]+"
");
}
}
}