DSA with java
//it is for adt in an array
import java.util.*;
class fa {
public static void main(String[] args) {
Scanner scan=new Scanner(System.in);
int []a=new int[100];
int n,i;
System.out.println("Enter no of elemnts in an array below 100:");
n=scan.nextInt();
System.out.println("Enter no of elements: ");
for (i=0;i<n;i++){
a[i]=scan.nextInt();
}
scan.close();
}
}
//insertion at particular index
// Online Java Compiler
// Use this editor to write, compile and run your Java code online
import java.util.*;
public class Array {
public static void main(String[] args) {
int[] a = new int[100];
int N, pos, ele, current;
Scanner scanner = new Scanner(System.in);
// Input size for the array
System.out.print("Enter the size of an array below 100: ");
N = scanner.nextInt();
// Input array elements
System.out.println("Enter array elements:");
for (int i = 0; i < N; i++) {
a[i] = scanner.nextInt();
}
// Input position to insert the value
System.out.print("Enter the position to insert the value: ");
pos = scanner.nextInt(); // 1-based index
// Input element to insert
System.out.print("Enter the element to insert: ");
ele = scanner.nextInt();
// Insert element
current = N;
for (int i = current; i >= pos; i--) {
a[i] = a[i - 1]; // Shift elements one position forward
}
a[pos ] = ele; // Insert the new element at the specified position
current++; // Update the current size
// Print the updated array
System.out.println("Updated array:");
for (int i = 0; i < current; i++) {
System.out.print(a[i] + " ");
}
}
}
//o/p is:
Enter the size of an array below 100: 4
Enter array elements:
1
2
3
4
Enter the position to insert the value: 4
Enter the element to insert: 5
Updated array:
1 2 3 4 5
Comments
Post a Comment