In: Computer Science
6. Write a Java program to rotate an array (length 3) of
integers in left direction
7. Write a Java program to store a collection of integers, sort
them in ascending order and print the sorted integers.
Answer 6 ;
JAVA PROGRAM TO ROTATE AN ARRAY(LENGTH 3) OF INTEGERS IN LEFT DIRECTION.
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("Enter array elements (length 3): ");
int arr[] =new int[3] ;
for(int i=0;i<3;i++)
{
int n=sc.nextInt();
arr[i]=n;
}
//rotate array of integers in left direction.
int temp=arr[0];
arr[0]=arr[1];
arr[1]=arr[2];
arr[2]=temp;
//printing the rotated elements of an array.
System.out.println("After rotation of an array in left direction: ");
for(int i=0;i<3;i++)
System.out.print(arr[i]+" ");
}
}
EXAMPLE :
Answer 7 ;
JAVA PROGRAM TO STORE A COLLECTION OF INTEGERS , SORT THEM IN ASCENDING ORDER AND PRINT THE SORTED INTEGERS.
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("Enter size of the collection of the integers: "); int n = sc.nextInt(); System.out.println("Enter the elements: "); int arr[]=new int[n]; //storing a collection of integers. for(int i=0;i<n;i++) { int element=sc.nextInt(); arr[i]=element; } //sorting them in ascending order. int len = arr.length; for (int i = 0; i < len-1; i++) { for (int j = 0; j < len - i - 1; j++) { if (arr[j] > arr[j + 1]) { // swap temp and arr[i] int temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; } } } //printing the sorted integers. System.out.println("Sorted integers in ascending order: "); for(int i=0;i<n;i++) System.out.print(arr[i]+" "); } }
EXAMPLE :