Q:

Java Program to Insert Element in Array

private static int i;

    public static void main(String[] args) 
    {
        int n,num1,num3;
        int arr[] = new int[50];

        Scanner scan = new Scanner(System.in);

        System.out.print("Enter number you want in array:");
        n = scan.nextInt();
        int a[] = new int[n];
        System.out.println("Enter any number:");
        for (int i = 0; i < n; i++) 
        {
            a[i] = scan.nextInt();
        }
        for (int i = 0; i < n; i++) 
        {
            for (int num = i + 1; num < n; num++) 
            {
                if (a[i] > a[num]) 
                {
                    num1 = a[i];
                    a[i] = a[num];
                    a[num] = num1;
                }
            }
        }

        System.out.print("Ascending Order:");
        for (int i = 0; i < n - 1; i++) 
        {
            System.out.print(a[i] + ",");
        }
        System.out.println(a[n-1]);

        System.out.println("Enter Last number:" );
        num1= scan.nextInt();

        System.out.print("New Array Position: ");
        for(i=0; i<n+1; i++)
        {
            System.out.print(arr[i] + " ");

        }
    }
}

Output:
Enter number you want in array:5
Enter any number: 5 2 3 1
Ascending Order: 1 2 3 5
Enter last number: 4
New Array Position: 0 0 0 0 

it should be like this 1 2 3 4 5 can guys help me thanks

A:

Couple of things:
1.While printing arr[i] in the last for loop, you have never touched array arr after declaration 
i.e. int arr[] = new int[50]; Therefore, output  0 0 0 0 is as expected.
2.After reading the last number i.e. num1= scan.nextInt();, you have not used it anywhere moving forward. How do you think you array will come to know about the last element which is to be added ? :)
Something of this sort will work:
1.After sorting array a, copy it into array arr:
for(int i=0;i<n;i++){
    arr[i] = a[i];
}

2.Once you have all the old elements in array arr, read last element in array arr i.e. arr[n+1] = scan.nextInt();
3.Here you can again sort the array arr to take last element to the appropriate place.
4.Print array arr:
for(int j=0;j<n+1;j++){
System.out.print(arr[j]+" ");
}

NOTE: Make sure your n is less than 50. Otherwise you will run into java.lang.ArrayIndexOutOfBoundsException

