Assignment: Module 03- Part 01
![]() |
Assignment: Module 03- Part 01 |
Input:
Enter the array size 3
Enter the elements 12, 7, 34
Enter the no to perform function
1-->ascending
2-->descending
1. Ascending order is:7
Ascending order is:12
Ascending order is:34
Input:
Enter the array size 3
Enter the elements 23, 1, 77
Enter the no to perform function
1-->ascending
2-->descending
2. Descending order is:77
Descending order is:23
Descending order is:1
import java.util.Scanner;
public class AscendingArray {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter the array size: ");
int size = input.nextInt();
int[] arr = new int[size];
System.out.println("Enter the elements: ");
for (int i = 0; i < size; i++) {
arr[i] = input.nextInt();
}
System.out.println("Enter the number to perform function: ");
System.out.println("1-->ascending");
System.out.println("2-->descending");
int choice = input.nextInt();
if (choice == 1) {
// sort array in ascending order
for (int i = 0; i < size; i++) {
for (int j = i + 1; j < size; j++) {
if (arr[i] > arr[j]) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
//print the array in ascending order
System.out.println("Ascending order is:");
for (int i = 0; i < size; i++) {
System.out.println(arr[i]);
}
} else if (choice == 2) {
// sort array in descending order
for (int i = 0; i < size; i++) {
for (int j = i + 1; j < size; j++) {
if (arr[i] < arr[j]) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
//print the array in descending order
System.out.println("Descending order is:");
for (int i = 0; i < size; i++) {
System.out.println(arr[i]);
}
}
}
}
This is an example of a simple class that sorts an array using control structures. The user inputs the size of the array and the elements, and then chooses whether to sort the array in ascending or descending order. The program uses nested loops and a temporary variable to sort the array, and then prints the sorted array to the console.