Array exercise 1
Wed May 25 2022 20:19:07 GMT+0000 (Coordinated Universal Time)
Saved by
@ahmed_salam21
/*Write a JAVA a program to
▪ Input 5 data elements (10 , 20 , 30 , 40 , 50)
▪ Search for number 30
▪ Delete number 30
▪ Display elements before and after deletion
*/
package com.Data_Structures_Learn;
public class Main {
public static void main(String[] args) {
int i , j ;
int searchKey = 30;
int noOfElements = 5 ;
int[] arr = new int[noOfElements];
arr[0] = 10 ;
arr[1] = 20 ;
arr[2] = 30 ;
arr[3] = 40 ;
arr[4] = 50 ;
// print elements
for(i = 0 ; i < noOfElements ; i++)
System.out.print(arr[i] + " ");
// search for 30
for( i = 0 ; i < noOfElements; i++) {
if (arr[i] == searchKey) { // it could find it
System.out.println("Found" + searchKey);
break;
}
if (i == noOfElements ) // reached to the final element without finding it
System.out.println("Can't find" + searchKey);
}
// Delete 30
for( i = 0 ; i < noOfElements ; i++) { // look for it
if (arr[i] == searchKey)
break;
}
for( j = i ; j < noOfElements ; j++) {
arr[j] = arr[j + 1]; // move elements up
}
noOfElements-- ; // decrease size of array by 1
// print elements after deletion
for( i = 0 ; i < noOfElements ; i++)
System.out.print(arr[i] + " ");
}
}
/* Output : 10 20 30 40 50
Found 30
10 20 40 50
*/
content_copyCOPY
Comments